Metadata-Version: 2.5
Name: trytond_keycloak_auth
Version: 8.0.3.0
Summary: Tryton module keycloak_auth
Author: Clemens Hupka
Maintainer-email: Clemens Hupka <issues@tryton-erp.eu>
License-Expression: GPL-3.0-or-later
License-File: COPYRIGHT
License-File: LICENSE
Keywords: authentication,jwt,keycloak,oidc,openid,tryton
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Environment :: Plugins
Classifier: Framework :: Tryton
Classifier: Topic :: Office/Business
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.10
Requires-Dist: cryptography
Requires-Dist: pyjwt<3,>=2.8
Requires-Dist: requests<3,>=2.28
Requires-Dist: trytond<8.1,>=8.0
Provides-Extra: test
Description-Content-Type: text/x-rst

Keycloak Authentication
=======================

The ``keycloak_auth`` module authenticates HTTP requests that carry a
Keycloak/OIDC access token as ``Authorization: Bearer <token>`` and
resolves the caller to a Tryton ``res.user``.

It exists because the flask_portal frontend modules (``fe_*``) run on
pool-less hosts and reach Tryton only through HTTP routes.  Before this
module every one of them carried its own, unrelated route authentication
(``web.user.session`` keys, manually provisioned
``res.user.application`` tokens), so there was no single identity for the
frontend.  ``keycloak_auth`` is that single identity, and it is the only
place the token pipeline lives.

Identity contract
-----------------

flask_portal establishes the identity with Keycloak and configures
``USER_SOURCES=res.user``: the Keycloak ``preferred_username`` claim is
the ``res.user`` login.

This module applies the same mapping server-side:

* the presented access token is verified against the realm's public keys
  (the JSON Web Key Set) before anything else happens;
* the identity is read from the configured claim (``preferred_username``
  by default) and matched to an **active** ``res.user`` by **exact,
  case-sensitive login**;
* no user is ever created, updated or modified on the authentication
  path: an unmatched login denies the request.

The exactness is deliberate: it is the answer to the impersonation class
of issue #694, where a user was resolved by matching an *email* against a
value a client presented.

The resolved user runs the request with the full Tryton access checks
enabled -- model access, field access and record rules -- so a route sees
exactly what that user may see.

On top of that, and still off by default, a request of an allowed
administrator may ask a route to run *read-only* as another user of the
installation, by naming that user's login in an ``X-Simulate-Login``
header.  It is what lets the portal render a simulated view with the
data the simulated user is allowed to see; both identities are audited,
and the acting user stays the accountable one.

Deny by default
---------------

The module ships with its single configuration record **disabled** and
authenticates nothing until an administrator configures an issuer and
explicitly enables it.  Every failure mode denies the request, a
configuration that can not be read denies it as well, and the opaque
token fallback is off on top of that.

Configuration
-------------

All settings live in one record, *Administration > Keycloak
Authentication > Configuration* (the ``keycloak_auth.configuration``
singleton).  The fields, their defaults and the accepted ranges are:

``enabled`` (Boolean, default ``False``)
    The master switch.  While it is off every request is denied with the
    reason code ``authentication_disabled`` and no token is parsed.
``issuer`` (Char, required)
    The exact ``iss`` value expected in a token, for example
    ``https://sso.example.com/realms/example``.  It is compared
    literally, so it has to match the realm issuer character for
    character.  Must be an absolute HTTPS URL without query string and
    without fragment; plain HTTP is accepted for a loopback host only.
``jwks_url`` (Char, optional)
    Absolute URL of the realm's JSON Web Key Set, for example
    ``https://sso.example.com/realms/example/protocol/openid-connect/certs``.
    When it is left empty the location is discovered from the issuer
    through OpenID Connect discovery.  When it is set it has to be
    served by the same host as the issuer, so that a substituted
    metadata document can not move the trust anchor to another server.
``audience`` (Char, optional)
    Expected ``aud`` entry of the access token.  When it is set, a token
    whose audience does not contain it is refused.
``client_id`` (Char, optional)
    Expected ``azp`` (authorized party) of the access token.  When it is
    set, a token issued for another client is refused.
``login_claim`` (Char, required, default ``preferred_username``)
    Name of the claim carrying the identity that is mapped to
    ``res.user.login``.  It must not contain whitespace.
``clock_skew`` (Integer, default ``60``, range ``0`` to ``600``)
    Seconds of clock skew tolerated while checking the ``exp``, ``nbf``
    and ``iat`` claims.
``jwks_cache_ttl`` (Integer, default ``3600``, range ``1`` to ``86400``)
    Seconds a stored JSON Web Key Set stays fresh before it is refreshed.
``jwks_fetch_timeout`` (Integer, default ``10``, range ``1`` to ``60``)
    Timeout of the HTTP request that retrieves the key set.  The request
    that asks the realm about an opaque token is bounded by the same
    value.
``allow_opaque_tokens`` (Boolean, default ``False``)
    Accept a reference (opaque) token by asking the realm to introspect
    it.
``introspection_url`` (Char, optional)
    Absolute URL of the realm's token introspection endpoint (RFC 7662).
    Required when opaque tokens are allowed.
``introspection_client_id`` (Char, optional)
    Identifier of the client the module authenticates to the
    introspection endpoint with.  Required when opaque tokens are
    allowed.
``introspection_client_secret`` (Char, optional)
    Secret of that client.  It is masked in the form and is sent to the
    endpoint only, never to a log and never into an error.  Required
    when opaque tokens are allowed.
``introspection_cache_ttl`` (Integer, default ``60``, range ``0`` to ``86400``)
    Seconds the answer of the realm about an opaque token is reused.
    ``0`` asks the realm for every request.
