Skip to content

feat(plugins): add plugin engine #486

Closed

Description

@uniqueg

Problem

Gateways built with FOCA (proTES now, proWES later) need one engine that
runs installed, allowlisted plugins on task requests, with defined
order, fallbacks, failure semantics and timeouts. proTES's own handler
imports classes by dotted path from config, instantiates them per
request, shares one mutable Flask request between alternatives (a failed
alternative leaves partial changes), and has no time bound.

Proposal

New package foca.plugins, framework-free:

  1. Model (foca.plugins.model): dataclasses Principal (subject,
    issuer, groups, claims, token), InboundRequest, Backend,
    Location, OutboundRequest, BackendResponse, and Headers, a
    case-insensitive mutable mapping (not Werkzeug's). Inbound headers
    exclude Authorization and Cookie; the token is in
    Principal.token (no capability grants: every plugin gets claims and
    token, decision Q18). Backend.auth names the backend's credential
    type (client_credentials | basic | none); the values are attached
    by the app, never put in the model.
  2. Base (foca.plugins.base): Plugin[Config, Params] with
    setup(config), hooks on_request, on_route, on_forward,
    on_response, close(); class attributes apis, phases (derived
    from implemented hooks), capabilities (generic descriptors, pattern
    ^[a-z0-9][a-z0-9.-]*$), maturity, api_version; exceptions
    NotApplicable, Rejected(status, title, detail) (400, 403, 409,
    413, 422 only), PluginError; forward outcomes for apps:
    NotAccepted(reason) and its subclass OutcomeUnknown(reason),
    reason codes [a-z0-9_]{1,64} (e.g. connect_error, http_403,
    read_timeout), exported from foca.plugins; API_VERSION = 1.
  3. Config (foca.plugins.config, top-level FOCA config key
    plugins; one field added to foca.models.config.Config):
    available (allowlist: distribution, version specifier, config,
    client_selectable, roles, enabled), defaults (timeout 10,
    pipeline_timeout 30, forward_timeout 60, workers 8),
    gateway_id, pipeline (steps with id, alternatives, timeout,
    on_failure: fail|skip; short forms - plugin: x and the plain
    string - x), presets;
    reserved keys when/needs rejected ("reserved for a later
    version"); unknown keys rejected.
  4. Loader (foca.plugins.loader): only entry points of group
    foca.plugins named in available are imported; pins checked
    (packaging); duplicate IDs, unknown IDs, version mismatches,
    unsupported api_version or apis stop the app; RECORD digest of
    each distribution computed once (for provenance). A middlewares key
    at the top level or in custom is a startup error with a migration
    hint to plugins (Q15), checked on the raw merged config in
    ConfigParser before Config and the app's custom model are
    validated (when gateway is set), so the hint wins over pydantic's
    "extra inputs are not permitted". Plugins are instantiated once per
    process and Config-validated at startup.
  5. Runtime (foca.plugins.runtime): apps pass
    Foca(..., gateway=GatewayApp(api, validate, sanitize, validate_outbound)); create_app() loads the plugins once (fail
    fast); get_host() returns the process's host, created lazily on
    first use (after Gunicorn/Celery forks; os.register_at_fork makes
    children forget it), and works in Celery without Flask.
  6. Engine (foca.plugins.engine): PluginHost(conf, api, validate, sanitize, validate_outbound); host.start(inbound, principal, tags)
    → PipelineRun with request(), route(initial),
    attempts(candidates) (yields Attempt with outbound;
    report(exc) with NotAccepted/OutcomeUnknown,
    succeeded(response, remote_id=...)). validate failures are
    invalid_output (next alternative); exceptions of sanitize
    propagate unchanged (stop, e.g. 413); validate_outbound runs per
    attempt after the forward phase, failure = not accepted with reason
    invalid_outbound (next candidate).
    Each alternative works on a deep copy, committed on success;
    outcomes ok, not_applicable, error, timeout,
    invalid_output, rejected (6.2); hooks run in a bounded
    ThreadPoolExecutor and are abandoned at the deadline; saturation
    fails fast. Route output must be a subset of the candidates. Errors:
    PipelineFailed (500, problem type .../plugin-step-failed),
    PipelineRejected (4xx), NoBackendAvailable (503), ForwardTimeout
    (503 after the total forward_timeout, with the attempts so far),
    LoopDetected (508). The engine adds Via: 1.1 <gateway_id> to
    outbound requests and raises LoopDetected if the inbound Via
    already names this gateway (Q22). Credentials are attached by the app
    after the forward phase. If no step implements on_route, the
    default route step is appended (P6 provides it).
  7. Adapter (foca.plugins.adapter): the only module of
    foca.plugins that imports Flask/Connexion; builds InboundRequest
    and Principal from the current request and the controller's body;
    Principal.groups = get_current_groups(), the mapped access-control
    roles (same code as access control); request_id() = a safe client
    X-Request-ID (≤ 128 characters of [A-Za-z0-9._:-]) or a new uuid4
    hex. No host registration here (see runtime).
  8. ast-grep rule no-framework-imports-in-plugins (with rule tests):
    no flask, werkzeug, connexion, starlette imports in
    foca/plugins/ except adapter.py.
  9. Docs: configuration page plugins (operator view), "Plugins"
    concepts page (incl. how apps integrate: GatewayApp, get_host(),
    forward outcomes), API reference, migration note.
  10. Dependency: packaging (version specifiers).

Acceptance criteria

  • Unlisted installed plugins are never imported (tests with fake entry
    points for the loader's lookup).
  • get_host() is lazy, per process and fork-safe; works without a Flask
    app context (Celery); create_app() fails fast on plugin errors.
  • sanitize exceptions propagate; validate and validate_outbound
    failures give invalid_output / invalid_outbound.
  • Legacy-key hint appears also when the app's custom model forbids extra
    keys.
  • Every outcome of 6.2 is tested, including a hanging plugin abandoned
    at its timeout, executor saturation, a failed alternative leaving no
    trace, on_failure: skip, Rejected stopping at once.
  • Startup errors for unknown IDs, pin mismatches, duplicate IDs,
    unsupported api_version, reserved keys, middlewares keys (with the
    hint).
  • Via added outbound; inbound loop → LoopDetected.
  • foca/models/config.py gets only the plugins field (other lanes edit
    the file).
  • 100% coverage, mypy, ruff, ast-grep, semgrep, mkdocs build --strict.

Surviving the Connexion 3 migration

No framework types anywhere in the engine, model, config or hooks; the
engine gets inbound request, principal and tags as arguments and never
reads Flask g or the request context; get_host() is a per-process
singleton, not tied to current_app. rc1 replaces only
foca.plugins.adapter (e.g. on Starlette's request, or on H1-S draft
C's current_request() once it exists). Hooks are def now; P8 adds
async def support without changing signatures. The bounded executor
maps to anyio.to_thread in 1.0.

Dependencies

Open questions

  • Loop status: 508 Loop Detected (chosen) or 400?

Added during review (PR #496): FrozenMapping (read-only, deep-copyable mapping for Principal.claims, exported from foca.plugins); InvalidVia (400, slug invalid-via) for inbound Via headers over 1024 characters; outbound Via = inbound Via plus this gateway's entry (RFC 9110 §7.6.3); public get_current_claims() in foca.security.access_control.

Added after the Sourcery review (PR #496): one gateway app per process: runtime.configure() raises RuntimeError if a host for other settings is in use, and runtime.reset() closes the host (for tests); the cached host is closed at exit; problem_response() gained a keyword-only title=; Principal.token is set only for validated tokens.

Metadata

Metadata

Assignees

No one assigned

    Labels

    priority: hightype: featuretype: securityworkload: weeks

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions