Source code for fleetmesh_auth.plugin_testing

"""Conformance checks for provider plugins, for a plugin's own test suite.

    from fleetmesh_auth.plugin_testing import check_provider

    class Conformance(unittest.TestCase):
        def test_standard(self):
            check_provider(MyProvider)

`check_provider` takes the plugin class (or factory) as its entry point
names it, builds it the way the engine does, and raises AssertionError
naming the first rule it breaks. It checks the declaration, that `describe()`
is public JSON, that bad and empty credentials fail with an error code and do
not raise, that `register({})` and (when offered) `check_handle` answer
cleanly, and that the engine routes the plugin's own tokens to it.
"""
from __future__ import annotations

import json
from typing import Any, Mapping, Optional

from fleetmesh_auth.plugins import build
from fleetmesh_auth.providers.base import HANDLE_CHECK_REASONS, PROVIDER_ID, AuthProviderPlugin

FIELD_TYPES = ("text", "password")


def _fail(provider_id: str, msg: str) -> None:
    raise AssertionError(f"provider {provider_id!r}: {msg}")


[docs]def check_provider(plugin: Any, environ: Optional[Mapping[str, str]] = None) -> AuthProviderPlugin: """Build `plugin` as the engine would and check it against the standard. Returns the built provider.""" provider = build(plugin, environ if environ is not None else {}) pid = provider.provider_id if not PROVIDER_ID.fullmatch(pid): _fail(pid, f"provider_id must match {PROVIDER_ID.pattern}") if not provider.display_name or provider.display_name == AuthProviderPlugin.display_name: _fail(pid, "set display_name") if not provider.supported_methods: _fail(pid, "declare supported_methods") for prefix in provider.token_prefixes: if not prefix or not prefix.endswith("_"): _fail(pid, f"token prefix {prefix!r} should end in '_', like 'fmk_'") if prefix in ("fmpass_", "fmauth_"): _fail(pid, f"token prefix {prefix!r} belongs to fleetmesh-auth") form = provider.login_form if form is not None: fields = form.get("fields") or [] if not fields: _fail(pid, "a login_form needs fields") names = [f.get("name") for f in fields] if len(set(names)) != len(names) or not all(names): _fail(pid, "login_form field names must be present and unique") if "provider" in names or "auth_method" in names: _fail(pid, "login_form fields cannot be named provider or auth_method") for f in fields: if f.get("type", "text") not in FIELD_TYPES: _fail(pid, f"field {f.get('name')!r} type must be one of {FIELD_TYPES}") if "service_login" not in provider.supported_methods: _fail(pid, "a provider with a login_form accepts the service_login method") desc = provider.describe() try: json.dumps(desc) except (TypeError, ValueError) as exc: _fail(pid, f"describe() must be JSON-serialisable ({exc})") if desc.get("provider_id") != pid: _fail(pid, "describe() must carry its provider_id") for key in desc: if any(word in key.lower() for word in ("secret", "password", "private")): _fail(pid, f"describe() is public; drop {key!r}") context: dict[str, Any] = {"web_auth": None, "host": None, "directory": None, "domain": "conformance.test", "app_preset": "standard", "allow_any_sovereign_key": False} probes = [{}, {"auth_method": "service_login"}, {"auth_method": "service_login", "username": "nobody", "password": "wrong"}] probes += [{"auth_method": "token", "token": prefix + "not-a-real-token"} for prefix in provider.token_prefixes] for payload in probes: try: res = provider.authenticate(dict(payload), context) except Exception as exc: # noqa: BLE001 _fail(pid, f"authenticate({payload}) raised {type(exc).__name__}: {exc}; return ok False instead") if not isinstance(res, dict) or res.get("ok") is not False or not res.get("error"): _fail(pid, f"authenticate({payload}) must return {{'ok': False, 'error': code}}, got {res!r}") # Registration: optional, but the hook must refuse cleanly (never raise) # for an empty body, and a provider declaring a register_form has to # actually implement register. rform = provider.register_form if rform is not None: rfields = rform.get("fields") or [] if not rfields: _fail(pid, "a register_form needs fields") rnames = [f.get("name") for f in rfields] if len(set(rnames)) != len(rnames) or not all(rnames): _fail(pid, "register_form field names must be present and unique") if "provider" in rnames or "auth_method" in rnames: _fail(pid, "register_form fields cannot be named provider or auth_method") for f in rfields: if f.get("type", "text") not in FIELD_TYPES: _fail(pid, f"register field {f.get('name')!r} type must be one of {FIELD_TYPES}") if type(provider).register is AuthProviderPlugin.register: _fail(pid, "a provider with a register_form implements register()") try: rres = provider.register({}, context) except Exception as exc: # noqa: BLE001 _fail(pid, f"register({{}}) raised {type(exc).__name__}: {exc}; return ok False instead") if not isinstance(rres, dict) or rres.get("ok") is not False or not rres.get("error"): _fail(pid, f"register({{}}) must return {{'ok': False, 'error': code}}, got {rres!r}") if desc.get("supports_registration") != provider.supports_registration(): _fail(pid, "describe() must carry supports_registration") # Handle check: optional; when offered, it answers the engine's shape # for a free-looking handle and for a too-short one, and never raises. if desc.get("supports_handle_check") != provider.supports_handle_check(): _fail(pid, "describe() must carry supports_handle_check") if provider.supports_handle_check(): for probe in ("conformance-probe-no-such-handle", "x"): hres: Any = None try: hres = provider.check_handle(probe) except Exception as exc: # noqa: BLE001 _fail(pid, f"check_handle({probe!r}) raised {type(exc).__name__}: {exc}; return a dict instead") if not isinstance(hres, dict) or "ok" not in hres: _fail(pid, f"check_handle({probe!r}) must return a dict with ok, got {hres!r}") if hres.get("ok"): if not isinstance(hres.get("available"), bool): _fail(pid, f"check_handle({probe!r}) must carry a boolean available, got {hres!r}") if hres.get("reason") not in (None,) + HANDLE_CHECK_REASONS: _fail(pid, f"check_handle({probe!r}) reason must be None or one of {HANDLE_CHECK_REASONS}, got {hres!r}") if hres["available"] and hres.get("reason"): _fail(pid, f"check_handle({probe!r}) gives no reason when available") if set(hres) - {"ok", "available", "reason"}: _fail(pid, f"check_handle({probe!r}) is public; keep it to ok/available/reason, got {hres!r}") elif not hres.get("error"): _fail(pid, f"check_handle({probe!r}) must return {{'ok': False, 'error': code}}, got {hres!r}") if provider.token_prefixes: from fleetmesh_auth.engine import FleetmeshAuthEngine engine = FleetmeshAuthEngine(plugins=[provider]) order = engine._infer_provider_order({"token": provider.token_prefixes[0] + "x"}) if order != [pid]: _fail(pid, f"its tokens route to {order}, not to it (another provider claims the prefix?)") return provider