``simulate_groups`` (Many2Many to ``res.group``, optional)
    Groups whose members may ask a route to run read-only as *another*
    user, by naming the login to simulate in an ``X-Simulate-Login``
    header.  Empty by default, and an empty set means the feature is off:
    a request that carries the header is refused rather than served.  The
    request still authenticates with the token of the acting user, it has
    to be a read, and both identities are audited.  See
    ``doc/simulation.rst``.

The record is validated on save: the URLs have to be absolute and secure
(loopback excepted), the key set URL has to be served by the host of the
issuer, the login claim has to be usable, the numeric tolerances have to
lie in their ranges, and turning ``allow_opaque_tokens`` on without
naming the endpoint, the client id and the client secret together is
refused rather than stored.

A minimal configuration for an installation that only accepts signed
tokens is:

* ``issuer`` -- the realm issuer, character for character;
* ``jwks_url`` -- empty to discover it from the issuer, or the realm's
  key set URL;
* ``audience`` and ``client_id`` -- the values the realm puts into the
  token, when they are to be enforced;
* ``login_claim`` -- ``preferred_username`` (the default);
* ``enabled`` -- checked last, once the rest is verified (see the
  rollout sequence in ``doc/runbook.rst``).

Adopting the module in a route
------------------------------

A module that exposes routes behind the same identity does not
authenticate anything itself: it wraps its view with
``keycloak_auth.authentication.authenticate_route``, innermost, and
receives the resolved ``res.user`` as the ``user`` keyword::

    from trytond.protocols.wrappers import (
        Response, with_pool, with_transaction)
    from trytond.wsgi import app

    from trytond.modules.keycloak_auth.authentication import (
        authenticate_route)

    @app.route('/<database_name>/example/thing', methods={'GET'})
    @with_pool
    @with_transaction(readonly=False)
    @authenticate_route
    def example_thing(request, pool, user):
        # `user` is the active res.user the access token resolved to,
        # and every ORM operation here runs with the access checks of
        # that user enabled.
        return Response('{}', status=200,
            content_type='application/json')

A refused request never reaches the view: it is answered with a JSON
``401`` carrying a stable reason code and no token content.  A caller
that is not a route -- a script, or a helper that already holds a
transaction -- authenticates with ``authenticate_request`` and runs its
block inside the ``run_as_user`` context manager.

``doc/adoption.rst`` documents both forms, their placement relative to
``@with_pool`` and ``@with_transaction``, the mapping of every reason
code to the answer a client gets, and what may and may not be logged.

The decorator also serves the read-only act-as path: a request that
carries an ``X-Simulate-Login`` header in an installation that names the
groups allowed to use it runs the view with the rights of the login it
names, and only when the request reads.  A route author does not opt in
and does not have to know the mechanism; ``doc/simulation.rst``
documents it and the contract the Flask Portal relies on.

Operations
----------

The module serves one diagnostic route,
``GET /<database_name>/keycloak_auth/whoami``, which answers the login
and the identifier of the user a presented token resolves to and nothing
else.  It is the reference use of the helper.

``doc/runbook.rst`` is the operator runbook: creating and retiring a
``res.user``, verifying an integration with ``whoami``, reading the JSON
Web Key cache, the log lines to expect, and the enable/disable rollout
sequence.

What the module does not do
---------------------------

* It does **not** provision users.  A token is a statement about an
  identity that already exists in the installation; resolving it never
  creates, updates or saves a user.
* It does **not** fall back to ``sub``, to an email address or to any
  other claim, and it never trusts a claim that was not verified.
* It does **not** open or hold a session.  Every request carries and
  verifies its own token; there is no session cookie, no login form and
  no logout.
* It does **not** perform single sign-out, back-channel logout, token
  refresh or password-grant flows.  Those are the business of the realm.
* It does **not** authenticate the Tryton desktop client or SAO.  Only
  the HTTP routes that opt in through the helper are served.
* It does **not** send a credential of a caller to the realm unless an
  administrator switched the opaque-token fallback on, and it never
  sends one that has the shape of a JSON Web Token.
* It does **not** replace the Tryton access rights: the resolved user is
  subject to the model, field and record rules of the installation, and
  the helper decides nothing about what the route may read or write.
* It does **not** impersonate: asking to act as another user is an
  authorization *request* made with the credential of the acting user,
  it is granted only to configured groups, it is read-only, and it is
  audited with both identities.

Dependencies
------------

Tryton modules: ``ir`` (base framework) and ``res`` (users and groups).

Third-party runtime dependencies:

* ``PyJWT`` -- token parsing and signature verification;
* ``cryptography`` -- cryptographic primitives used by the JSON Web Keys;
* ``requests`` -- realm metadata and key set retrieval.

Installation
------------

Install the module with pip::

    pip install trytond_keycloak_auth

Or, if running from the monorepo, put ``modules-cch`` on ``PYTHONPATH``
and activate the module through the Tryton client under *Administration >
Modules > Modules*.

Documentation
-------------

The module documentation lives under ``doc/`` (Sphinx): ``index.rst`` for
the overview, ``models.rst`` for the models, ``adoption.rst`` for route
authors, ``simulation.rst`` for the read-only act-as path and the portal
contract, ``security.rst`` for the threat model and the deny-by-default
matrix, and ``runbook.rst`` for operators.

See also the umbrella issue #783, the security precedent #694, the
view-simulation counterpart tryton/flask_portal#361 and the flask_portal
counterparts #205, #226 and #323.

Status
------

The module is under active development.  The configuration model, the
JSON Web Key cache, the token validation pipeline, the identity resolver,
the back-off and the reusable route authentication helper are delivered;
the documentation under ``doc/`` describes the feature set available in
the installed version.
