From 866f6d13f411dc52b72fbde5740e243e2805a8ea Mon Sep 17 00:00:00 2001 From: eLBati Date: Tue, 6 Oct 2026 18:16:08 +0200 Subject: [PATCH 1/5] [ADD] auth_oauth_server: OAuth 2.1 authorization server Odoo can log users in through external providers (auth_oauth, auth_oidc, auth_saml) and accept bearer JWTs on routes (auth_jwt), but nothing lets it issue tokens to third-party applications. This module makes Odoo an OAuth 2.1 authorization server, following what the MCP authorization specification requires, so that MCP clients can connect to an MCP server hosted in Odoo by having the user log in and approve. - Authorization code flow with mandatory PKCE (S256). Refresh tokens are stored as digests and rotated on each use; reusing a code or a rotated refresh token revokes the authorization. - Discovery: authorization server metadata (RFC 8414) and protected resource metadata (RFC 9728). - Clients registered by an administrator, through dynamic registration (RFC 7591), or identified by a Client ID Metadata Document, fetched from public addresses only. - Tokens bound to the resource they were asked for (RFC 8707), iss in authorization responses (RFC 9207), token revocation (RFC 7009). - Access tokens are short-lived JWTs signed with an auth_jwt validator created for each protected resource, so routes can use auth="jwt_". Each token is also checked against its authorization, so revoking one takes effect at once. - Login is left to Odoo's login page (password, two-factor, auth_oauth, ...), followed by a consent page bound to the validated request. - Users see and revoke the applications they connected in their preferences; administrators manage resources, clients and authorizations. Assisted-by: Claude Opus 5.5 --- auth_oauth_server/README.rst | 208 +++++++ auth_oauth_server/__init__.py | 3 + auth_oauth_server/__manifest__.py | 30 + auth_oauth_server/controllers/__init__.py | 1 + auth_oauth_server/controllers/main.py | 293 ++++++++++ auth_oauth_server/data/neutralize.sql | 9 + auth_oauth_server/exceptions.py | 32 + auth_oauth_server/hooks.py | 21 + auth_oauth_server/models/__init__.py | 8 + .../models/auth_jwt_validator.py | 34 ++ auth_oauth_server/models/oauth_server.py | 228 ++++++++ .../models/oauth_server_authorization.py | 380 ++++++++++++ .../models/oauth_server_client.py | 343 +++++++++++ .../models/oauth_server_refresh_token.py | 81 +++ .../models/oauth_server_resource.py | 278 +++++++++ .../models/res_config_settings.py | 39 ++ auth_oauth_server/models/res_users.py | 25 + auth_oauth_server/readme/CONFIGURE.md | 25 + auth_oauth_server/readme/CONTRIBUTORS.md | 1 + auth_oauth_server/readme/DESCRIPTION.md | 27 + auth_oauth_server/readme/ROADMAP.md | 14 + auth_oauth_server/readme/USAGE.md | 33 ++ .../security/ir.model.access.csv | 6 + .../security/oauth_server_security.xml | 15 + .../static/description/index.html | 545 ++++++++++++++++++ auth_oauth_server/tests/__init__.py | 5 + auth_oauth_server/tests/common.py | 88 +++ auth_oauth_server/tests/test_controllers.py | 359 ++++++++++++ auth_oauth_server/tests/test_flow.py | 448 ++++++++++++++ auth_oauth_server/tests/test_registration.py | 307 ++++++++++ auth_oauth_server/tests/test_resource.py | 167 ++++++ auth_oauth_server/tests/test_utils.py | 161 ++++++ auth_oauth_server/utils.py | 262 +++++++++ .../views/auth_jwt_validator_views.xml | 39 ++ .../oauth_server_authorization_views.xml | 102 ++++ .../views/oauth_server_client_views.xml | 139 +++++ .../views/oauth_server_menus.xml | 28 + .../views/oauth_server_resource_views.xml | 79 +++ .../views/oauth_server_templates.xml | 69 +++ .../views/res_config_settings_views.xml | 74 +++ auth_oauth_server/views/res_users_views.xml | 44 ++ 41 files changed, 5050 insertions(+) create mode 100644 auth_oauth_server/README.rst create mode 100644 auth_oauth_server/__init__.py create mode 100644 auth_oauth_server/__manifest__.py create mode 100644 auth_oauth_server/controllers/__init__.py create mode 100644 auth_oauth_server/controllers/main.py create mode 100644 auth_oauth_server/data/neutralize.sql create mode 100644 auth_oauth_server/exceptions.py create mode 100644 auth_oauth_server/hooks.py create mode 100644 auth_oauth_server/models/__init__.py create mode 100644 auth_oauth_server/models/auth_jwt_validator.py create mode 100644 auth_oauth_server/models/oauth_server.py create mode 100644 auth_oauth_server/models/oauth_server_authorization.py create mode 100644 auth_oauth_server/models/oauth_server_client.py create mode 100644 auth_oauth_server/models/oauth_server_refresh_token.py create mode 100644 auth_oauth_server/models/oauth_server_resource.py create mode 100644 auth_oauth_server/models/res_config_settings.py create mode 100644 auth_oauth_server/models/res_users.py create mode 100644 auth_oauth_server/readme/CONFIGURE.md create mode 100644 auth_oauth_server/readme/CONTRIBUTORS.md create mode 100644 auth_oauth_server/readme/DESCRIPTION.md create mode 100644 auth_oauth_server/readme/ROADMAP.md create mode 100644 auth_oauth_server/readme/USAGE.md create mode 100644 auth_oauth_server/security/ir.model.access.csv create mode 100644 auth_oauth_server/security/oauth_server_security.xml create mode 100644 auth_oauth_server/static/description/index.html create mode 100644 auth_oauth_server/tests/__init__.py create mode 100644 auth_oauth_server/tests/common.py create mode 100644 auth_oauth_server/tests/test_controllers.py create mode 100644 auth_oauth_server/tests/test_flow.py create mode 100644 auth_oauth_server/tests/test_registration.py create mode 100644 auth_oauth_server/tests/test_resource.py create mode 100644 auth_oauth_server/tests/test_utils.py create mode 100644 auth_oauth_server/utils.py create mode 100644 auth_oauth_server/views/auth_jwt_validator_views.xml create mode 100644 auth_oauth_server/views/oauth_server_authorization_views.xml create mode 100644 auth_oauth_server/views/oauth_server_client_views.xml create mode 100644 auth_oauth_server/views/oauth_server_menus.xml create mode 100644 auth_oauth_server/views/oauth_server_resource_views.xml create mode 100644 auth_oauth_server/views/oauth_server_templates.xml create mode 100644 auth_oauth_server/views/res_config_settings_views.xml create mode 100644 auth_oauth_server/views/res_users_views.xml diff --git a/auth_oauth_server/README.rst b/auth_oauth_server/README.rst new file mode 100644 index 0000000000..9d0eb737ba --- /dev/null +++ b/auth_oauth_server/README.rst @@ -0,0 +1,208 @@ +.. image:: https://odoo-community.org/readme-banner-image + :target: https://odoo-community.org/get-involved?utm_source=readme + :alt: Odoo Community Association + +========================== +OAuth Authorization Server +========================== + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:eb111f86f7a6aebcf3f080391d42a302e6f0aaa59fd74b5b059161b092f3c142 + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |badge1| image:: https://img.shields.io/badge/maturity-Alpha-red.png + :target: https://odoo-community.org/page/development-status + :alt: Alpha +.. |badge2| image:: https://img.shields.io/badge/license-LGPL--3-blue.png + :target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html + :alt: License: LGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fserver--auth-lightgray.png?logo=github + :target: https://github.com/OCA/server-auth/tree/16.0/auth_oauth_server + :alt: OCA/server-auth +.. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png + :target: https://translation.odoo-community.org/projects/server-auth-16-0/server-auth-16-0-auth_oauth_server + :alt: Translate me on Weblate +.. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png + :target: https://runboat.odoo-community.org/builds?repo=OCA/server-auth&target_branch=16.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +This module makes Odoo an OAuth 2.1 authorization server: applications +ask a user for access, the user logs in on the usual Odoo login page and +approves, and the application receives tokens that let it call an API of +Odoo as that user, with that user's access rights. + +It supports what the `MCP authorization +specification `__ +requires, so MCP clients can connect to an MCP server hosted in Odoo: + +- authorization code flow with mandatory PKCE (S256), and refresh + tokens, rotated on each use; +- discovery: authorization server metadata (RFC 8414) and protected + resource metadata (RFC 9728); +- applications may be registered by an administrator, register + themselves (RFC 7591), or be identified by the URL of the details + they publish (OAuth Client ID Metadata Documents); +- tokens bound to the API they were asked for (RFC 8707 resource + indicators), ``iss`` in authorization responses (RFC 9207), token + revocation (RFC 7009). + +Access tokens are short-lived JWTs checked by an ``auth_jwt`` validator, +which the module creates for each protected API. Routes can therefore be +protected with ``auth="jwt_"``, as with any other +``auth_jwt`` validator. Each token is also checked against the +authorization it comes from, so that revoking an authorization takes +effect at once. + +Logging in is left to Odoo: password, two-factor authentication, and +login through another provider (``auth_oauth``, ``auth_oidc``, +``auth_saml``) all work. + +.. IMPORTANT:: + This is an alpha version, the data model and design can change at any time without warning. + Only for development or testing purpose, do not use in production. + `More details on development status `_ + +**Table of contents** + +.. contents:: + :local: + +Configuration +============= + +In *Settings > General Settings > OAuth Authorization Server*: + +- **OAuth Issuer URL**: the public HTTPS address of Odoo, as + applications reach it. It is set from ``web.base.url`` at + installation; check it, especially behind a reverse proxy (where + ``proxy_mode`` must be enabled too). Changing it invalidates the + access tokens issued so far; applications get new ones with their + refresh tokens. +- **Accept Client Metadata Documents**: let applications identify + themselves with the URL of the details they publish, without being + registered first. Odoo then fetches that URL, from public addresses + only. Optionally, list the domains to accept. +- **Allow Dynamic Client Registration**: let applications register + themselves. + +Then, in *Settings > Users & Companies > OAuth Server > Protected +Resources*, declare each API that accepts the tokens: its path on this +server, the scopes applications may ask for, the groups whose users may +give access (all internal users when empty), and the lifetime of tokens. + +Applications to be registered by hand go in *OAuth Applications*. Give +them the Client ID and, for confidential ones, the secret shown by +*Generate Secret*. + +With several databases on one server, set ``dbfilter`` so that each host +name selects one database: the endpoints of this module are called +without a session, so they cannot work otherwise. + +Usage +===== + +Applications discover the server from +``/.well-known/oauth-authorization-server`` and each protected +API from ``/.well-known/oauth-protected-resource``. When a +user connects an application, Odoo asks them to log in if needed, then +shows what the application asks for and where the user will be sent. +Once the user allows it, the application can call the API. + +Users see the applications they connected in their preferences (*Account +Security* tab) and can revoke them there. Administrators see every +authorization in *Settings > Users & Companies > OAuth Server*. + +To protect a route of your own module, either use the resource's +validator in the route: + +.. code:: python + + @http.route("/api/orders", auth="jwt_oauth_server_api", type="http") + def orders(self): + if "orders:read" not in request.jwt_payload["scope"].split(): + raise Forbidden() + ... + +or check the token yourself, which also gives you the +``WWW-Authenticate`` header that lets clients discover the server: + +.. code:: python + + resource = request.env.ref("my_module.my_resource").sudo() + try: + uid, payload = resource._authenticate_bearer(token, ["orders:read"]) + except Unauthorized: + headers = [("WWW-Authenticate", resource._www_authenticate())] + ... + +Known issues / Roadmap +====================== + +- Tokens are signed with a secret (HS256) known only to this database, + so only Odoo itself can check them. Asymmetric keys published as a + JWKS would let other servers check them too. +- No OpenID Connect (ID tokens, userinfo), no token introspection, no + ``private_key_jwt`` client authentication. +- Redirect URIs must use https, or http on localhost: private-use + schemes of native applications are not supported. +- Dynamic client registration is not rate limited; use a reverse proxy, + or disable it. +- A resource created while Odoo runs registers its ``auth="jwt_..."`` + route method only in the worker that created it (an ``auth_jwt`` + limitation): restart the workers before using it in routes. +- Users of the portal can authorize applications when a resource allows + their group, but cannot see or revoke them from the portal. + +Bug Tracker +=========== + +Bugs are tracked on `GitHub Issues `_. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +`feedback `_. + +Do not contact contributors directly about support or help with technical issues. + +Credits +======= + +Authors +------- + +* Lorenzo Battistini + +Contributors +------------ + +- Lorenzo Battistini + +Maintainers +----------- + +This module is maintained by the OCA. + +.. image:: https://odoo-community.org/logo.png + :alt: Odoo Community Association + :target: https://odoo-community.org + +OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use. + +.. |maintainer-eLBati| image:: https://github.com/eLBati.png?size=40px + :target: https://github.com/eLBati + :alt: eLBati + +Current `maintainer `__: + +|maintainer-eLBati| + +This module is part of the `OCA/server-auth `_ project on GitHub. + +You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/auth_oauth_server/__init__.py b/auth_oauth_server/__init__.py new file mode 100644 index 0000000000..6487efb0df --- /dev/null +++ b/auth_oauth_server/__init__.py @@ -0,0 +1,3 @@ +from . import controllers +from . import models +from .hooks import post_init_hook diff --git a/auth_oauth_server/__manifest__.py b/auth_oauth_server/__manifest__.py new file mode 100644 index 0000000000..0b1292c4d0 --- /dev/null +++ b/auth_oauth_server/__manifest__.py @@ -0,0 +1,30 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +{ + "name": "OAuth Authorization Server", + "summary": "Let applications obtain OAuth 2.1 access tokens for Odoo users", + "version": "16.0.1.0.0", + "category": "Tools", + "license": "LGPL-3", + "author": "Lorenzo Battistini, Odoo Community Association (OCA)", + "maintainers": ["eLBati"], + "website": "https://github.com/OCA/server-auth", + "development_status": "Alpha", + "depends": ["auth_jwt", "base_setup"], + "external_dependencies": {"python": ["pyjwt"]}, + "data": [ + "security/ir.model.access.csv", + "security/oauth_server_security.xml", + "views/oauth_server_resource_views.xml", + "views/oauth_server_client_views.xml", + "views/oauth_server_authorization_views.xml", + "views/auth_jwt_validator_views.xml", + "views/res_users_views.xml", + "views/res_config_settings_views.xml", + "views/oauth_server_menus.xml", + "views/oauth_server_templates.xml", + ], + "post_init_hook": "post_init_hook", + "installable": True, +} diff --git a/auth_oauth_server/controllers/__init__.py b/auth_oauth_server/controllers/__init__.py new file mode 100644 index 0000000000..12a7e529b6 --- /dev/null +++ b/auth_oauth_server/controllers/__init__.py @@ -0,0 +1 @@ +from . import main diff --git a/auth_oauth_server/controllers/main.py b/auth_oauth_server/controllers/main.py new file mode 100644 index 0000000000..d1664d1760 --- /dev/null +++ b/auth_oauth_server/controllers/main.py @@ -0,0 +1,293 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +import json +import logging +from urllib.parse import urlsplit + +from odoo import SUPERUSER_ID, http +from odoo.http import request + +from ..exceptions import OAuthError +from ..utils import add_query, is_loopback_host + +_logger = logging.getLogger(__name__) + +NO_STORE = [("Cache-Control", "no-store"), ("Pragma", "no-cache")] +PAGE_HEADERS = NO_STORE + [ + ("X-Frame-Options", "DENY"), + ("Content-Security-Policy", "frame-ancestors 'none'"), + ("Referrer-Policy", "no-referrer"), +] +MAX_REGISTRATION_BODY = 16 * 1024 + + +class OAuthServerController(http.Controller): + """Endpoints of the authorization server. + + They only parse requests and serialize answers: the flow is implemented + by the models. OAuthError raised by the models is turned into a response + here rather than propagated, so what a model did before failing, such as + revoking an authorization whose code was reused, is committed. + """ + + @staticmethod + def _env(): + # unauthenticated endpoints: auth="none" leaves no user in request.env + return request.env(user=SUPERUSER_ID, su=True) + + @staticmethod + def _json_response(data, status=200, headers=None): + return request.make_json_response( + data, headers=(headers or []) + NO_STORE, status=status + ) + + def _oauth_error_response(self, error): + headers = [] + if error.status == 401: + headers.append(("WWW-Authenticate", 'Basic realm="oauth"')) + return self._json_response( + error.to_dict(), status=error.status, headers=headers + ) + + # ------------------------------------------------------------------ + # Metadata + # ------------------------------------------------------------------ + + @http.route( + "/.well-known/oauth-authorization-server", + type="http", + auth="none", + methods=["GET"], + cors="*", + csrf=False, + save_session=False, + ) + def authorization_server_metadata(self): + return self._json_response(self._env()["oauth.server"]._metadata()) + + @http.route( + [ + "/.well-known/oauth-protected-resource", + "/.well-known/oauth-protected-resource/", + ], + type="http", + auth="none", + methods=["GET"], + cors="*", + csrf=False, + save_session=False, + ) + def protected_resource_metadata(self, path=""): + resource = self._env()["oauth.server.resource"].search( + [("path", "=", "/" + path)], limit=1 + ) + if not resource: + return self._json_response({"error": "not_found"}, status=404) + return self._json_response(resource._metadata()) + + # ------------------------------------------------------------------ + # Authorization endpoint + # ------------------------------------------------------------------ + + @http.route( + "/oauth/authorize", + type="http", + auth="public", + methods=["GET"], + website=True, + multilang=False, + sitemap=False, + ) + def authorize(self, **params): + if request.env.user._is_public(): + # nothing is checked, and no metadata document fetched, for + # anonymous visitors: the login page brings them back here + return request.redirect_query( + "/web/login", {"redirect": request.httprequest.full_path} + ) + server = self._env()["oauth.server"] + try: + client, redirect_uri = server._get_authorization_client(params) + except OAuthError as error: + return self._error_page(error) + try: + values = server._check_authorization_request( + client, redirect_uri, params, request.env.user + ) + except OAuthError as error: + if client.registration_type != "manual": + # the redirect URI of a self-registered client may belong to + # anyone: never send the user there without their consent + return self._error_page(error) + return self._redirect_to_client( + redirect_uri, + { + "error": error.error, + "error_description": error.description, + "state": params.get("state"), + }, + ) + return self._consent_page(client, values) + + @http.route( + "/oauth/authorize/decision", + type="http", + auth="public", + methods=["POST"], + website=True, + multilang=False, + sitemap=False, + ) + def authorize_decision(self, consent=None, decision=None, **kwargs): + user = request.env.user + server = self._env()["oauth.server"] + values = None if user._is_public() else server._verify_consent(consent) + if not values or values.get("uid") != user.id: + return self._error_page( + OAuthError( + "invalid_request", + "The authorization request expired: start again from the " + "application.", + ) + ) + if decision != "approve": + return self._redirect_to_client( + values["redirect_uri"], + { + "error": "access_denied", + "error_description": "The user denied the request.", + "state": values.get("state"), + }, + ) + try: + code = server._approve(values, user) + except OAuthError as error: + return self._error_page(error) + return self._redirect_to_client( + values["redirect_uri"], {"code": code, "state": values.get("state")} + ) + + def _redirect_to_client(self, redirect_uri, params): + params = dict(params, iss=self._env()["oauth.server"]._get_issuer()) + return request.redirect(add_query(redirect_uri, params), local=False) + + def _consent_page(self, client, values): + env = self._env() + redirect_host = urlsplit(values["redirect_uri"]).hostname + is_document = client.registration_type == "metadata_document" + qcontext = { + "client": client, + "client_host": urlsplit(client.identifier).hostname if is_document else "", + "unverified": client.registration_type == "dynamic", + "redirect_host": redirect_host, + "loopback": is_loopback_host(redirect_host), + "resource": env["oauth.server.resource"].browse(values["resource"]), + "scopes": values["scope"].split(), + "user": request.env.user, + "consent": env["oauth.server"]._sign_consent(values), + } + return self._page("auth_oauth_server.consent_page", qcontext) + + def _error_page(self, error): + return self._page("auth_oauth_server.error_page", {"error": error}, 400) + + @staticmethod + def _page(template, qcontext, status=200): + response = request.render(template, qcontext, status=status) + for key, value in PAGE_HEADERS: + response.headers[key] = value + return response + + # ------------------------------------------------------------------ + # Token, revocation and registration endpoints + # ------------------------------------------------------------------ + + @staticmethod + def _basic_credentials(): + authorization = request.httprequest.authorization + if authorization and authorization.type == "basic": + return authorization.username, authorization.password + return None + + @http.route( + "/oauth/token", + type="http", + auth="none", + methods=["POST"], + cors="*", + csrf=False, + save_session=False, + ) + def token(self, **params): + env = self._env() + try: + client = env["oauth.server"]._authenticate_client( + params.get("client_id"), + params.get("client_secret"), + self._basic_credentials(), + ) + grant_type = params.get("grant_type") + authorizations = env["oauth.server.authorization"] + if grant_type == "authorization_code": + result = authorizations._exchange_code(client, params) + elif grant_type == "refresh_token": + result = authorizations._refresh(client, params) + else: + raise OAuthError("unsupported_grant_type", "Unsupported grant_type.") + except OAuthError as error: + return self._oauth_error_response(error) + return self._json_response(result) + + @http.route( + "/oauth/revoke", + type="http", + auth="none", + methods=["POST"], + cors="*", + csrf=False, + save_session=False, + ) + def revoke(self, **params): + env = self._env() + try: + client = env["oauth.server"]._authenticate_client( + params.get("client_id"), + params.get("client_secret"), + self._basic_credentials(), + ) + except OAuthError as error: + return self._oauth_error_response(error) + env["oauth.server.authorization"]._revoke_token(client, params.get("token")) + return request.make_response("", headers=NO_STORE) + + @http.route( + "/oauth/register", + type="http", + auth="none", + methods=["POST"], + cors="*", + csrf=False, + save_session=False, + ) + def register(self): + env = self._env() + if not env["oauth.server"]._is_dynamic_registration_enabled(): + return self._json_response({"error": "not_found"}, status=404) + length = request.httprequest.content_length + try: + if not length or length > MAX_REGISTRATION_BODY: + raise OAuthError( + "invalid_client_metadata", + "The registration request is missing or too large.", + ) + try: + metadata = json.loads(request.httprequest.get_data(as_text=True)) + except ValueError as exc: + raise OAuthError( + "invalid_client_metadata", "The request is not valid JSON." + ) from exc + result = env["oauth.server.client"]._register_dynamic(metadata) + except OAuthError as error: + return self._oauth_error_response(error) + return self._json_response(result, status=201) diff --git a/auth_oauth_server/data/neutralize.sql b/auth_oauth_server/data/neutralize.sql new file mode 100644 index 0000000000..7b6c70927e --- /dev/null +++ b/auth_oauth_server/data/neutralize.sql @@ -0,0 +1,9 @@ +-- a copy of the database must not accept the tokens of the original +UPDATE oauth_server_authorization + SET revoked = true, revoked_reason = 'admin' + WHERE revoked IS NOT true; +DELETE FROM oauth_server_refresh_token; +UPDATE auth_jwt_validator + SET secret_key = md5(random()::text || clock_timestamp()::text) + || md5(random()::text || clock_timestamp()::text) + WHERE user_id_strategy = 'oauth_server'; diff --git a/auth_oauth_server/exceptions.py b/auth_oauth_server/exceptions.py new file mode 100644 index 0000000000..67cd19213c --- /dev/null +++ b/auth_oauth_server/exceptions.py @@ -0,0 +1,32 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from werkzeug.exceptions import Forbidden + + +class OAuthError(Exception): + """An OAuth error, answered to the client as defined by RFC 6749. + + ``error`` is the RFC error code; ``description`` is meant for developers + and is therefore not translated. + """ + + def __init__(self, error, description=None, status=400): + super().__init__(description or error) + self.error = error + self.description = description + self.status = status + + def to_dict(self): + res = {"error": self.error} + if self.description: + res["error_description"] = self.description + return res + + +class InsufficientScope(Forbidden): + """The access token is valid but lacks scopes the resource requires.""" + + def __init__(self, scope, description=None): + super().__init__(description) + self.scope = scope diff --git a/auth_oauth_server/hooks.py b/auth_oauth_server/hooks.py new file mode 100644 index 0000000000..e8a4ce70bf --- /dev/null +++ b/auth_oauth_server/hooks.py @@ -0,0 +1,21 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from odoo import SUPERUSER_ID, api + + +def post_init_hook(cr, registry): + """Pin the issuer to the current base URL and enable client registration. + + The issuer is a parameter of its own because ``web.base.url`` is rewritten + on every administrator login unless frozen, and every change of issuer + invalidates the access tokens issued so far. + """ + env = api.Environment(cr, SUPERUSER_ID, {}) + params = env["ir.config_parameter"] + if not params.get_param("auth_oauth_server.issuer"): + base_url = params.get_param("web.base.url") or "" + params.set_param("auth_oauth_server.issuer", base_url.rstrip("/")) + for key in ("auth_oauth_server.cimd_enabled", "auth_oauth_server.dcr_enabled"): + if not params.get_param(key): + params.set_param(key, "True") diff --git a/auth_oauth_server/models/__init__.py b/auth_oauth_server/models/__init__.py new file mode 100644 index 0000000000..d8e04fad68 --- /dev/null +++ b/auth_oauth_server/models/__init__.py @@ -0,0 +1,8 @@ +from . import oauth_server +from . import oauth_server_resource +from . import oauth_server_client +from . import oauth_server_authorization +from . import oauth_server_refresh_token +from . import auth_jwt_validator +from . import res_users +from . import res_config_settings diff --git a/auth_oauth_server/models/auth_jwt_validator.py b/auth_oauth_server/models/auth_jwt_validator.py new file mode 100644 index 0000000000..8e6622be73 --- /dev/null +++ b/auth_oauth_server/models/auth_jwt_validator.py @@ -0,0 +1,34 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from odoo import api, fields, models +from odoo.osv import expression + + +class AuthJwtValidator(models.Model): + _inherit = "auth.jwt.validator" + + user_id_strategy = fields.Selection( + selection_add=[("oauth_server", "OAuth Server Authorization")], + ondelete={"oauth_server": "cascade"}, + ) + oauth_server_resource_ids = fields.One2many( + "oauth.server.resource", "jwt_validator_id", readonly=True + ) + + @api.model + def _get_validator_by_name_domain(self, validator_name): + """Keep the validators of the authorization server out of routes that + name no validator (``auth="jwt"``), which require exactly one.""" + domain = super()._get_validator_by_name_domain(validator_name) + if not validator_name: + domain = expression.AND( + [domain, [("user_id_strategy", "!=", "oauth_server")]] + ) + return domain + + def _get_uid(self, payload): + if self.user_id_strategy != "oauth_server": + return super()._get_uid(payload) + authorization = self.env["oauth.server.authorization"].sudo() + return authorization._get_for_access_token(self, payload).user_id.id diff --git a/auth_oauth_server/models/oauth_server.py b/auth_oauth_server/models/oauth_server.py new file mode 100644 index 0000000000..b3b91b1b23 --- /dev/null +++ b/auth_oauth_server/models/oauth_server.py @@ -0,0 +1,228 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from urllib.parse import unquote_plus + +from odoo import api, models +from odoo.tools import str2bool + +from ..exceptions import OAuthError +from ..utils import ( + PKCE_CHALLENGE_RE, + is_valid_redirect_uri, + redirect_uri_matches, + sign, + verify, +) + +AUTH_METHODS = ("none", "client_secret_basic", "client_secret_post") +CONSENT_SCOPE = "auth_oauth_server.consent" +# time the user has to answer the consent page +CONSENT_MAX_AGE = 600 +MAX_STATE_LENGTH = 2048 + + +class OAuthServer(models.AbstractModel): + """The authorization server: configuration, metadata and the steps of the + authorization code flow that are not tied to one record.""" + + _name = "oauth.server" + _description = "OAuth Authorization Server" + + # ------------------------------------------------------------------ + # Configuration + # ------------------------------------------------------------------ + + @api.model + def _get_issuer(self): + params = self.env["ir.config_parameter"].sudo() + issuer = params.get_param("auth_oauth_server.issuer") or params.get_param( + "web.base.url" + ) + return (issuer or "").rstrip("/") + + @api.model + def _get_bool_param(self, key): + value = self.env["ir.config_parameter"].sudo().get_param(key) + return str2bool(value or "False", False) + + @api.model + def _is_metadata_document_enabled(self): + return self._get_bool_param("auth_oauth_server.cimd_enabled") + + @api.model + def _is_dynamic_registration_enabled(self): + return self._get_bool_param("auth_oauth_server.dcr_enabled") + + @api.model + def _get_trusted_metadata_domains(self): + value = ( + self.env["ir.config_parameter"] + .sudo() + .get_param("auth_oauth_server.cimd_trusted_domains") + ) + return [ + domain.strip().lower().lstrip(".") + for domain in (value or "").split(",") + if domain.strip() + ] + + @api.model + def _metadata(self): + """Authorization server metadata (RFC 8414).""" + issuer = self._get_issuer() + resources = self.env["oauth.server.resource"].search([]) + scopes = sorted({scope for res in resources for scope in res._get_scopes()}) + metadata = { + "issuer": issuer, + "authorization_endpoint": issuer + "/oauth/authorize", + "token_endpoint": issuer + "/oauth/token", + "revocation_endpoint": issuer + "/oauth/revoke", + "response_types_supported": ["code"], + "response_modes_supported": ["query"], + "grant_types_supported": ["authorization_code", "refresh_token"], + "code_challenge_methods_supported": ["S256"], + "token_endpoint_auth_methods_supported": list(AUTH_METHODS), + "revocation_endpoint_auth_methods_supported": list(AUTH_METHODS), + "scopes_supported": scopes, + "authorization_response_iss_parameter_supported": True, + "client_id_metadata_document_supported": ( + self._is_metadata_document_enabled() + ), + } + if self._is_dynamic_registration_enabled(): + metadata["registration_endpoint"] = issuer + "/oauth/register" + return metadata + + # ------------------------------------------------------------------ + # Authorization request + # ------------------------------------------------------------------ + + @api.model + def _get_authorization_client(self, params): + """The client and redirect URI of an authorization request. + + The errors raised here must be shown to the user, never redirected: + the redirect URI is not trusted yet. + """ + identifier = params.get("client_id") + if not identifier or not isinstance(identifier, str): + raise OAuthError("invalid_request", "Missing client_id.") + client = self.env["oauth.server.client"]._get_for_authorization(identifier) + registered = client._get_redirect_uris() + redirect_uri = params.get("redirect_uri") + if not redirect_uri: + if len(registered) != 1: + raise OAuthError("invalid_request", "Missing redirect_uri.") + redirect_uri = registered[0] + if not is_valid_redirect_uri(redirect_uri) or not any( + redirect_uri_matches(uri, redirect_uri) for uri in registered + ): + raise OAuthError("invalid_request", "Unregistered redirect_uri.") + return client, redirect_uri + + @api.model + def _check_authorization_request(self, client, redirect_uri, params, user): + """Validate an authorization request for ``user``. + + Returns the values to sign into the consent page, from which the + decision is taken once the user answers. + """ + if params.get("response_type") != "code": + raise OAuthError( + "unsupported_response_type", "Only the code response type is supported." + ) + challenge = params.get("code_challenge") + if ( + params.get("code_challenge_method") != "S256" + or not isinstance(challenge, str) + or not PKCE_CHALLENGE_RE.match(challenge) + ): + raise OAuthError( + "invalid_request", "PKCE with the S256 method is required." + ) + state = params.get("state") + if state is not None and len(state) > MAX_STATE_LENGTH: + raise OAuthError("invalid_request", "The state parameter is too long.") + resource = self.env["oauth.server.resource"]._get_for_request( + params.get("resource") + ) + if not resource._is_user_allowed(user): + raise OAuthError( + "access_denied", "This user may not give access to this resource." + ) + return { + "client": client.id, + "redirect_uri": redirect_uri, + "resource": resource.id, + "scope": resource._filter_scopes(params.get("scope")), + "code_challenge": challenge, + "state": state, + "uid": user.id, + } + + @api.model + def _get_consent_secret(self): + return self.env["ir.config_parameter"].sudo().get_param("database.secret") + + @api.model + def _sign_consent(self, values): + return sign(self._get_consent_secret(), CONSENT_SCOPE, values, CONSENT_MAX_AGE) + + @api.model + def _verify_consent(self, signed): + return verify(self._get_consent_secret(), CONSENT_SCOPE, signed) + + @api.model + def _approve(self, values, user): + """Record the user's consent; returns the authorization code.""" + client = self.env["oauth.server.client"].browse(values["client"]).exists() + resource = self.env["oauth.server.resource"].browse(values["resource"]).exists() + if not client.active or not resource.active: + raise OAuthError("invalid_request", "The application is no longer allowed.") + if not resource._is_user_allowed(user): + raise OAuthError( + "access_denied", "This user may not give access to this resource." + ) + _authorization, code = self.env[ + "oauth.server.authorization" + ]._create_from_consent( + user, + client, + resource, + values["scope"], + values["redirect_uri"], + values["code_challenge"], + ) + return code + + # ------------------------------------------------------------------ + # Client authentication (token and revocation endpoints) + # ------------------------------------------------------------------ + + @api.model + def _authenticate_client(self, client_id, client_secret, basic=None): + """The client of a token or revocation request. + + ``basic`` is the (username, password) pair of an HTTP Basic + Authorization header, if any. Confidential clients must present + their secret; public clients are identified by client_id alone. + """ + if basic: + basic_id, basic_secret = (unquote_plus(value or "") for value in basic) + if client_id and client_id != basic_id: + raise OAuthError("invalid_request", "Conflicting client_id.") + client_id, client_secret = basic_id, basic_secret + failure = OAuthError("invalid_client", "Client authentication failed.", 401) + if not client_id or not isinstance(client_id, str): + raise failure + client = self.env["oauth.server.client"].search( + [("identifier", "=", client_id)], limit=1 + ) + if not client: + raise failure + if client.client_type == "confidential" and not client._check_secret( + client_secret + ): + raise failure + return client diff --git a/auth_oauth_server/models/oauth_server_authorization.py b/auth_oauth_server/models/oauth_server_authorization.py new file mode 100644 index 0000000000..db270705fe --- /dev/null +++ b/auth_oauth_server/models/oauth_server_authorization.py @@ -0,0 +1,380 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +import calendar +import time +import uuid +from datetime import timedelta + +import jwt # pylint: disable=missing-manifest-dependency + +from odoo import _, api, fields, models +from odoo.exceptions import AccessError + +from odoo.addons.auth_jwt.exceptions import UnauthorizedInvalidToken + +from ..exceptions import OAuthError +from ..utils import check_pkce, generate_token, hash_token, normalize_uri + +# lifetime of an authorization code, in seconds +CODE_LIFETIME = 60 +# a refresh token presented again this soon after its first use (in seconds) +# comes from concurrent requests of the same client, not from a stolen copy +REFRESH_REUSE_GRACE = 60 + + +def _timestamp(value): + """Unix timestamp of a naive UTC datetime, as Odoo stores them.""" + return calendar.timegm(value.utctimetuple()) + + +class OAuthServerAuthorization(models.Model): + """The consent a user gave an application for a resource. + + One record per approval: two installations of the same application, or + two approvals on the same computer, are independent, so revoking (or + detecting the theft of) one leaves the others working. + """ + + _name = "oauth.server.authorization" + _description = "OAuth Authorization" + _order = "create_date desc, id desc" + _rec_name = "client_id" + # users see their authorizations in their preferences: never let them + # alter them through the sudo-ed write of res.users + _allow_sudo_commands = False + + user_id = fields.Many2one( + "res.users", required=True, readonly=True, ondelete="cascade", index=True + ) + client_id = fields.Many2one( + "oauth.server.client", + string="Application", + required=True, + readonly=True, + ondelete="cascade", + index=True, + ) + resource_id = fields.Many2one( + "oauth.server.resource", + required=True, + readonly=True, + ondelete="cascade", + index=True, + ) + scopes = fields.Char(readonly=True) + redirect_uri = fields.Char(readonly=True) + code_hash = fields.Char(readonly=True, copy=False, index=True) + code_challenge = fields.Char(readonly=True, copy=False) + code_expires_at = fields.Datetime(readonly=True) + code_used = fields.Boolean(readonly=True, copy=False) + expires_at = fields.Datetime(required=True, readonly=True) + last_refresh = fields.Datetime(readonly=True) + revoked = fields.Boolean(readonly=True, copy=False) + revoked_reason = fields.Selection( + [ + ("user", "By the user"), + ("admin", "By an administrator"), + ("client", "By the application"), + ("code_reuse", "Authorization code used twice"), + ("refresh_reuse", "Refresh token used twice"), + ], + readonly=True, + copy=False, + ) + state = fields.Selection( + [ + ("pending", "Pending"), + ("active", "Active"), + ("expired", "Expired"), + ("revoked", "Revoked"), + ], + compute="_compute_state", + ) + refresh_token_ids = fields.One2many( + "oauth.server.refresh.token", "authorization_id", readonly=True + ) + + @api.depends("revoked", "expires_at", "code_used") + def _compute_state(self): + now = fields.Datetime.now() + for authorization in self: + if authorization.revoked: + authorization.state = "revoked" + elif authorization.expires_at and authorization.expires_at <= now: + authorization.state = "expired" + elif not authorization.code_used: + authorization.state = "pending" + else: + authorization.state = "active" + + # ------------------------------------------------------------------ + # Lifecycle + # ------------------------------------------------------------------ + + @api.model + def _create_from_consent( + self, user, client, resource, scopes, redirect_uri, code_challenge + ): + """Record an approval; returns ``(authorization, code)``.""" + code = generate_token() + now = fields.Datetime.now() + authorization = self.create( + { + "user_id": user.id, + "client_id": client.id, + "resource_id": resource.id, + "scopes": scopes, + "redirect_uri": redirect_uri, + "code_hash": hash_token(code), + "code_challenge": code_challenge, + "code_expires_at": now + timedelta(seconds=CODE_LIFETIME), + "expires_at": now + timedelta(days=resource.max_lifetime), + } + ) + return authorization, code + + def _revoke(self, reason): + self.write({"revoked": True, "revoked_reason": reason}) + self.refresh_token_ids.unlink() + + def action_revoke(self): + """Revoke from the user's preferences or the administration menu.""" + is_admin = self.env.user.has_group("base.group_system") + for authorization in self: + own = authorization.user_id == self.env.user + if not own and not is_admin: + raise AccessError(_("You can only revoke your own authorizations.")) + authorization.sudo()._revoke("user" if own else "admin") + return True + + @api.autovacuum + def _gc_authorizations(self): + """Drop authorizations expired or revoked for a month, and codes + never exchanged.""" + now = fields.Datetime.now() + month_ago = now - timedelta(days=30) + self.search( + [ + "|", + "|", + ("expires_at", "<", month_ago), + "&", + ("revoked", "=", True), + ("write_date", "<", month_ago), + "&", + ("code_used", "=", False), + ("code_expires_at", "<", now - timedelta(days=1)), + ] + ).unlink() + + # ------------------------------------------------------------------ + # Token endpoint + # ------------------------------------------------------------------ + + @api.model + def _exchange_code(self, client, params): + """The authorization_code grant.""" + code = params.get("code") + authorization = self.browse() + if code and isinstance(code, str): + authorization = self.search([("code_hash", "=", hash_token(code))], limit=1) + if not authorization or authorization.client_id != client: + raise OAuthError("invalid_grant", "Invalid authorization code.") + if authorization.code_used: + # the code leaked: whatever was obtained with it must stop working + authorization._revoke("code_reuse") + raise OAuthError("invalid_grant", "Authorization code already used.") + if ( + authorization.revoked + or authorization.code_expires_at <= fields.Datetime.now() + ): + raise OAuthError("invalid_grant", "Authorization code expired.") + redirect_uri = params.get("redirect_uri") + if redirect_uri and redirect_uri != authorization.redirect_uri: + raise OAuthError("invalid_grant", "redirect_uri does not match.") + if not check_pkce(params.get("code_verifier"), authorization.code_challenge): + raise OAuthError("invalid_grant", "Invalid code_verifier.") + authorization._check_resource_param(params.get("resource")) + authorization._check_still_allowed() + if not authorization._claim_code(): + authorization._revoke("code_reuse") + raise OAuthError("invalid_grant", "Authorization code already used.") + return authorization._issue_tokens(authorization.scopes) + + def _claim_code(self): + """Mark the code used, atomically; False if it already was.""" + self.ensure_one() + self.flush_recordset(["code_used"]) + self.env.cr.execute( + "UPDATE oauth_server_authorization SET code_used = true " + "WHERE id = %s AND code_used IS NOT TRUE RETURNING id", + (self.id,), + ) + claimed = bool(self.env.cr.fetchone()) + self.invalidate_recordset(["code_used"]) + return claimed + + @api.model + def _refresh(self, client, params): + """The refresh_token grant, rotating the refresh token.""" + token = self.env["oauth.server.refresh.token"]._get_by_token( + params.get("refresh_token") + ) + authorization = token.authorization_id + if not token or authorization.client_id != client: + raise OAuthError("invalid_grant", "Invalid refresh token.") + now = fields.Datetime.now() + if ( + authorization.revoked + or authorization.expires_at <= now + or token.expires_at <= now + ): + raise OAuthError("invalid_grant", "Refresh token expired.") + # validate the request before using the token up + authorization._check_resource_param(params.get("resource")) + authorization._check_still_allowed() + scopes = authorization._narrow_scopes(params.get("scope")) + if not token._claim() and token.used_at < now - timedelta( + seconds=REFRESH_REUSE_GRACE + ): + # someone else holds a copy of the token + authorization._revoke("refresh_reuse") + raise OAuthError("invalid_grant", "Refresh token already used.") + authorization.last_refresh = now + return authorization._issue_tokens(scopes) + + def _check_resource_param(self, resource): + self.ensure_one() + if resource and normalize_uri(resource) != normalize_uri(self.resource_id.uri): + raise OAuthError( + "invalid_target", "The resource does not match the authorization." + ) + + def _check_still_allowed(self): + """The application, resource and user must still be allowed.""" + self.ensure_one() + if not self._is_valid(): + raise OAuthError("invalid_grant", "The authorization is no longer valid.") + + def _is_valid(self): + self.ensure_one() + return ( + not self.revoked + and self.expires_at > fields.Datetime.now() + and self.client_id.active + and self.resource_id.active + and self.resource_id._is_user_allowed(self.user_id) + ) + + def _narrow_scopes(self, requested): + """Scopes of a refreshed token: those granted, or fewer on request.""" + self.ensure_one() + granted = (self.scopes or "").split() + if not requested or not isinstance(requested, str): + return " ".join(granted) + scopes = list(dict.fromkeys(requested.split())) + if not set(scopes) <= set(granted): + raise OAuthError("invalid_scope", "Scopes beyond the authorization.") + return " ".join(scopes) + + def _issue_tokens(self, scopes): + self.ensure_one() + access_token, expires_in = self._make_access_token(scopes) + return { + "access_token": access_token, + "token_type": "Bearer", + "expires_in": expires_in, + "scope": scopes, + "refresh_token": self.env["oauth.server.refresh.token"]._create_for(self), + } + + def _make_access_token(self, scopes): + """A JWT access token (RFC 9068) signed with the resource's validator. + + Returns ``(token, expires_in)``. + """ + self.ensure_one() + resource = self.resource_id + validator = resource.jwt_validator_id.sudo() + now = int(time.time()) + exp = min(now + resource.access_token_lifetime, _timestamp(self.expires_at)) + payload = { + "iss": validator.issuer, + "aud": validator.audience, + "sub": str(self.user_id.id), + "client_id": self.client_id.identifier, + "scope": scopes, + "iat": now, + "exp": exp, + "jti": str(uuid.uuid4()), + "authorization_id": self.id, + } + token = jwt.encode( + payload, + validator.secret_key, + algorithm=validator.secret_algorithm, + headers={"typ": "at+jwt"}, + ) + return token, exp - now + + # ------------------------------------------------------------------ + # Access tokens presented to resources, revocation + # ------------------------------------------------------------------ + + @api.model + def _get_for_access_token(self, validator, payload): + """The authorization behind a validated access token payload. + + Refuses tokens of revoked or expired authorizations, of disabled + applications or resources, and of users no longer allowed, so that + revoking takes effect at once rather than when the token expires. + """ + authorization = self.browse() + try: + authorization = self.browse(int(payload.get("authorization_id"))).exists() + except (TypeError, ValueError): + authorization = self.browse() + if ( + not authorization + or authorization.resource_id.jwt_validator_id != validator + or payload.get("client_id") != authorization.client_id.identifier + or payload.get("sub") != str(authorization.user_id.id) + or not authorization._is_valid() + ): + raise UnauthorizedInvalidToken() + return authorization + + @api.model + def _revoke_token(self, client, token): + """Token revocation (RFC 7009) of a refresh or access token of + ``client``. Unknown tokens are ignored, as the RFC requires.""" + if not token or not isinstance(token, str): + return + refresh_token = self.env["oauth.server.refresh.token"]._get_by_token(token) + if refresh_token: + if refresh_token.authorization_id.client_id == client: + refresh_token.authorization_id._revoke("client") + return + authorization = self._get_for_unverified_access_token(token) + if authorization and authorization.client_id == client: + authorization._revoke("client") + + @api.model + def _get_for_unverified_access_token(self, token): + try: + claims = jwt.decode(token, options={"verify_signature": False}) + except jwt.PyJWTError: + return self.browse() + audience = claims.get("aud") + resource = self.env["oauth.server.resource"]._get_by_uri( + audience if isinstance(audience, str) else "" + ) + if not resource: + return self.browse() + validator = resource.jwt_validator_id.sudo() + try: + payload = validator._decode(token) + return self._get_for_access_token(validator, payload) + except UnauthorizedInvalidToken: + return self.browse() diff --git a/auth_oauth_server/models/oauth_server_client.py b/auth_oauth_server/models/oauth_server_client.py new file mode 100644 index 0000000000..38789c54a1 --- /dev/null +++ b/auth_oauth_server/models/oauth_server_client.py @@ -0,0 +1,343 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +import logging +import time +from datetime import timedelta +from urllib.parse import urlsplit + +import requests + +from odoo import _, api, fields, models +from odoo.exceptions import ValidationError +from odoo.tools import consteq + +from .. import utils +from ..exceptions import OAuthError +from .oauth_server import AUTH_METHODS + +_logger = logging.getLogger(__name__) + +MAX_REDIRECT_URIS = 10 +MAX_NAME_LENGTH = 200 + + +class OAuthServerClient(models.Model): + """An application that may ask users for access tokens.""" + + _name = "oauth.server.client" + _description = "OAuth Client" + _order = "name, id" + + name = fields.Char(required=True) + identifier = fields.Char( + string="Client ID", + required=True, + readonly=True, + copy=False, + default=lambda self: utils.generate_token(18), + ) + registration_type = fields.Selection( + [ + ("manual", "Manual"), + ("dynamic", "Dynamic Registration"), + ("metadata_document", "Metadata Document"), + ], + default="manual", + required=True, + readonly=True, + help="Manual: created here. Dynamic Registration: the application " + "registered itself, so its name is not verified. Metadata Document: " + "the Client ID is the URL where the application publishes its details.", + ) + client_type = fields.Selection( + [("public", "Public"), ("confidential", "Confidential")], + default="public", + required=True, + help="Confidential clients authenticate with a secret; public ones, " + "such as desktop applications, rely on PKCE alone.", + ) + client_secret_hash = fields.Char(readonly=True, copy=False) + redirect_uris = fields.Text( + string="Redirect URIs", + required=True, + help="One per line. https, or http on localhost; the port of localhost " + "addresses may vary.", + ) + client_uri = fields.Char(string="Homepage", readonly=True) + metadata_expires_at = fields.Datetime(readonly=True) + authorization_ids = fields.One2many( + "oauth.server.authorization", "client_id", readonly=True + ) + authorization_count = fields.Integer(compute="_compute_authorization_count") + active = fields.Boolean(default=True) + + _sql_constraints = [ + ("identifier_uniq", "unique(identifier)", "The Client ID must be unique."), + ] + + @api.depends("authorization_ids") + def _compute_authorization_count(self): + for client in self: + client.authorization_count = len(client.authorization_ids) + + @api.constrains("redirect_uris") + def _check_redirect_uris(self): + for client in self: + uris = client._get_redirect_uris() + if not uris: + raise ValidationError(_("At least one redirect URI is required.")) + for uri in uris: + if not utils.is_valid_redirect_uri(uri): + raise ValidationError( + _( + "Invalid redirect URI %(uri)s: use https, or http " + "on localhost, without fragment.", + uri=uri, + ) + ) + + def _get_redirect_uris(self): + self.ensure_one() + return [ + uri.strip() + for uri in (self.redirect_uris or "").splitlines() + if uri.strip() + ] + + def _check_secret(self, secret): + self.ensure_one() + if not self.client_secret_hash or not isinstance(secret, str) or not secret: + return False + return consteq(utils.hash_token(secret), self.client_secret_hash) + + def action_generate_secret(self): + """Make the client confidential with a new secret, shown only once.""" + self.ensure_one() + secret = utils.generate_token() + self.write( + { + "client_type": "confidential", + "client_secret_hash": utils.hash_token(secret), + } + ) + return { + "type": "ir.actions.act_window", + "res_model": "oauth.server.client.secret", + "name": _("Client Secret"), + "views": [(False, "form")], + "target": "new", + "context": { + "default_identifier": self.identifier, + "default_secret": secret, + }, + } + + # ------------------------------------------------------------------ + # Authorization requests + # ------------------------------------------------------------------ + + @api.model + def _get_for_authorization(self, identifier): + """The client named by the client_id of an authorization request. + + A client_id that is an https URL is resolved as a Client ID Metadata + Document when that is enabled. This is the only place where the + server fetches one: token and revocation requests use the stored + client only. + """ + client = self.with_context(active_test=False).search( + [("identifier", "=", identifier)], limit=1 + ) + if client and not client.active: + raise OAuthError("unauthorized_client", "This application is disabled.") + is_document = ( + client.registration_type == "metadata_document" + if client + else utils.check_metadata_document_url(identifier) + ) + if not is_document: + if not client: + raise OAuthError("invalid_client", "Unknown client.") + return client + if not self.env["oauth.server"]._is_metadata_document_enabled(): + raise OAuthError("invalid_client", "Unknown client.") + return self._get_metadata_document_client(identifier, client) + + @api.model + def _is_trusted_metadata_host(self, hostname): + domains = self.env["oauth.server"]._get_trusted_metadata_domains() + hostname = (hostname or "").lower() + return not domains or any( + hostname == domain or hostname.endswith("." + domain) for domain in domains + ) + + @api.model + def _get_metadata_document_client(self, url, client): + """Fetch (or reuse while fresh) the metadata document at ``url``.""" + now = fields.Datetime.now() + if client and client.metadata_expires_at and client.metadata_expires_at > now: + return client + hostname = urlsplit(url).hostname + if not self._is_trusted_metadata_host(hostname): + raise OAuthError( + "invalid_client", "Applications from this domain are not accepted." + ) + try: + addresses = utils.resolve_host(hostname) + except OSError: + addresses = set() + if not addresses or not all(utils.is_public_address(a) for a in addresses): + raise OAuthError( + "invalid_client", "The client metadata host is not a public address." + ) + try: + document, cache_control = utils.fetch_metadata_document(url) + except (requests.RequestException, ValueError) as error: + _logger.info("Cannot fetch client metadata document %s: %s", url, error) + raise OAuthError( + "invalid_client", "Cannot fetch the client metadata document." + ) from error + values = self._get_metadata_document_values(url, document) + values["metadata_expires_at"] = now + timedelta( + seconds=utils.max_age_from_cache_control(cache_control) + ) + if client: + client.write(values) + return client + values.update(identifier=url, registration_type="metadata_document") + return self.create(values) + + @api.model + def _get_metadata_document_values(self, url, document): + if not isinstance(document, dict) or document.get("client_id") != url: + raise OAuthError( + "invalid_client", "The client metadata document does not match its URL." + ) + name = document.get("client_name") + uris = document.get("redirect_uris") + if not isinstance(name, str) or not name.strip() or len(name) > MAX_NAME_LENGTH: + raise OAuthError("invalid_client", "Invalid client_name.") + if not self._are_valid_redirect_uris(uris): + raise OAuthError("invalid_client", "Invalid redirect_uris.") + # a client may declare another method while also supporting none + supported = document.get("token_endpoint_auth_methods_supported") + if document.get("token_endpoint_auth_method", "none") != "none" and not ( + isinstance(supported, list) and "none" in supported + ): + raise OAuthError( + "invalid_client", + "Only public clients may use a client metadata document.", + ) + return { + "name": name.strip(), + "redirect_uris": "\n".join(uris), + "client_uri": self._get_valid_client_uri(document.get("client_uri")), + "client_type": "public", + } + + @api.model + def _are_valid_redirect_uris(self, uris): + return ( + isinstance(uris, list) + and 0 < len(uris) <= MAX_REDIRECT_URIS + and all(utils.is_valid_redirect_uri(uri) for uri in uris) + ) + + @api.model + def _get_valid_client_uri(self, uri): + if ( + isinstance(uri, str) + and uri.startswith("https://") + and len(uri) <= utils.MAX_URI_LENGTH + ): + return uri + return False + + # ------------------------------------------------------------------ + # Dynamic client registration (RFC 7591) + # ------------------------------------------------------------------ + + @api.model + def _register_dynamic(self, metadata): + """Register a client from an RFC 7591 request; returns the response. + + Fields the server does not use are ignored rather than rejected. + """ + if not isinstance(metadata, dict): + raise OAuthError( + "invalid_client_metadata", "The request must be a JSON object." + ) + uris = metadata.get("redirect_uris") + if not self._are_valid_redirect_uris(uris): + raise OAuthError( + "invalid_redirect_uri", + "Give 1 to %s redirect URIs using https, or http on localhost." + % MAX_REDIRECT_URIS, + ) + method = metadata.get("token_endpoint_auth_method", "client_secret_basic") + if method not in AUTH_METHODS: + raise OAuthError( + "invalid_client_metadata", "Unsupported token_endpoint_auth_method." + ) + grant_types = metadata.get("grant_types", ["authorization_code"]) + if ( + not isinstance(grant_types, list) + or "authorization_code" not in grant_types + or not set(grant_types) <= {"authorization_code", "refresh_token"} + ): + raise OAuthError("invalid_client_metadata", "Unsupported grant_types.") + if metadata.get("response_types", ["code"]) != ["code"]: + raise OAuthError("invalid_client_metadata", "Unsupported response_types.") + name = metadata.get("client_name") or urlsplit(uris[0]).hostname + if not isinstance(name, str) or len(name) > MAX_NAME_LENGTH: + raise OAuthError("invalid_client_metadata", "Invalid client_name.") + secret = utils.generate_token() if method != "none" else None + client = self.create( + { + "name": name, + "registration_type": "dynamic", + "client_type": "confidential" if secret else "public", + "client_secret_hash": secret and utils.hash_token(secret), + "redirect_uris": "\n".join(uris), + "client_uri": self._get_valid_client_uri(metadata.get("client_uri")), + } + ) + response = { + "client_id": client.identifier, + "client_id_issued_at": int(time.time()), + "client_name": client.name, + "redirect_uris": uris, + "grant_types": grant_types, + "response_types": ["code"], + "token_endpoint_auth_method": method, + } + if client.client_uri: + response["client_uri"] = client.client_uri + if secret: + response.update(client_secret=secret, client_secret_expires_at=0) + return response + + @api.autovacuum + def _gc_unused_clients(self): + """Forget self-registered clients no user authorized within a day.""" + limit = fields.Datetime.now() - timedelta(days=1) + self.with_context(active_test=False).search( + [ + ("registration_type", "in", ("dynamic", "metadata_document")), + ("create_date", "<", limit), + ("authorization_ids", "=", False), + ] + ).unlink() + + +class OAuthServerClientSecret(models.AbstractModel): + """Shows a new client secret once, without storing it (like API keys).""" + + _name = "oauth.server.client.secret" + _description = "OAuth Client Secret" + + # the field 'id' is needed by the onchange that fills in the defaults + id = fields.Id() + identifier = fields.Char(string="Client ID", readonly=True) + secret = fields.Char(readonly=True) diff --git a/auth_oauth_server/models/oauth_server_refresh_token.py b/auth_oauth_server/models/oauth_server_refresh_token.py new file mode 100644 index 0000000000..39696a8a52 --- /dev/null +++ b/auth_oauth_server/models/oauth_server_refresh_token.py @@ -0,0 +1,81 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from datetime import timedelta + +from odoo import api, fields, models + +from ..utils import generate_token, hash_token + + +class OAuthServerRefreshToken(models.Model): + """A refresh token, stored as a digest. Each one is used once (rotation).""" + + _name = "oauth.server.refresh.token" + _description = "OAuth Refresh Token" + + token_hash = fields.Char(required=True, readonly=True) + authorization_id = fields.Many2one( + "oauth.server.authorization", + required=True, + readonly=True, + ondelete="cascade", + index=True, + ) + used_at = fields.Datetime(readonly=True) + expires_at = fields.Datetime(required=True, readonly=True) + + _sql_constraints = [ + ("token_hash_uniq", "unique(token_hash)", "Refresh tokens must be unique."), + ] + + @api.model + def _create_for(self, authorization): + """Issue a refresh token for ``authorization``; returns its value.""" + token = generate_token() + lifetime = timedelta(days=authorization.resource_id.refresh_token_lifetime) + self.create( + { + "token_hash": hash_token(token), + "authorization_id": authorization.id, + "expires_at": min( + fields.Datetime.now() + lifetime, authorization.expires_at + ), + } + ) + return token + + @api.model + def _get_by_token(self, token): + if not token or not isinstance(token, str): + return self.browse() + return self.search([("token_hash", "=", hash_token(token))], limit=1) + + def _claim(self): + """Mark the token used, atomically; False if it already was. + + Of two concurrent requests presenting the token, only one updates the + row: the other one waits, fails to serialize, and is retried by Odoo, + which then sees the token used. + """ + self.ensure_one() + self.flush_recordset(["used_at"]) + self.env.cr.execute( + "UPDATE oauth_server_refresh_token SET used_at = %s " + "WHERE id = %s AND used_at IS NULL RETURNING id", + (fields.Datetime.now(), self.id), + ) + claimed = bool(self.env.cr.fetchone()) + self.invalidate_recordset(["used_at"]) + return claimed + + @api.autovacuum + def _gc_refresh_tokens(self): + now = fields.Datetime.now() + self.search( + [ + "|", + ("expires_at", "<", now), + ("used_at", "<", now - timedelta(days=1)), + ] + ).unlink() diff --git a/auth_oauth_server/models/oauth_server_resource.py b/auth_oauth_server/models/oauth_server_resource.py new file mode 100644 index 0000000000..758e040f38 --- /dev/null +++ b/auth_oauth_server/models/oauth_server_resource.py @@ -0,0 +1,278 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +import re + +from odoo import _, api, fields, models +from odoo.exceptions import ValidationError + +from ..exceptions import InsufficientScope, OAuthError +from ..utils import generate_token, normalize_uri + +WELL_KNOWN_RESOURCE = "/.well-known/oauth-protected-resource" + + +class OAuthServerResource(models.Model): + """An API of this Odoo that accepts the access tokens of the server. + + Each resource has its own JWT validator, which signs and checks its + tokens: a token issued for one resource is refused by every other. + """ + + _name = "oauth.server.resource" + _description = "OAuth Protected Resource" + _order = "name, id" + + name = fields.Char(required=True) + path = fields.Char( + required=True, + help="Path of the API on this server, such as /api. Its URI, which " + "applications ask tokens for, is the issuer URL followed by this path.", + ) + uri = fields.Char(string="URI", compute="_compute_uri") + scopes = fields.Char( + help="Space-separated scopes applications may ask for. Tokens get " + "all of them unless the application asks for fewer." + ) + group_ids = fields.Many2many( + "res.groups", + string="Allowed Groups", + help="Users in one of these groups may connect applications to this " + "resource. Leave empty to allow every internal user.", + ) + access_token_lifetime = fields.Integer( + string="Access Token Lifetime (seconds)", default=600, required=True + ) + refresh_token_lifetime = fields.Integer( + string="Refresh Token Lifetime (days)", + default=30, + required=True, + help="An application that does not connect for this long must be " + "authorized again.", + ) + max_lifetime = fields.Integer( + string="Authorization Lifetime (days)", + default=90, + required=True, + help="After this many days the user must authorize the application " + "again, however often it connects.", + ) + jwt_validator_id = fields.Many2one( + "auth.jwt.validator", + string="JWT Validator", + required=True, + readonly=True, + copy=False, + ondelete="cascade", + ) + authorization_ids = fields.One2many( + "oauth.server.authorization", "resource_id", readonly=True + ) + active = fields.Boolean(default=True) + + _sql_constraints = [ + ("path_uniq", "unique(path)", "Another resource already uses this path."), + ( + "lifetimes_positive", + "CHECK(access_token_lifetime > 0 AND refresh_token_lifetime > 0 " + "AND max_lifetime > 0)", + "Lifetimes must be positive.", + ), + ] + + @api.constrains("path") + def _check_path(self): + for resource in self: + path = resource.path + if ( + not path.startswith("/") + or (path != "/" and path.endswith("/")) + or re.search(r"[\s?#]", path) + ): + raise ValidationError( + _( + "The path %(path)s must start with a slash, and contain " + "no trailing slash, query or fragment.", + path=path, + ) + ) + + @api.model + def _uri_for_path(self, path): + issuer = self.env["oauth.server"]._get_issuer() + return issuer if path == "/" else issuer + (path or "") + + @api.depends("path") + def _compute_uri(self): + for resource in self: + resource.uri = self._uri_for_path(resource.path) + + @api.model + def _create_jwt_validator(self, path): + validators = self.env["auth.jwt.validator"].sudo() + base = "oauth_server_" + (re.sub(r"\W+", "_", path or "").strip("_") or "root") + name, counter = base, 1 + while validators.search_count([("name", "=", name)]): + counter += 1 + name = "%s_%s" % (base, counter) + return validators.create( + { + "name": name, + "signature_type": "secret", + "secret_key": generate_token(48), + "secret_algorithm": "HS256", + "audience": self._uri_for_path(path), + "issuer": self.env["oauth.server"]._get_issuer(), + "user_id_strategy": "oauth_server", + "static_user_id": False, + "cookie_enabled": False, + } + ) + + @api.model_create_multi + def create(self, vals_list): + for vals in vals_list: + if not vals.get("jwt_validator_id"): + validator = self._create_jwt_validator(vals.get("path")) + vals["jwt_validator_id"] = validator.id + return super().create(vals_list) + + def write(self, vals): + res = super().write(vals) + if "path" in vals: + self._sync_jwt_validator() + return res + + def unlink(self): + validators = self.jwt_validator_id + res = super().unlink() + validators.sudo().unlink() + return res + + def _sync_jwt_validator(self): + """Follow a change of issuer or path in the validator's iss and aud.""" + self.invalidate_recordset(["uri"]) + issuer = self.env["oauth.server"]._get_issuer() + for resource in self: + validator = resource.jwt_validator_id.sudo() + if validator.issuer != issuer or validator.audience != resource.uri: + validator.write({"issuer": issuer, "audience": resource.uri}) + + def action_rotate_secret(self): + """Invalidate every access token of the resource at once. + + Applications get a new access token with their refresh token. + """ + for resource in self: + resource.jwt_validator_id.sudo().secret_key = generate_token(48) + + # ------------------------------------------------------------------ + # Requests + # ------------------------------------------------------------------ + + def _get_scopes(self): + self.ensure_one() + return (self.scopes or "").split() + + def _filter_scopes(self, requested): + """The scopes to grant for a request: unknown ones are dropped (RFC + 6749 3.3), and no request at all means every scope.""" + allowed = self._get_scopes() + if isinstance(requested, str): + kept = [scope for scope in requested.split() if scope in allowed] + if kept: + return " ".join(dict.fromkeys(kept)) + return " ".join(allowed) + + @api.model + def _get_by_uri(self, uri): + normalized = normalize_uri(uri) + if not normalized: + return self.browse() + for resource in self.search([]): + if normalize_uri(resource.uri) == normalized: + return resource + return self.browse() + + @api.model + def _get_for_request(self, uri): + """The resource named by an RFC 8707 resource parameter. + + Without one, the only active resource is used, if there is only one. + """ + if uri: + resource = self._get_by_uri(uri) + if not resource: + raise OAuthError("invalid_target", "Unknown resource.") + return resource + resources = self.search([]) + if len(resources) != 1: + raise OAuthError("invalid_target", "The resource parameter is required.") + return resources + + def _is_user_allowed(self, user): + self.ensure_one() + user = user.sudo() + if not user.active: + return False + if self.group_ids: + return bool(self.group_ids & user.groups_id) + return user._is_internal() + + # ------------------------------------------------------------------ + # Helpers for the controllers of the resource + # ------------------------------------------------------------------ + + def _get_metadata_url(self): + self.ensure_one() + issuer = self.env["oauth.server"]._get_issuer() + path = "" if self.path == "/" else self.path + return issuer + WELL_KNOWN_RESOURCE + path + + def _metadata(self): + """Protected resource metadata (RFC 9728).""" + self.ensure_one() + return { + "resource": self.uri, + "authorization_servers": [self.env["oauth.server"]._get_issuer()], + "scopes_supported": self._get_scopes(), + "bearer_methods_supported": ["header"], + "resource_name": self.name, + } + + def _www_authenticate(self, error=None, error_description=None, scope=None): + """Value of the WWW-Authenticate header of a 401 or 403 answer. + + It points clients to the resource metadata, from which they discover + the authorization server (RFC 9728 5.1). + """ + self.ensure_one() + scope = self.scopes if scope is None else scope + params = [("resource_metadata", self._get_metadata_url())] + if scope: + params.append(("scope", scope)) + if error: + params.append(("error", error)) + if error_description: + params.append(("error_description", error_description)) + return "Bearer " + ", ".join( + '%s="%s"' % (key, value.replace("\\", "\\\\").replace('"', '\\"')) + for key, value in params + ) + + def _authenticate_bearer(self, token, required_scopes=None): + """Check an access token presented to this resource. + + Returns ``(uid, payload)``. Raises werkzeug's Unauthorized for an + invalid, expired or revoked token, and InsufficientScope when the + token lacks one of ``required_scopes``. + """ + self.ensure_one() + validator = self.jwt_validator_id.sudo() + payload = validator._decode(token) + uid = validator._get_and_check_uid(payload) + required = list(required_scopes or []) + granted = set((payload.get("scope") or "").split()) + if not set(required) <= granted: + raise InsufficientScope(" ".join(required)) + return uid, payload diff --git a/auth_oauth_server/models/res_config_settings.py b/auth_oauth_server/models/res_config_settings.py new file mode 100644 index 0000000000..0677758900 --- /dev/null +++ b/auth_oauth_server/models/res_config_settings.py @@ -0,0 +1,39 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from odoo import fields, models + + +class ResConfigSettings(models.TransientModel): + _inherit = "res.config.settings" + + oauth_server_issuer = fields.Char( + string="OAuth Issuer URL", + config_parameter="auth_oauth_server.issuer", + help="Public address of this Odoo as applications reach it. Changing it " + "invalidates every access token issued so far.", + ) + oauth_server_cimd_enabled = fields.Boolean( + string="Accept Client Metadata Documents", + config_parameter="auth_oauth_server.cimd_enabled", + ) + oauth_server_cimd_trusted_domains = fields.Char( + string="Trusted Application Domains", + config_parameter="auth_oauth_server.cimd_trusted_domains", + help="Comma-separated domains whose metadata documents are accepted. " + "Leave empty to accept any domain.", + ) + oauth_server_dcr_enabled = fields.Boolean( + string="Allow Dynamic Client Registration", + config_parameter="auth_oauth_server.dcr_enabled", + ) + + def set_values(self): + res = super().set_values() + params = self.env["ir.config_parameter"].sudo() + issuer = params.get_param("auth_oauth_server.issuer") + if issuer and issuer != issuer.rstrip("/"): + params.set_param("auth_oauth_server.issuer", issuer.rstrip("/")) + resources = self.env["oauth.server.resource"].sudo() + resources.with_context(active_test=False).search([])._sync_jwt_validator() + return res diff --git a/auth_oauth_server/models/res_users.py b/auth_oauth_server/models/res_users.py new file mode 100644 index 0000000000..4bfe5a7c29 --- /dev/null +++ b/auth_oauth_server/models/res_users.py @@ -0,0 +1,25 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from odoo import fields, models + + +class ResUsers(models.Model): + _inherit = "res.users" + + oauth_server_authorization_ids = fields.One2many( + "oauth.server.authorization", + "user_id", + string="Connected Applications", + domain=[("revoked", "=", False), ("code_used", "=", True)], + ) + + @property + def SELF_READABLE_FIELDS(self): + return super().SELF_READABLE_FIELDS + ["oauth_server_authorization_ids"] + + @property + def SELF_WRITEABLE_FIELDS(self): + # as for api_key_ids: the list sits in the preferences form, whose + # save may send it back; the model refuses commands sent through sudo + return super().SELF_WRITEABLE_FIELDS + ["oauth_server_authorization_ids"] diff --git a/auth_oauth_server/readme/CONFIGURE.md b/auth_oauth_server/readme/CONFIGURE.md new file mode 100644 index 0000000000..14a6e344c7 --- /dev/null +++ b/auth_oauth_server/readme/CONFIGURE.md @@ -0,0 +1,25 @@ +In *Settings > General Settings > OAuth Authorization Server*: + +- **OAuth Issuer URL**: the public HTTPS address of Odoo, as applications reach + it. It is set from `web.base.url` at installation; check it, especially + behind a reverse proxy (where `proxy_mode` must be enabled too). Changing it + invalidates the access tokens issued so far; applications get new ones with + their refresh tokens. +- **Accept Client Metadata Documents**: let applications identify themselves + with the URL of the details they publish, without being registered first. + Odoo then fetches that URL, from public addresses only. Optionally, list the + domains to accept. +- **Allow Dynamic Client Registration**: let applications register themselves. + +Then, in *Settings > Users & Companies > OAuth Server > Protected Resources*, +declare each API that accepts the tokens: its path on this server, the scopes +applications may ask for, the groups whose users may give access (all internal +users when empty), and the lifetime of tokens. + +Applications to be registered by hand go in *OAuth Applications*. Give them +the Client ID and, for confidential ones, the secret shown by *Generate +Secret*. + +With several databases on one server, set `dbfilter` so that each host name +selects one database: the endpoints of this module are called without a +session, so they cannot work otherwise. diff --git a/auth_oauth_server/readme/CONTRIBUTORS.md b/auth_oauth_server/readme/CONTRIBUTORS.md new file mode 100644 index 0000000000..0513642a9c --- /dev/null +++ b/auth_oauth_server/readme/CONTRIBUTORS.md @@ -0,0 +1 @@ +- Lorenzo Battistini diff --git a/auth_oauth_server/readme/DESCRIPTION.md b/auth_oauth_server/readme/DESCRIPTION.md new file mode 100644 index 0000000000..f1ec8daa8f --- /dev/null +++ b/auth_oauth_server/readme/DESCRIPTION.md @@ -0,0 +1,27 @@ +This module makes Odoo an OAuth 2.1 authorization server: applications ask a +user for access, the user logs in on the usual Odoo login page and approves, +and the application receives tokens that let it call an API of Odoo as that +user, with that user's access rights. + +It supports what the [MCP authorization +specification](https://modelcontextprotocol.io/specification/latest/basic/authorization) +requires, so MCP clients can connect to an MCP server hosted in Odoo: + +- authorization code flow with mandatory PKCE (S256), and refresh tokens, + rotated on each use; +- discovery: authorization server metadata (RFC 8414) and protected resource + metadata (RFC 9728); +- applications may be registered by an administrator, register themselves + (RFC 7591), or be identified by the URL of the details they publish + (OAuth Client ID Metadata Documents); +- tokens bound to the API they were asked for (RFC 8707 resource indicators), + `iss` in authorization responses (RFC 9207), token revocation (RFC 7009). + +Access tokens are short-lived JWTs checked by an `auth_jwt` validator, which +the module creates for each protected API. Routes can therefore be protected +with `auth="jwt_"`, as with any other `auth_jwt` validator. +Each token is also checked against the authorization it comes from, so that +revoking an authorization takes effect at once. + +Logging in is left to Odoo: password, two-factor authentication, and login +through another provider (`auth_oauth`, `auth_oidc`, `auth_saml`) all work. diff --git a/auth_oauth_server/readme/ROADMAP.md b/auth_oauth_server/readme/ROADMAP.md new file mode 100644 index 0000000000..cccccfe804 --- /dev/null +++ b/auth_oauth_server/readme/ROADMAP.md @@ -0,0 +1,14 @@ +- Tokens are signed with a secret (HS256) known only to this database, so only + Odoo itself can check them. Asymmetric keys published as a JWKS would let + other servers check them too. +- No OpenID Connect (ID tokens, userinfo), no token introspection, no + `private_key_jwt` client authentication. +- Redirect URIs must use https, or http on localhost: private-use schemes of + native applications are not supported. +- Dynamic client registration is not rate limited; use a reverse proxy, or + disable it. +- A resource created while Odoo runs registers its `auth="jwt_..."` route + method only in the worker that created it (an `auth_jwt` limitation): + restart the workers before using it in routes. +- Users of the portal can authorize applications when a resource allows their + group, but cannot see or revoke them from the portal. diff --git a/auth_oauth_server/readme/USAGE.md b/auth_oauth_server/readme/USAGE.md new file mode 100644 index 0000000000..f99347031f --- /dev/null +++ b/auth_oauth_server/readme/USAGE.md @@ -0,0 +1,33 @@ +Applications discover the server from +`/.well-known/oauth-authorization-server` and each protected API from +`/.well-known/oauth-protected-resource`. When a user connects an +application, Odoo asks them to log in if needed, then shows what the +application asks for and where the user will be sent. Once the user allows it, +the application can call the API. + +Users see the applications they connected in their preferences (*Account +Security* tab) and can revoke them there. Administrators see every +authorization in *Settings > Users & Companies > OAuth Server*. + +To protect a route of your own module, either use the resource's validator in +the route: + +```python +@http.route("/api/orders", auth="jwt_oauth_server_api", type="http") +def orders(self): + if "orders:read" not in request.jwt_payload["scope"].split(): + raise Forbidden() + ... +``` + +or check the token yourself, which also gives you the `WWW-Authenticate` header +that lets clients discover the server: + +```python +resource = request.env.ref("my_module.my_resource").sudo() +try: + uid, payload = resource._authenticate_bearer(token, ["orders:read"]) +except Unauthorized: + headers = [("WWW-Authenticate", resource._www_authenticate())] + ... +``` diff --git a/auth_oauth_server/security/ir.model.access.csv b/auth_oauth_server/security/ir.model.access.csv new file mode 100644 index 0000000000..e7ec2bedcb --- /dev/null +++ b/auth_oauth_server/security/ir.model.access.csv @@ -0,0 +1,6 @@ +id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink +access_oauth_server_resource_system,oauth.server.resource system,model_oauth_server_resource,base.group_system,1,1,1,1 +access_oauth_server_client_system,oauth.server.client system,model_oauth_server_client,base.group_system,1,1,1,1 +access_oauth_server_authorization_system,oauth.server.authorization system,model_oauth_server_authorization,base.group_system,1,0,0,1 +access_oauth_server_authorization_user,oauth.server.authorization user,model_oauth_server_authorization,base.group_user,1,0,0,0 +access_oauth_server_refresh_token_system,oauth.server.refresh.token system,model_oauth_server_refresh_token,base.group_system,1,0,0,1 diff --git a/auth_oauth_server/security/oauth_server_security.xml b/auth_oauth_server/security/oauth_server_security.xml new file mode 100644 index 0000000000..19c98aaa3b --- /dev/null +++ b/auth_oauth_server/security/oauth_server_security.xml @@ -0,0 +1,15 @@ + + + + OAuth authorizations: own ones + + [('user_id', '=', user.id)] + + + + OAuth authorizations: all + + [(1, '=', 1)] + + + diff --git a/auth_oauth_server/static/description/index.html b/auth_oauth_server/static/description/index.html new file mode 100644 index 0000000000..ace1999940 --- /dev/null +++ b/auth_oauth_server/static/description/index.html @@ -0,0 +1,545 @@ + + + + + +README.rst + + + +
+ + + +Odoo Community Association + +
+

OAuth Authorization Server

+ +

Alpha License: LGPL-3 OCA/server-auth Translate me on Weblate Try me on Runboat

+

This module makes Odoo an OAuth 2.1 authorization server: applications +ask a user for access, the user logs in on the usual Odoo login page and +approves, and the application receives tokens that let it call an API of +Odoo as that user, with that user’s access rights.

+

It supports what the MCP authorization +specification +requires, so MCP clients can connect to an MCP server hosted in Odoo:

+
    +
  • authorization code flow with mandatory PKCE (S256), and refresh +tokens, rotated on each use;
  • +
  • discovery: authorization server metadata (RFC 8414) and protected +resource metadata (RFC 9728);
  • +
  • applications may be registered by an administrator, register +themselves (RFC 7591), or be identified by the URL of the details +they publish (OAuth Client ID Metadata Documents);
  • +
  • tokens bound to the API they were asked for (RFC 8707 resource +indicators), iss in authorization responses (RFC 9207), token +revocation (RFC 7009).
  • +
+

Access tokens are short-lived JWTs checked by an auth_jwt validator, +which the module creates for each protected API. Routes can therefore be +protected with auth="jwt_<validator name>", as with any other +auth_jwt validator. Each token is also checked against the +authorization it comes from, so that revoking an authorization takes +effect at once.

+

Logging in is left to Odoo: password, two-factor authentication, and +login through another provider (auth_oauth, auth_oidc, +auth_saml) all work.

+
+

Important

+

This is an alpha version, the data model and design can change at any time without warning. +Only for development or testing purpose, do not use in production. +More details on development status

+
+

Table of contents

+ +
+

Configuration

+

In Settings > General Settings > OAuth Authorization Server:

+
    +
  • OAuth Issuer URL: the public HTTPS address of Odoo, as +applications reach it. It is set from web.base.url at +installation; check it, especially behind a reverse proxy (where +proxy_mode must be enabled too). Changing it invalidates the +access tokens issued so far; applications get new ones with their +refresh tokens.
  • +
  • Accept Client Metadata Documents: let applications identify +themselves with the URL of the details they publish, without being +registered first. Odoo then fetches that URL, from public addresses +only. Optionally, list the domains to accept.
  • +
  • Allow Dynamic Client Registration: let applications register +themselves.
  • +
+

Then, in Settings > Users & Companies > OAuth Server > Protected +Resources, declare each API that accepts the tokens: its path on this +server, the scopes applications may ask for, the groups whose users may +give access (all internal users when empty), and the lifetime of tokens.

+

Applications to be registered by hand go in OAuth Applications. Give +them the Client ID and, for confidential ones, the secret shown by +Generate Secret.

+

With several databases on one server, set dbfilter so that each host +name selects one database: the endpoints of this module are called +without a session, so they cannot work otherwise.

+
+
+

Usage

+

Applications discover the server from +<issuer>/.well-known/oauth-authorization-server and each protected +API from <issuer>/.well-known/oauth-protected-resource<path>. When a +user connects an application, Odoo asks them to log in if needed, then +shows what the application asks for and where the user will be sent. +Once the user allows it, the application can call the API.

+

Users see the applications they connected in their preferences (Account +Security tab) and can revoke them there. Administrators see every +authorization in Settings > Users & Companies > OAuth Server.

+

To protect a route of your own module, either use the resource’s +validator in the route:

+
+@http.route("/api/orders", auth="jwt_oauth_server_api", type="http")
+def orders(self):
+    if "orders:read" not in request.jwt_payload["scope"].split():
+        raise Forbidden()
+    ...
+
+

or check the token yourself, which also gives you the +WWW-Authenticate header that lets clients discover the server:

+
+resource = request.env.ref("my_module.my_resource").sudo()
+try:
+    uid, payload = resource._authenticate_bearer(token, ["orders:read"])
+except Unauthorized:
+    headers = [("WWW-Authenticate", resource._www_authenticate())]
+    ...
+
+
+
+

Known issues / Roadmap

+
    +
  • Tokens are signed with a secret (HS256) known only to this database, +so only Odoo itself can check them. Asymmetric keys published as a +JWKS would let other servers check them too.
  • +
  • No OpenID Connect (ID tokens, userinfo), no token introspection, no +private_key_jwt client authentication.
  • +
  • Redirect URIs must use https, or http on localhost: private-use +schemes of native applications are not supported.
  • +
  • Dynamic client registration is not rate limited; use a reverse proxy, +or disable it.
  • +
  • A resource created while Odoo runs registers its auth="jwt_..." +route method only in the worker that created it (an auth_jwt +limitation): restart the workers before using it in routes.
  • +
  • Users of the portal can authorize applications when a resource allows +their group, but cannot see or revoke them from the portal.
  • +
+
+
+

Bug Tracker

+

Bugs are tracked on GitHub Issues. +In case of trouble, please check there if your issue has already been reported. +If you spotted it first, help us to smash it by providing a detailed and welcomed +feedback.

+

Do not contact contributors directly about support or help with technical issues.

+
+
+

Credits

+
+

Authors

+
    +
  • Lorenzo Battistini
  • +
+
+
+

Contributors

+
    +
  • Lorenzo Battistini
  • +
+
+
+

Maintainers

+

This module is maintained by the OCA.

+ +Odoo Community Association + +

OCA, or the Odoo Community Association, is a nonprofit organization whose +mission is to support the collaborative development of Odoo features and +promote its widespread use.

+

Current maintainer:

+

eLBati

+

This module is part of the OCA/server-auth project on GitHub.

+

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

+
+
+
+
+ + diff --git a/auth_oauth_server/tests/__init__.py b/auth_oauth_server/tests/__init__.py new file mode 100644 index 0000000000..1ce3d604b9 --- /dev/null +++ b/auth_oauth_server/tests/__init__.py @@ -0,0 +1,5 @@ +from . import test_utils +from . import test_resource +from . import test_flow +from . import test_registration +from . import test_controllers diff --git a/auth_oauth_server/tests/common.py b/auth_oauth_server/tests/common.py new file mode 100644 index 0000000000..5846a53eb0 --- /dev/null +++ b/auth_oauth_server/tests/common.py @@ -0,0 +1,88 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). +"""Fixtures shared by the tests. + +Import this module rather than its names: Odoo collects every test class +found in a test module's namespace. +""" + +import secrets + +from odoo.tests.common import new_test_user + +from ..utils import pkce_s256 + +ISSUER = "https://erp.example.com" +REDIRECT_URI = "https://app.example.com/callback" +LOOPBACK_REDIRECT_URI = "http://127.0.0.1/callback" + + +def pkce_pair(): + verifier = secrets.token_urlsafe(48) + return verifier, pkce_s256(verifier) + + +class OAuthServerMixin: + """A resource, a public and a confidential client, and a user.""" + + @classmethod + def setup_oauth_server(cls): + env = cls.env + env["ir.config_parameter"].sudo().set_param("auth_oauth_server.issuer", ISSUER) + cls.resource = env["oauth.server.resource"].create( + {"name": "Test API", "path": "/test_api", "scopes": "read write"} + ) + cls.client = env["oauth.server.client"].create( + { + "name": "Test App", + "redirect_uris": "%s\n%s" % (REDIRECT_URI, LOOPBACK_REDIRECT_URI), + } + ) + cls.confidential_client = env["oauth.server.client"].create( + {"name": "Test Server App", "redirect_uris": REDIRECT_URI} + ) + action = cls.confidential_client.action_generate_secret() + cls.client_secret = action["context"]["default_secret"] + cls.user = new_test_user(env, login="oauth_user") + cls.other_user = new_test_user(env, login="oauth_other") + + def approve(self, client=None, user=None, scopes="read write"): + """What the consent page does: returns (authorization, code, verifier).""" + verifier, challenge = pkce_pair() + authorization, code = self.env[ + "oauth.server.authorization" + ]._create_from_consent( + user or self.user, + client or self.client, + self.resource, + scopes, + REDIRECT_URI, + challenge, + ) + return authorization, code, verifier + + def exchange(self, code, verifier, client=None, **params): + params = dict( + {"code": code, "code_verifier": verifier, "redirect_uri": REDIRECT_URI}, + **params + ) + return self.env["oauth.server.authorization"]._exchange_code( + client or self.client, params + ) + + def refresh(self, refresh_token, client=None, **params): + params = dict({"refresh_token": refresh_token}, **params) + return self.env["oauth.server.authorization"]._refresh( + client or self.client, params + ) + + def tokens(self, client=None, user=None): + """Approve and exchange the code: returns (authorization, tokens).""" + authorization, code, verifier = self.approve(client=client, user=user) + return authorization, self.exchange(code, verifier, client=client) + + def check_token(self, access_token, resource=None): + """The uid an access token runs as on ``resource``.""" + validator = (resource or self.resource).jwt_validator_id + payload = validator._decode(access_token) + return validator._get_and_check_uid(payload) diff --git a/auth_oauth_server/tests/test_controllers.py b/auth_oauth_server/tests/test_controllers.py new file mode 100644 index 0000000000..be508367fb --- /dev/null +++ b/auth_oauth_server/tests/test_controllers.py @@ -0,0 +1,359 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +import base64 +import json +import re +from urllib.parse import parse_qs, urlencode, urlsplit + +from odoo.tests.common import HttpCase, tagged + +from . import common + +CSRF_RE = re.compile(r'name="csrf_token"\s+value="([^"]+)"') +CONSENT_RE = re.compile(r'name="consent"\s+value="([^"]+)"') + + +def query_of(url): + return {key: values[0] for key, values in parse_qs(urlsplit(url).query).items()} + + +@tagged("post_install", "-at_install") +class TestControllers(common.OAuthServerMixin, HttpCase): + """The endpoints, called over HTTP as clients and browsers do.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.setup_oauth_server() + + # ------------------------------------------------------------------ + # Helpers + # ------------------------------------------------------------------ + + def url_open(self, *args, **kwargs): + # the server shares the test cursor but not the test's cache + self.env.flush_all() + response = super().url_open(*args, **kwargs) + self.env.invalidate_all() + return response + + def get_json(self, path, status=200): + response = self.url_open(path) + self.assertEqual(response.status_code, status, response.text) + return response + + def post(self, path, data=None, headers=None): + return self.url_open(path, data=data, headers=headers, allow_redirects=False) + + def authorize_query(self, client=None, **params): + """Query of an authorization request; returns (verifier, query).""" + verifier, challenge = common.pkce_pair() + query = dict( + { + "client_id": (client or self.client).identifier, + "redirect_uri": common.REDIRECT_URI, + "response_type": "code", + "code_challenge": challenge, + "code_challenge_method": "S256", + "resource": self.resource.uri, + "scope": "read", + "state": "xyz", + }, + **params + ) + return verifier, {key: value for key, value in query.items() if value} + + def open_authorize(self, query): + return self.url_open( + "/oauth/authorize?" + urlencode(query), allow_redirects=False + ) + + def consent_form(self, query): + """GET the consent page; returns (csrf_token, consent).""" + response = self.open_authorize(query) + self.assertEqual(response.status_code, 200, response.text) + return CSRF_RE.search(response.text).group(1), CONSENT_RE.search( + response.text + ).group(1) + + def decide(self, csrf_token, consent, decision="approve"): + return self.post( + "/oauth/authorize/decision", + {"csrf_token": csrf_token, "consent": consent, "decision": decision}, + ) + + def token_request(self, data, headers=None): + return self.post("/oauth/token", data, headers) + + # ------------------------------------------------------------------ + # Metadata + # ------------------------------------------------------------------ + + def test_authorization_server_metadata(self): + response = self.get_json("/.well-known/oauth-authorization-server") + self.assertEqual(response.headers.get("Access-Control-Allow-Origin"), "*") + metadata = response.json() + self.assertEqual(metadata["issuer"], common.ISSUER) + self.assertEqual( + metadata["authorization_endpoint"], common.ISSUER + "/oauth/authorize" + ) + self.assertEqual(metadata["token_endpoint"], common.ISSUER + "/oauth/token") + self.assertEqual( + metadata["registration_endpoint"], common.ISSUER + "/oauth/register" + ) + self.assertEqual(metadata["code_challenge_methods_supported"], ["S256"]) + self.assertTrue(metadata["authorization_response_iss_parameter_supported"]) + self.assertTrue(metadata["client_id_metadata_document_supported"]) + self.assertTrue({"read", "write"} <= set(metadata["scopes_supported"])) + self.env["ir.config_parameter"].sudo().set_param( + "auth_oauth_server.dcr_enabled", False + ) + metadata = self.get_json("/.well-known/oauth-authorization-server").json() + self.assertNotIn("registration_endpoint", metadata) + + def test_protected_resource_metadata(self): + metadata = self.get_json( + "/.well-known/oauth-protected-resource/test_api" + ).json() + self.assertEqual(metadata, self.resource._metadata()) + self.get_json("/.well-known/oauth-protected-resource/unknown", 404) + + # ------------------------------------------------------------------ + # Authorization endpoint + # ------------------------------------------------------------------ + + def test_authorize_asks_to_log_in(self): + _verifier, query = self.authorize_query() + response = self.open_authorize(query) + self.assertEqual(response.status_code, 303) + location = response.headers["Location"] + self.assertEqual(urlsplit(location).path, "/web/login") + back = query_of(location)["redirect"] + self.assertEqual(urlsplit(back).path, "/oauth/authorize") + self.assertEqual(query_of(back), query) + + def test_authorization_code_flow(self): + self.authenticate(self.user.login, self.user.login) + verifier, query = self.authorize_query() + response = self.open_authorize(query) + self.assertEqual(response.headers["X-Frame-Options"], "DENY") + self.assertIn( + "frame-ancestors 'none'", response.headers["Content-Security-Policy"] + ) + self.assertIn("Test App", response.text) + self.assertIn("app.example.com", response.text) + csrf_token, consent = self.consent_form(query) + response = self.decide(csrf_token, consent) + self.assertEqual(response.status_code, 303) + location = response.headers["Location"] + self.assertTrue(location.startswith(common.REDIRECT_URI + "?"), location) + answer = query_of(location) + self.assertEqual(answer["state"], "xyz") + self.assertEqual(answer["iss"], common.ISSUER) + response = self.token_request( + { + "grant_type": "authorization_code", + "code": answer["code"], + "code_verifier": verifier, + "redirect_uri": common.REDIRECT_URI, + "client_id": self.client.identifier, + "resource": self.resource.uri, + } + ) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(response.headers["Cache-Control"], "no-store") + tokens = response.json() + self.assertEqual(tokens["scope"], "read") + self.assertEqual(self.check_token(tokens["access_token"]), self.user.id) + response = self.token_request( + { + "grant_type": "refresh_token", + "refresh_token": tokens["refresh_token"], + "client_id": self.client.identifier, + } + ) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual( + self.check_token(response.json()["access_token"]), self.user.id + ) + + def test_deny(self): + self.authenticate(self.user.login, self.user.login) + _verifier, query = self.authorize_query() + response = self.decide(*self.consent_form(query), decision="deny") + self.assertEqual(response.status_code, 303) + answer = query_of(response.headers["Location"]) + self.assertEqual(answer["error"], "access_denied") + self.assertEqual(answer["state"], "xyz") + self.assertEqual(answer["iss"], common.ISSUER) + self.assertNotIn("code", answer) + + def test_decision_is_bound_to_the_request(self): + self.authenticate(self.user.login, self.user.login) + _verifier, query = self.authorize_query() + csrf_token, consent = self.consent_form(query) + tampered = consent[:-1] + ("1" if consent.endswith("0") else "0") + response = self.decide(csrf_token, tampered) + self.assertEqual(response.status_code, 400) + self.assertNotIn("Location", response.headers) + # another user cannot use it + self.authenticate(self.other_user.login, self.other_user.login) + other_csrf_token, _consent = self.consent_form(query) + response = self.decide(other_csrf_token, consent) + self.assertEqual(response.status_code, 400) + self.assertFalse( + self.env["oauth.server.authorization"].search( + [("client_id", "=", self.client.id)] + ) + ) + + def test_authorize_errors(self): + self.authenticate(self.user.login, self.user.login) + # the redirect URI is not trusted: show the error, never redirect + _verifier, query = self.authorize_query( + redirect_uri="https://evil.example.com/callback" + ) + response = self.open_authorize(query) + self.assertEqual(response.status_code, 400) + self.assertNotIn("Location", response.headers) + # a client registered by an administrator gets the error back + _verifier, query = self.authorize_query(code_challenge_method="plain") + response = self.open_authorize(query) + self.assertEqual(response.status_code, 303) + answer = query_of(response.headers["Location"]) + self.assertEqual(answer["error"], "invalid_request") + self.assertEqual(answer["state"], "xyz") + # a self-registered one does not, its redirect URI may be anyone's + registered = self.env["oauth.server.client"]._register_dynamic( + { + "redirect_uris": [common.REDIRECT_URI], + "token_endpoint_auth_method": "none", + } + ) + client = self.env["oauth.server.client"].search( + [("identifier", "=", registered["client_id"])] + ) + _verifier, query = self.authorize_query( + client=client, code_challenge_method="plain" + ) + response = self.open_authorize(query) + self.assertEqual(response.status_code, 400) + self.assertNotIn("Location", response.headers) + + # ------------------------------------------------------------------ + # Token and revocation endpoints + # ------------------------------------------------------------------ + + def test_token_errors(self): + response = self.token_request( + {"grant_type": "authorization_code", "client_id": "unknown"} + ) + self.assertEqual(response.status_code, 401) + self.assertEqual(response.json()["error"], "invalid_client") + self.assertIn("Basic", response.headers["WWW-Authenticate"]) + response = self.token_request( + {"grant_type": "password", "client_id": self.client.identifier} + ) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()["error"], "unsupported_grant_type") + response = self.token_request( + { + "grant_type": "authorization_code", + "code": "unknown", + "client_id": self.client.identifier, + } + ) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()["error"], "invalid_grant") + + def test_code_reuse_revokes_over_http(self): + """The revocation done before answering the error is kept.""" + authorization, code, verifier = self.approve() + data = { + "grant_type": "authorization_code", + "code": code, + "code_verifier": verifier, + "client_id": self.client.identifier, + } + self.assertEqual(self.token_request(data).status_code, 200) + self.assertEqual(self.token_request(data).status_code, 400) + self.assertTrue(authorization.revoked) + + def test_confidential_client_basic_auth(self): + client = self.confidential_client + _authorization, code, verifier = self.approve(client=client) + credentials = "%s:%s" % (client.identifier, self.client_secret) + response = self.token_request( + { + "grant_type": "authorization_code", + "code": code, + "code_verifier": verifier, + }, + headers={ + "Authorization": "Basic " + + base64.b64encode(credentials.encode()).decode() + }, + ) + self.assertEqual(response.status_code, 200, response.text) + + def test_revoke(self): + authorization, tokens = self.tokens() + response = self.post( + "/oauth/revoke", + {"token": tokens["refresh_token"], "client_id": self.client.identifier}, + ) + self.assertEqual(response.status_code, 200) + self.assertTrue(authorization.revoked) + response = self.post( + "/oauth/revoke", {"token": "unknown", "client_id": self.client.identifier} + ) + self.assertEqual(response.status_code, 200) + response = self.post("/oauth/revoke", {"token": "x", "client_id": "unknown"}) + self.assertEqual(response.status_code, 401) + + def test_cors_preflight(self): + response = self.opener.options( + self.base_url() + "/oauth/token", + headers={ + "Origin": "https://inspector.example.com", + "Access-Control-Request-Method": "POST", + }, + ) + self.assertEqual(response.status_code, 204) + self.assertEqual(response.headers["Access-Control-Allow-Origin"], "*") + + # ------------------------------------------------------------------ + # Registration endpoint + # ------------------------------------------------------------------ + + def register(self, body): + return self.post( + "/oauth/register", body, headers={"Content-Type": "application/json"} + ) + + def test_register(self): + response = self.register( + json.dumps( + { + "client_name": "MCP Client", + "redirect_uris": ["http://localhost:6274/callback"], + "token_endpoint_auth_method": "none", + } + ) + ) + self.assertEqual(response.status_code, 201, response.text) + client_id = response.json()["client_id"] + self.assertTrue( + self.env["oauth.server.client"].search([("identifier", "=", client_id)]) + ) + response = self.register("not json") + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()["error"], "invalid_client_metadata") + response = self.register(json.dumps({"client_name": "x" * 20000})) + self.assertEqual(response.status_code, 400) + self.env["ir.config_parameter"].sudo().set_param( + "auth_oauth_server.dcr_enabled", False + ) + response = self.register(json.dumps({"redirect_uris": [common.REDIRECT_URI]})) + self.assertEqual(response.status_code, 404) diff --git a/auth_oauth_server/tests/test_flow.py b/auth_oauth_server/tests/test_flow.py new file mode 100644 index 0000000000..70d6976f76 --- /dev/null +++ b/auth_oauth_server/tests/test_flow.py @@ -0,0 +1,448 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from datetime import timedelta + +import jwt # pylint: disable=missing-manifest-dependency + +from odoo import fields +from odoo.exceptions import AccessError +from odoo.tests.common import TransactionCase, new_test_user, tagged + +from odoo.addons.auth_jwt.exceptions import UnauthorizedInvalidToken + +from ..exceptions import OAuthError +from . import common + + +@tagged("post_install", "-at_install") +class TestFlow(common.OAuthServerMixin, TransactionCase): + """The authorization code flow, model side.""" + + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.setup_oauth_server() + + def assertOAuthError(self, error, function, *args, **kwargs): + with self.assertRaises(OAuthError) as raised: + function(*args, **kwargs) + self.assertEqual(raised.exception.error, error, raised.exception.description) + return raised.exception + + def assertOAuthErrorKeepingChanges(self, error, function, *args, **kwargs): + """assertOAuthError without the savepoint that Odoo's assertRaises + rolls back: the controllers keep what the model did before failing.""" + try: + function(*args, **kwargs) + except OAuthError as raised: + self.assertEqual(raised.error, error, raised.description) + else: + self.fail("%s not raised" % error) + + # ------------------------------------------------------------------ + # Authorization request + # ------------------------------------------------------------------ + + def request_params(self, **params): + _verifier, challenge = common.pkce_pair() + return dict( + { + "client_id": self.client.identifier, + "redirect_uri": common.REDIRECT_URI, + "response_type": "code", + "code_challenge": challenge, + "code_challenge_method": "S256", + "resource": self.resource.uri, + "scope": "read", + "state": "xyz", + }, + **params + ) + + def test_authorization_request(self): + server = self.env["oauth.server"] + params = self.request_params() + client, redirect_uri = server._get_authorization_client(params) + self.assertEqual(client, self.client) + values = server._check_authorization_request( + client, redirect_uri, params, self.user + ) + self.assertEqual(values["resource"], self.resource.id) + self.assertEqual(values["scope"], "read") + self.assertEqual(values["uid"], self.user.id) + self.assertEqual(values["state"], "xyz") + verified = server._verify_consent(server._sign_consent(values)) + verified.pop("exp") + self.assertEqual(verified, values) + code = server._approve(values, self.user) + authorization = self.env["oauth.server.authorization"].search( + [("user_id", "=", self.user.id)] + ) + self.assertEqual(len(authorization), 1) + self.assertEqual(authorization.state, "pending") + self.assertTrue(code) + + def test_authorization_request_client_errors(self): + server = self.env["oauth.server"] + for params in ( + self.request_params(client_id=None), + self.request_params(client_id="unknown"), + self.request_params(redirect_uri="https://evil.example.com/callback"), + self.request_params(redirect_uri=common.REDIRECT_URI + "/"), + self.request_params(redirect_uri=None), + ): + with self.assertRaises(OAuthError): + server._get_authorization_client(params) + self.client.active = False + self.assertOAuthError( + "unauthorized_client", + server._get_authorization_client, + self.request_params(), + ) + + def test_authorization_request_redirect_uri(self): + server = self.env["oauth.server"] + _client, redirect_uri = server._get_authorization_client( + self.request_params(redirect_uri="http://127.0.0.1:43123/callback") + ) + self.assertEqual(redirect_uri, "http://127.0.0.1:43123/callback") + # the only registered redirect URI is the default + _client, redirect_uri = server._get_authorization_client( + self.request_params( + client_id=self.confidential_client.identifier, redirect_uri=None + ) + ) + self.assertEqual(redirect_uri, common.REDIRECT_URI) + + def test_authorization_request_errors(self): + server = self.env["oauth.server"] + check = server._check_authorization_request + args = (self.client, common.REDIRECT_URI) + cases = [ + ("unsupported_response_type", {"response_type": "token"}), + ("invalid_request", {"code_challenge": None}), + ("invalid_request", {"code_challenge_method": "plain"}), + ("invalid_request", {"code_challenge_method": None}), + ("invalid_request", {"code_challenge": "short"}), + ("invalid_request", {"state": "x" * 3000}), + ("invalid_target", {"resource": "https://other.example.com/api"}), + ] + for error, params in cases: + with self.subTest(params=params): + self.assertOAuthError( + error, check, *args, self.request_params(**params), self.user + ) + self.resource.group_ids = self.env["res.groups"].create({"name": "API"}) + self.assertOAuthError( + "access_denied", check, *args, self.request_params(), self.user + ) + + def test_approve_rechecks_access(self): + server = self.env["oauth.server"] + params = self.request_params() + values = server._check_authorization_request( + self.client, common.REDIRECT_URI, params, self.user + ) + self.resource.group_ids = self.env["res.groups"].create({"name": "API"}) + self.assertOAuthError("access_denied", server._approve, values, self.user) + self.client.active = False + self.assertOAuthError("invalid_request", server._approve, values, self.user) + + # ------------------------------------------------------------------ + # Code exchange + # ------------------------------------------------------------------ + + def test_code_exchange(self): + authorization, code, verifier = self.approve(scopes="read") + tokens = self.exchange(code, verifier, resource=self.resource.uri + "/") + self.assertEqual( + set(tokens), + {"access_token", "token_type", "expires_in", "scope", "refresh_token"}, + ) + self.assertEqual(tokens["token_type"], "Bearer") + self.assertEqual(tokens["scope"], "read") + self.assertEqual(tokens["expires_in"], 600) + self.assertEqual(authorization.state, "active") + header = jwt.get_unverified_header(tokens["access_token"]) + self.assertEqual(header["typ"], "at+jwt") + payload = self.resource.jwt_validator_id._decode(tokens["access_token"]) + self.assertEqual(payload["iss"], common.ISSUER) + self.assertEqual(payload["aud"], self.resource.uri) + # recent PyJWT versions refuse non-string sub and jti claims + self.assertEqual(payload["sub"], str(self.user.id)) + self.assertIsInstance(payload["jti"], str) + self.assertEqual(payload["client_id"], self.client.identifier) + self.assertEqual(payload["authorization_id"], authorization.id) + self.assertEqual(self.check_token(tokens["access_token"]), self.user.id) + + def test_code_errors(self): + _authorization, code, verifier = self.approve() + cases = [ + ("invalid_grant", {"code": "unknown"}), + ("invalid_grant", {"code": None}), + ("invalid_grant", {"code_verifier": "x" * 43}), + ("invalid_grant", {"code_verifier": None}), + ("invalid_grant", {"redirect_uri": "http://127.0.0.1/callback"}), + ("invalid_target", {"resource": "https://other.example.com/api"}), + ] + for error, params in cases: + with self.subTest(params=params): + params = dict({"code": code, "code_verifier": verifier}, **params) + self.assertOAuthError( + error, + self.env["oauth.server.authorization"]._exchange_code, + self.client, + dict({"redirect_uri": common.REDIRECT_URI}, **params), + ) + self.assertOAuthError( + "invalid_grant", + self.exchange, + code, + verifier, + client=self.confidential_client, + ) + # none of the failures consumed the code + self.assertTrue(self.exchange(code, verifier)["access_token"]) + + def test_code_expired(self): + authorization, code, verifier = self.approve() + authorization.code_expires_at = fields.Datetime.now() - timedelta(seconds=1) + self.assertOAuthError("invalid_grant", self.exchange, code, verifier) + + def test_code_reuse_revokes(self): + authorization, code, verifier = self.approve() + tokens = self.exchange(code, verifier) + self.assertOAuthErrorKeepingChanges( + "invalid_grant", self.exchange, code, verifier + ) + self.assertTrue(authorization.revoked) + self.assertEqual(authorization.revoked_reason, "code_reuse") + with self.assertRaises(UnauthorizedInvalidToken): + self.check_token(tokens["access_token"]) + self.assertOAuthError("invalid_grant", self.refresh, tokens["refresh_token"]) + + def test_code_after_user_loses_access(self): + _authorization, code, verifier = self.approve() + self.resource.group_ids = self.env["res.groups"].create({"name": "API"}) + self.assertOAuthError("invalid_grant", self.exchange, code, verifier) + + # ------------------------------------------------------------------ + # Refresh + # ------------------------------------------------------------------ + + def test_refresh_rotation(self): + authorization, tokens = self.tokens() + new_tokens = self.refresh(tokens["refresh_token"]) + self.assertNotEqual(new_tokens["refresh_token"], tokens["refresh_token"]) + self.assertEqual(self.check_token(new_tokens["access_token"]), self.user.id) + self.assertTrue(authorization.last_refresh) + # concurrent requests of one client may present the same token twice + self.assertTrue(self.refresh(tokens["refresh_token"])["access_token"]) + self.assertFalse(authorization.revoked) + + def test_refresh_reuse_revokes(self): + authorization, tokens = self.tokens() + new_tokens = self.refresh(tokens["refresh_token"]) + old_token = self.env["oauth.server.refresh.token"]._get_by_token( + tokens["refresh_token"] + ) + old_token.used_at = fields.Datetime.now() - timedelta(minutes=5) + self.assertOAuthErrorKeepingChanges( + "invalid_grant", self.refresh, tokens["refresh_token"] + ) + self.assertEqual(authorization.revoked_reason, "refresh_reuse") + self.assertOAuthError( + "invalid_grant", self.refresh, new_tokens["refresh_token"] + ) + with self.assertRaises(UnauthorizedInvalidToken): + self.check_token(new_tokens["access_token"]) + + def test_refresh_errors(self): + _authorization, tokens = self.tokens() + refresh_token = tokens["refresh_token"] + self.assertOAuthError("invalid_grant", self.refresh, "unknown") + self.assertOAuthError( + "invalid_grant", + self.refresh, + refresh_token, + client=self.confidential_client, + ) + self.assertOAuthError( + "invalid_scope", self.refresh, refresh_token, scope="read admin" + ) + self.assertOAuthError( + "invalid_target", self.refresh, refresh_token, resource="https://x.com/a" + ) + # refused requests do not use the token up + self.assertTrue(self.refresh(refresh_token)["access_token"]) + + def test_refresh_scope_narrowing(self): + _authorization, tokens = self.tokens() + tokens = self.refresh(tokens["refresh_token"], scope="read") + self.assertEqual(tokens["scope"], "read") + payload = self.resource.jwt_validator_id._decode(tokens["access_token"]) + self.assertEqual(payload["scope"], "read") + + def test_refresh_expired(self): + _authorization, tokens = self.tokens() + token = self.env["oauth.server.refresh.token"]._get_by_token( + tokens["refresh_token"] + ) + token.expires_at = fields.Datetime.now() - timedelta(seconds=1) + self.assertOAuthError("invalid_grant", self.refresh, tokens["refresh_token"]) + + def test_authorization_lifetime_caps_tokens(self): + authorization, code, verifier = self.approve() + authorization.expires_at = fields.Datetime.now() + timedelta(seconds=100) + tokens = self.exchange(code, verifier) + self.assertLessEqual(tokens["expires_in"], 100) + token = self.env["oauth.server.refresh.token"]._get_by_token( + tokens["refresh_token"] + ) + self.assertLessEqual(token.expires_at, authorization.expires_at) + authorization.expires_at = fields.Datetime.now() - timedelta(seconds=1) + self.assertOAuthError("invalid_grant", self.refresh, tokens["refresh_token"]) + + # ------------------------------------------------------------------ + # Access tokens presented to the resource + # ------------------------------------------------------------------ + + def test_access_token_checks(self): + """Every change that withdraws access takes effect at once.""" + changes = [ + lambda a: a._revoke("admin"), + lambda a: a.client_id.write({"active": False}), + lambda a: a.resource_id.write({"active": False}), + lambda a: a.user_id.write({"active": False}), + lambda a: a.resource_id.write( + { + "group_ids": [ + (6, 0, self.env["res.groups"].create({"name": "G"}).ids) + ] + } + ), + lambda a: a.write( + {"expires_at": fields.Datetime.now() - timedelta(seconds=1)} + ), + ] + for index, change in enumerate(changes): + with self.subTest(change=index): + user = new_test_user(self.env, login="oauth_change_%s" % index) + client = self.client.copy({"name": "Copy %s" % index}) + authorization, tokens = self.tokens(client=client, user=user) + self.assertEqual(self.check_token(tokens["access_token"]), user.id) + change(authorization.sudo()) + with self.assertRaises(UnauthorizedInvalidToken): + self.check_token(tokens["access_token"]) + self.resource.write({"active": True, "group_ids": [(5,)]}) + + def test_access_token_bound_to_resource(self): + _authorization, tokens = self.tokens() + other = self.env["oauth.server.resource"].create( + {"name": "Other", "path": "/other_api", "scopes": "read write"} + ) + with self.assertRaises(UnauthorizedInvalidToken): + self.check_token(tokens["access_token"], resource=other) + + def test_forged_claims_refused(self): + authorization, tokens = self.tokens() + validator = self.resource.jwt_validator_id + payload = validator._decode(tokens["access_token"]) + other_authorization, _tokens = self.tokens(user=self.other_user) + for claims in ( + {"sub": str(self.other_user.id)}, + {"client_id": self.confidential_client.identifier}, + {"authorization_id": other_authorization.id}, + {"authorization_id": "x"}, + ): + with self.subTest(claims=claims): + forged = jwt.encode( + dict(payload, **claims), validator.secret_key, algorithm="HS256" + ) + with self.assertRaises(UnauthorizedInvalidToken): + self.check_token(forged) + self.assertEqual(authorization.state, "active") + + # ------------------------------------------------------------------ + # Revocation + # ------------------------------------------------------------------ + + def test_revoke_from_preferences(self): + authorization, _tokens = self.tokens() + self.assertIn(authorization, self.user.oauth_server_authorization_ids) + with self.assertRaises(AccessError): + authorization.with_user(self.other_user).action_revoke() + authorization.with_user(self.user).action_revoke() + self.assertEqual(authorization.revoked_reason, "user") + self.user.invalidate_recordset(["oauth_server_authorization_ids"]) + self.assertNotIn(authorization, self.user.oauth_server_authorization_ids) + self.assertFalse(authorization.refresh_token_ids) + + def test_users_see_only_their_authorizations(self): + own, _tokens = self.tokens() + other, _tokens = self.tokens(user=self.other_user) + visible = self.env["oauth.server.authorization"].with_user(self.user).search([]) + self.assertIn(own, visible) + self.assertNotIn(other, visible) + + def test_revoke_token(self): + authorizations = self.env["oauth.server.authorization"] + authorization, tokens = self.tokens() + # tokens of another client are ignored + authorizations._revoke_token(self.confidential_client, tokens["refresh_token"]) + self.assertFalse(authorization.revoked) + authorizations._revoke_token(self.client, tokens["refresh_token"]) + self.assertEqual(authorization.revoked_reason, "client") + authorization, tokens = self.tokens() + authorizations._revoke_token(self.client, tokens["access_token"]) + self.assertTrue(authorization.revoked) + # unknown tokens are ignored + authorizations._revoke_token(self.client, "unknown") + authorizations._revoke_token(self.client, None) + + # ------------------------------------------------------------------ + # Client authentication + # ------------------------------------------------------------------ + + def test_authenticate_client(self): + authenticate = self.env["oauth.server"]._authenticate_client + public, confidential = self.client, self.confidential_client + self.assertEqual(authenticate(public.identifier, None), public) + secret = self.client_secret + self.assertEqual(authenticate(confidential.identifier, secret), confidential) + self.assertEqual( + authenticate(None, None, (confidential.identifier, secret)), confidential + ) + for args in ( + (confidential.identifier, None), + (confidential.identifier, "wrong"), + (None, None, (confidential.identifier, "wrong")), + ("unknown", None), + (None, None), + ): + with self.subTest(args=args): + error = self.assertOAuthError("invalid_client", authenticate, *args) + self.assertEqual(error.status, 401) + self.assertOAuthError( + "invalid_request", + authenticate, + public.identifier, + None, + (confidential.identifier, secret), + ) + + def test_new_secret_replaces_old_one(self): + authenticate = self.env["oauth.server"]._authenticate_client + action = self.confidential_client.action_generate_secret() + new_secret = action["context"]["default_secret"] + self.assertOAuthError( + "invalid_client", + authenticate, + self.confidential_client.identifier, + self.client_secret, + ) + self.assertEqual( + authenticate(self.confidential_client.identifier, new_secret), + self.confidential_client, + ) diff --git a/auth_oauth_server/tests/test_registration.py b/auth_oauth_server/tests/test_registration.py new file mode 100644 index 0000000000..71e3fc0a39 --- /dev/null +++ b/auth_oauth_server/tests/test_registration.py @@ -0,0 +1,307 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from datetime import timedelta +from unittest import mock + +import requests + +from odoo import fields +from odoo.tests.common import TransactionCase, tagged + +from .. import utils +from ..exceptions import OAuthError +from . import common + +DOCUMENT_URL = "https://app.example.com/oauth/client.json" +PUBLIC_ADDRESS = "93.184.216.34" +# the document of ChatGPT, as published at its client_id on 2026-10-20 +CHATGPT_DOCUMENT = { + "client_id": "https://chatgpt.com/oauth/client.json", + "client_uri": "https://chatgpt.com/", + "redirect_uris": ["https://chatgpt.com/connector_platform_oauth_redirect"], + "token_endpoint_auth_method": "private_key_jwt", + "token_endpoint_auth_methods_supported": ["none", "private_key_jwt"], + "grant_types": ["authorization_code", "refresh_token"], + "response_types": ["code"], + "client_name": "ChatGPT", + "logo_uri": "https://persistent.oaistatic.com/sonic/misc/openai-logo.png", + "token_endpoint_auth_signing_alg": "RS256", + "jwks_uri": "https://chatgpt.com/oauth/jwks.json", +} + + +def metadata_document(**values): + return dict( + { + "client_id": DOCUMENT_URL, + "client_name": "Example Client", + "client_uri": "https://app.example.com", + "redirect_uris": ["http://127.0.0.1/callback"], + "token_endpoint_auth_method": "none", + }, + **values + ) + + +@tagged("post_install", "-at_install") +class TestRegistration(common.OAuthServerMixin, TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.setup_oauth_server() + cls.clients = cls.env["oauth.server.client"] + + def assertOAuthError(self, error, function, *args, **kwargs): + with self.assertRaises(OAuthError) as raised: + function(*args, **kwargs) + self.assertEqual(raised.exception.error, error, raised.exception.description) + + # ------------------------------------------------------------------ + # Dynamic client registration + # ------------------------------------------------------------------ + + def test_register_public_client(self): + response = self.clients._register_dynamic( + { + "client_name": "Desktop App", + "redirect_uris": ["http://localhost:3000/callback"], + "token_endpoint_auth_method": "none", + "grant_types": ["authorization_code", "refresh_token"], + "software_id": "ignored", + } + ) + client = self.clients.search([("identifier", "=", response["client_id"])]) + self.assertEqual(client.registration_type, "dynamic") + self.assertEqual(client.client_type, "public") + self.assertEqual(client.name, "Desktop App") + self.assertNotIn("client_secret", response) + self.assertEqual(response["token_endpoint_auth_method"], "none") + self.assertEqual(response["response_types"], ["code"]) + + def test_register_confidential_client(self): + response = self.clients._register_dynamic( + { + "redirect_uris": ["https://web.example.com/callback"], + "token_endpoint_auth_method": "client_secret_post", + "client_uri": "http://not-https.example.com", + } + ) + client = self.clients.search([("identifier", "=", response["client_id"])]) + self.assertEqual(client.client_type, "confidential") + # no client_name: the redirect host stands in for it + self.assertEqual(client.name, "web.example.com") + self.assertFalse(client.client_uri) + self.assertEqual(response["client_secret_expires_at"], 0) + self.assertEqual( + self.env["oauth.server"]._authenticate_client( + response["client_id"], response["client_secret"] + ), + client, + ) + + def test_register_errors(self): + uris = ["https://web.example.com/callback"] + cases = [ + ("invalid_client_metadata", ["not", "an", "object"]), + ("invalid_redirect_uri", {}), + ("invalid_redirect_uri", {"redirect_uris": []}), + ("invalid_redirect_uri", {"redirect_uris": "https://a.example.com/cb"}), + ("invalid_redirect_uri", {"redirect_uris": ["http://web.example.com/cb"]}), + ("invalid_redirect_uri", {"redirect_uris": uris * 11}), + ( + "invalid_client_metadata", + { + "redirect_uris": uris, + "token_endpoint_auth_method": "private_key_jwt", + }, + ), + ( + "invalid_client_metadata", + {"redirect_uris": uris, "grant_types": ["client_credentials"]}, + ), + ( + "invalid_client_metadata", + {"redirect_uris": uris, "response_types": ["token"]}, + ), + ( + "invalid_client_metadata", + {"redirect_uris": uris, "client_name": "x" * 201}, + ), + ] + for error, metadata in cases: + with self.subTest(metadata=metadata): + self.assertOAuthError(error, self.clients._register_dynamic, metadata) + + # ------------------------------------------------------------------ + # Client ID Metadata Documents + # ------------------------------------------------------------------ + + def patch_network(self, document=None, addresses=None, error=None): + fetch = mock.patch.object( + utils, + "fetch_metadata_document", + side_effect=error, + return_value=(document or metadata_document(), "max-age=600"), + ) + resolve = mock.patch.object( + utils, "resolve_host", return_value=addresses or {PUBLIC_ADDRESS} + ) + return fetch, resolve + + def get_client(self, url=DOCUMENT_URL, **kwargs): + fetch, resolve = self.patch_network(**kwargs) + with fetch as fetched, resolve: + client = self.clients._get_for_authorization(url) + return client, fetched + + def test_metadata_document(self): + client, fetched = self.get_client() + fetched.assert_called_once_with(DOCUMENT_URL) + self.assertEqual(client.identifier, DOCUMENT_URL) + self.assertEqual(client.registration_type, "metadata_document") + self.assertEqual(client.client_type, "public") + self.assertEqual(client.name, "Example Client") + self.assertEqual(client._get_redirect_uris(), ["http://127.0.0.1/callback"]) + self.assertGreater(client.metadata_expires_at, fields.Datetime.now()) + # cached while fresh + same, fetched = self.get_client() + self.assertEqual(same, client) + fetched.assert_not_called() + # fetched again once expired + client.metadata_expires_at = fields.Datetime.now() - timedelta(seconds=1) + same, fetched = self.get_client( + document=metadata_document(client_name="Renamed") + ) + fetched.assert_called_once_with(DOCUMENT_URL) + self.assertEqual(same, client) + self.assertEqual(client.name, "Renamed") + + def test_metadata_document_supporting_none(self): + url = CHATGPT_DOCUMENT["client_id"] + client, _fetched = self.get_client(url, document=CHATGPT_DOCUMENT) + self.assertEqual(client.identifier, url) + self.assertEqual(client.client_type, "public") + self.assertEqual(client.name, "ChatGPT") + self.assertEqual( + client._get_redirect_uris(), + ["https://chatgpt.com/connector_platform_oauth_redirect"], + ) + # identified by its client_id alone, without a client assertion + self.assertEqual( + self.env["oauth.server"]._authenticate_client(url, None), client + ) + + def test_metadata_document_errors(self): + cases = [ + {"document": metadata_document(client_id="https://other.example.com/c")}, + {"document": metadata_document(client_name="")}, + {"document": metadata_document(redirect_uris=["http://evil.com/cb"])}, + { + "document": metadata_document( + token_endpoint_auth_method="client_secret_basic" + ) + }, + { + "document": metadata_document( + token_endpoint_auth_method="private_key_jwt", + token_endpoint_auth_methods_supported=["private_key_jwt"], + ) + }, + { + "document": metadata_document( + token_endpoint_auth_method="private_key_jwt", + token_endpoint_auth_methods_supported="none", + ) + }, + {"document": ["not", "a", "dict"]}, + {"addresses": {"10.0.0.5"}}, + {"addresses": {PUBLIC_ADDRESS, "127.0.0.1"}}, + {"error": requests.ConnectionError("down")}, + {"error": ValueError("too large")}, + ] + for kwargs in cases: + with self.subTest(kwargs=kwargs): + fetch, resolve = self.patch_network(**kwargs) + with fetch, resolve: + self.assertOAuthError( + "invalid_client", + self.clients._get_for_authorization, + DOCUMENT_URL, + ) + self.assertFalse(self.clients.search([("identifier", "=", DOCUMENT_URL)])) + + def test_metadata_document_not_a_url(self): + fetch, resolve = self.patch_network() + with fetch as fetched, resolve: + for identifier in ("http://app.example.com/c.json", "unknown-client"): + self.assertOAuthError( + "invalid_client", self.clients._get_for_authorization, identifier + ) + fetched.assert_not_called() + + def test_metadata_document_disabled(self): + params = self.env["ir.config_parameter"].sudo() + params.set_param("auth_oauth_server.cimd_enabled", False) + fetch, resolve = self.patch_network() + with fetch as fetched, resolve: + self.assertOAuthError( + "invalid_client", self.clients._get_for_authorization, DOCUMENT_URL + ) + fetched.assert_not_called() + self.assertFalse( + self.env["oauth.server"]._metadata()[ + "client_id_metadata_document_supported" + ] + ) + + def test_metadata_document_trusted_domains(self): + params = self.env["ir.config_parameter"].sudo() + params.set_param( + "auth_oauth_server.cimd_trusted_domains", "other.com, .example.com" + ) + client, _fetched = self.get_client() + self.assertTrue(client) + params.set_param("auth_oauth_server.cimd_trusted_domains", "other.com") + fetch, resolve = self.patch_network() + with fetch, resolve: + self.assertOAuthError( + "invalid_client", + self.clients._get_for_authorization, + "https://evil.example.org/client.json", + ) + + def test_disabled_metadata_document_client(self): + client, _fetched = self.get_client() + client.active = False + fetch, resolve = self.patch_network() + with fetch, resolve: + self.assertOAuthError( + "unauthorized_client", self.clients._get_for_authorization, DOCUMENT_URL + ) + + # ------------------------------------------------------------------ + # Garbage collection + # ------------------------------------------------------------------ + + def test_unused_clients_are_forgotten(self): + response = self.clients._register_dynamic( + {"redirect_uris": ["https://web.example.com/callback"]} + ) + unused = self.clients.search([("identifier", "=", response["client_id"])]) + response = self.clients._register_dynamic( + {"redirect_uris": ["https://web.example.com/callback"]} + ) + used = self.clients.search([("identifier", "=", response["client_id"])]) + self.approve(client=used) + clients = unused | used | self.client + clients.flush_recordset() + self.env.cr.execute( + "UPDATE oauth_server_client SET create_date = %s WHERE id IN %s", + (fields.Datetime.now() - timedelta(days=2), tuple(clients.ids)), + ) + self.clients._gc_unused_clients() + self.assertFalse(unused.exists()) + self.assertTrue(used.exists()) + # clients created by an administrator are kept + self.assertTrue(self.client.exists()) diff --git a/auth_oauth_server/tests/test_resource.py b/auth_oauth_server/tests/test_resource.py new file mode 100644 index 0000000000..f78621a49a --- /dev/null +++ b/auth_oauth_server/tests/test_resource.py @@ -0,0 +1,167 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from odoo.exceptions import ValidationError +from odoo.tests.common import TransactionCase, tagged + +from odoo.addons.auth_jwt.exceptions import UnauthorizedInvalidToken + +from ..exceptions import InsufficientScope, OAuthError +from . import common + + +@tagged("post_install", "-at_install") +class TestResource(common.OAuthServerMixin, TransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.setup_oauth_server() + + def test_resource_creates_its_validator(self): + validator = self.resource.jwt_validator_id + self.assertEqual(validator.name, "oauth_server_test_api") + self.assertEqual(validator.user_id_strategy, "oauth_server") + self.assertEqual(validator.signature_type, "secret") + self.assertTrue(validator.secret_key) + self.assertFalse(validator.cookie_enabled) + self.assertEqual(validator.issuer, common.ISSUER) + self.assertEqual(validator.audience, common.ISSUER + "/test_api") + self.assertEqual(self.resource.uri, common.ISSUER + "/test_api") + other = self.env["oauth.server.resource"].create( + {"name": "Other", "path": "/test-api"} + ) + self.assertEqual(other.jwt_validator_id.name, "oauth_server_test_api_2") + + def test_root_resource(self): + resource = self.env["oauth.server.resource"].create( + {"name": "Root", "path": "/"} + ) + self.assertEqual(resource.uri, common.ISSUER) + self.assertEqual(resource.jwt_validator_id.name, "oauth_server_root") + self.assertEqual( + resource._get_metadata_url(), + common.ISSUER + "/.well-known/oauth-protected-resource", + ) + + def test_invalid_path(self): + for path in ("api", "/api/", "/api?x=1", "/a b"): + with self.assertRaises(ValidationError, msg=path): + self.env["oauth.server.resource"].create({"name": "X", "path": path}) + + def test_validator_follows_issuer_and_path(self): + settings = self.env["res.config.settings"].create( + {"oauth_server_issuer": "https://new.example.com/"} + ) + settings.set_values() + params = self.env["ir.config_parameter"].sudo() + self.assertEqual( + params.get_param("auth_oauth_server.issuer"), "https://new.example.com" + ) + validator = self.resource.jwt_validator_id + self.assertEqual(validator.issuer, "https://new.example.com") + self.assertEqual(validator.audience, "https://new.example.com/test_api") + self.resource.path = "/renamed" + self.assertEqual(validator.audience, "https://new.example.com/renamed") + + def test_unlink_removes_validator(self): + validator = self.resource.jwt_validator_id + self.resource.unlink() + self.assertFalse(validator.exists()) + + def test_unnamed_jwt_routes_ignore_oauth_validators(self): + """auth="jwt" routes need exactly one validator: those of the + authorization server must not count.""" + validators = self.env["auth.jwt.validator"] + domain = validators._get_validator_by_name_domain(None) + self.assertNotIn(self.resource.jwt_validator_id, validators.search(domain)) + by_name = validators._get_validator_by_name("oauth_server_test_api") + self.assertEqual(by_name, self.resource.jwt_validator_id) + + def test_scopes(self): + self.assertEqual(self.resource._filter_scopes("write"), "write") + self.assertEqual(self.resource._filter_scopes("write read write"), "write read") + # unknown scopes are dropped rather than refused (RFC 6749 3.3) + self.assertEqual(self.resource._filter_scopes("admin write"), "write") + self.assertEqual(self.resource._filter_scopes("admin"), "read write") + self.assertEqual(self.resource._filter_scopes(None), "read write") + + def test_resource_from_request(self): + resources = self.env["oauth.server.resource"] + for uri in ( + common.ISSUER + "/test_api", + common.ISSUER.upper() + "/test_api/", + ): + self.assertEqual(resources._get_for_request(uri), self.resource) + with self.assertRaises(OAuthError) as error: + resources._get_for_request(common.ISSUER + "/unknown") + self.assertEqual(error.exception.error, "invalid_target") + resources.create({"name": "Second", "path": "/second"}) + with self.assertRaises(OAuthError) as error: + resources._get_for_request(None) + self.assertEqual(error.exception.error, "invalid_target") + + def test_allowed_users(self): + portal = self.env["res.users"].create( + { + "name": "Portal", + "login": "oauth_portal", + "groups_id": [(6, 0, [self.env.ref("base.group_portal").id])], + } + ) + self.assertTrue(self.resource._is_user_allowed(self.user)) + self.assertFalse(self.resource._is_user_allowed(portal)) + group = self.env["res.groups"].create({"name": "API users"}) + self.resource.group_ids = group + self.assertFalse(self.resource._is_user_allowed(self.user)) + group.users = self.user + self.assertTrue(self.resource._is_user_allowed(self.user)) + self.user.active = False + self.assertFalse(self.resource._is_user_allowed(self.user)) + + def test_metadata(self): + self.assertEqual( + self.resource._metadata(), + { + "resource": common.ISSUER + "/test_api", + "authorization_servers": [common.ISSUER], + "scopes_supported": ["read", "write"], + "bearer_methods_supported": ["header"], + "resource_name": "Test API", + }, + ) + + def test_www_authenticate(self): + metadata_url = common.ISSUER + "/.well-known/oauth-protected-resource/test_api" + self.assertEqual( + self.resource._www_authenticate(), + 'Bearer resource_metadata="%s", scope="read write"' % metadata_url, + ) + self.assertEqual( + self.resource._www_authenticate( + error="invalid_token", error_description='a "quoted" text', scope="" + ), + 'Bearer resource_metadata="%s", error="invalid_token", ' + 'error_description="a \\"quoted\\" text"' % metadata_url, + ) + + def test_authenticate_bearer(self): + _authorization, tokens = self.tokens() + uid, payload = self.resource._authenticate_bearer( + tokens["access_token"], ["read"] + ) + self.assertEqual(uid, self.user.id) + self.assertEqual(payload["scope"], "read write") + with self.assertRaises(InsufficientScope) as error: + self.resource._authenticate_bearer(tokens["access_token"], ["admin"]) + self.assertEqual(error.exception.scope, "admin") + with self.assertRaises(UnauthorizedInvalidToken): + self.resource._authenticate_bearer("not.a.token") + + def test_rotate_secret(self): + _authorization, tokens = self.tokens() + self.resource.action_rotate_secret() + with self.assertRaises(UnauthorizedInvalidToken): + self.check_token(tokens["access_token"]) + # the refresh token still works and yields a token with the new secret + tokens = self.refresh(tokens["refresh_token"]) + self.assertEqual(self.check_token(tokens["access_token"]), self.user.id) diff --git a/auth_oauth_server/tests/test_utils.py b/auth_oauth_server/tests/test_utils.py new file mode 100644 index 0000000000..d1e0c09b04 --- /dev/null +++ b/auth_oauth_server/tests/test_utils.py @@ -0,0 +1,161 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from unittest import mock + +from odoo.tests.common import TransactionCase + +from .. import utils + + +class FakeResponse: + def __init__(self, status=200, content_type="application/json", body=b"{}"): + self.status_code = status + self.headers = {"Content-Type": content_type, "Cache-Control": "max-age=60"} + self.body = body + self.closed = False + + def iter_content(self, chunk_size=1): + for start in range(0, len(self.body), chunk_size): + yield self.body[start : start + chunk_size] + + def close(self): + self.closed = True + + +class TestUtils(TransactionCase): + def test_redirect_uri_validity(self): + valid = [ + "https://app.example.com/callback", + "https://app.example.com/callback?tenant=1", + "http://localhost:3000/callback", + "http://127.0.0.1/callback", + "http://[::1]:8080/callback", + ] + invalid = [ + "http://app.example.com/callback", + "https://app.example.com/callback#fragment", + "https://user:pass@app.example.com/callback", + "https://app.example.com/call back", + "https://app.example.com:99999/callback", + "myapp://callback", + "", + None, + "https://" + "a" * 3000, + ] + for uri in valid: + self.assertTrue(utils.is_valid_redirect_uri(uri), uri) + for uri in invalid: + self.assertFalse(utils.is_valid_redirect_uri(uri), uri) + + def test_redirect_uri_matching(self): + match = utils.redirect_uri_matches + self.assertTrue(match("https://a.example.com/cb", "https://a.example.com/cb")) + self.assertFalse(match("https://a.example.com/cb", "https://a.example.com/cb/")) + self.assertFalse( + match("https://a.example.com/cb", "https://a.example.com:444/cb") + ) + # the port of loopback redirect URIs may vary (RFC 8252) + self.assertTrue(match("http://127.0.0.1/cb", "http://127.0.0.1:51234/cb")) + self.assertTrue(match("http://localhost:1/cb", "http://localhost:2/cb")) + self.assertFalse(match("http://127.0.0.1/cb", "http://localhost:51234/cb")) + self.assertFalse(match("http://127.0.0.1/cb", "http://127.0.0.1:5/other")) + + def test_add_query_keeps_existing_query(self): + uri = utils.add_query( + "https://a.example.com/cb?tenant=1", {"code": "x y", "state": None} + ) + self.assertEqual(uri, "https://a.example.com/cb?tenant=1&code=x+y") + + def test_normalize_uri(self): + self.assertEqual( + utils.normalize_uri("HTTPS://ERP.Example.com/mcp/"), + "https://erp.example.com/mcp", + ) + self.assertEqual(utils.normalize_uri("erp.example.com"), "") + self.assertEqual(utils.normalize_uri(None), "") + + def test_pkce(self): + verifier = "a" * 43 + challenge = utils.pkce_s256(verifier) + self.assertTrue(utils.check_pkce(verifier, challenge)) + self.assertFalse(utils.check_pkce("b" * 43, challenge)) + self.assertFalse(utils.check_pkce("short", utils.pkce_s256("short"))) + self.assertFalse(utils.check_pkce(None, challenge)) + + def test_sign_verify(self): + signed = utils.sign("secret", "scope", {"uid": 2}, 60) + self.assertEqual(utils.verify("secret", "scope", signed)["uid"], 2) + self.assertIsNone(utils.verify("other", "scope", signed)) + self.assertIsNone(utils.verify("secret", "other", signed)) + body, signature = signed.split(".") + self.assertIsNone(utils.verify("secret", "scope", body + "x." + signature)) + self.assertIsNone(utils.verify("secret", "scope", "garbage")) + expired = utils.sign("secret", "scope", {"uid": 2}, -1) + self.assertIsNone(utils.verify("secret", "scope", expired)) + + def test_metadata_document_url(self): + check = utils.check_metadata_document_url + self.assertTrue(check("https://app.example.com/oauth/client.json")) + self.assertTrue(check("https://app.example.com/client?v=1")) + for url in ( + "http://app.example.com/client.json", + "https://app.example.com", + "https://app.example.com/", + "https://app.example.com:8443/client.json", + "https://user@app.example.com/client.json", + "https://app.example.com/client.json#x", + "https://93.184.216.34/client.json", + "https://[2001:db8::1]/client.json", + "https://app.example.com/a/../client.json", + "https://app.example.com/a/%2e%2e/client.json", + ): + self.assertFalse(check(url), url) + + def test_public_address(self): + self.assertTrue(utils.is_public_address("93.184.216.34")) + self.assertTrue(utils.is_public_address("2606:2800:220:1:248:1893:25c8:1946")) + for address in ( + "127.0.0.1", + "10.1.2.3", + "192.168.1.1", + "169.254.169.254", + "::1", + "fe80::1", + "fe80::1%eth0", + "::ffff:127.0.0.1", + "64:ff9b::a01:203", + "2002:a01:203::1", + "not an address", + ): + self.assertFalse(utils.is_public_address(address), address) + + def test_max_age(self): + self.assertEqual(utils.max_age_from_cache_control("max-age=600"), 600) + self.assertEqual(utils.max_age_from_cache_control("max-age=5"), 300) + self.assertEqual(utils.max_age_from_cache_control("max-age=999999"), 86400) + self.assertEqual(utils.max_age_from_cache_control("no-store"), 300) + self.assertEqual(utils.max_age_from_cache_control(""), 3600) + + def _fetch(self, response): + with mock.patch.object(utils.requests, "get", return_value=response) as get: + try: + return utils.fetch_metadata_document("https://app.example.com/c.json") + finally: + self.assertTrue(response.closed) + kwargs = get.call_args[1] + self.assertFalse(kwargs["allow_redirects"]) + self.assertTrue(kwargs["timeout"]) + + def test_fetch_metadata_document(self): + document, cache_control = self._fetch(FakeResponse(body=b'{"a": 1}')) + self.assertEqual(document, {"a": 1}) + self.assertEqual(cache_control, "max-age=60") + for response in ( + FakeResponse(status=302), + FakeResponse(content_type="text/html"), + FakeResponse(body=b"{" + b" " * 6000 + b"}"), + FakeResponse(body=b"not json"), + ): + with self.assertRaises(ValueError): + self._fetch(response) diff --git a/auth_oauth_server/utils.py b/auth_oauth_server/utils.py new file mode 100644 index 0000000000..5d6825c884 --- /dev/null +++ b/auth_oauth_server/utils.py @@ -0,0 +1,262 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). +"""Stateless helpers of the authorization server. + +The two functions that reach the network, ``resolve_host`` and +``fetch_metadata_document``, are module-level so that tests can patch them. +Call them as ``utils.resolve_host(...)``, never import them by name. +""" + +import base64 +import hashlib +import hmac +import ipaddress +import json +import re +import secrets +import socket +import time +from urllib.parse import parse_qsl, unquote, urlencode, urlsplit, urlunsplit + +import requests + +from odoo.tools import consteq + +TOKEN_BYTES = 32 +MAX_URI_LENGTH = 2048 +PKCE_VERIFIER_RE = re.compile(r"^[A-Za-z0-9\-._~]{43,128}$") +# base64url without padding of a SHA-256 digest +PKCE_CHALLENGE_RE = re.compile(r"^[A-Za-z0-9\-_]{43}$") +LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"} +METADATA_DOCUMENT_MAX_BYTES = 5 * 1024 +METADATA_DOCUMENT_TIMEOUT = 5 +NAT64_NETWORK = ipaddress.ip_network("64:ff9b::/96") + + +def generate_token(nbytes=TOKEN_BYTES): + return secrets.token_urlsafe(nbytes) + + +def hash_token(token): + """Digest under which a high-entropy secret is stored and looked up.""" + return hashlib.sha256(token.encode()).hexdigest() + + +def pkce_s256(verifier): + digest = hashlib.sha256(verifier.encode("ascii")).digest() + return base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=") + + +def check_pkce(verifier, challenge): + if not isinstance(verifier, str) or not PKCE_VERIFIER_RE.match(verifier): + return False + return consteq(pkce_s256(verifier), challenge or "") + + +# ---------------------------------------------------------------------- +# URIs +# ---------------------------------------------------------------------- + + +def _split(uri): + """urlsplit() that also validates the port; None for unusable URIs.""" + if not isinstance(uri, str) or not uri or len(uri) > MAX_URI_LENGTH: + return None + if any(char.isspace() for char in uri): + return None + try: + parts = urlsplit(uri) + parts.port # pylint: disable=pointless-statement + except ValueError: + return None + return parts + + +def is_loopback_host(hostname): + return (hostname or "").lower() in LOOPBACK_HOSTS + + +def is_valid_redirect_uri(uri): + """Redirect URIs must use https, or http on a loopback host (RFC 8252).""" + parts = _split(uri) + if not parts or "#" in uri or not parts.hostname: + return False + if parts.username is not None or parts.password is not None: + return False + if parts.scheme == "https": + return True + return parts.scheme == "http" and is_loopback_host(parts.hostname) + + +def redirect_uri_matches(registered, requested): + """Exact match, except the port of loopback redirect URIs (RFC 8252 7.3).""" + if registered == requested: + return True + reg, req = _split(registered), _split(requested) + if not reg or not req: + return False + return ( + reg.scheme == req.scheme == "http" + and is_loopback_host(reg.hostname) + and reg.hostname == req.hostname + and reg.path == req.path + and reg.query == req.query + ) + + +def add_query(uri, params): + """Append ``params`` to ``uri``, keeping the query it already has.""" + parts = urlsplit(uri) + query = parse_qsl(parts.query, keep_blank_values=True) + query.extend((key, value) for key, value in params.items() if value is not None) + return urlunsplit(parts._replace(query=urlencode(query))) + + +def normalize_uri(uri): + """Compare resource URIs case-insensitively on scheme and host, and + regardless of a trailing slash.""" + parts = _split(uri) + if not parts or not parts.scheme or not parts.netloc: + return "" + return urlunsplit( + ( + parts.scheme.lower(), + parts.netloc.lower(), + parts.path.rstrip("/"), + parts.query, + "", + ) + ) + + +# ---------------------------------------------------------------------- +# Signed values +# ---------------------------------------------------------------------- + + +def _signature(secret, scope, body): + message = ("%s:%s" % (scope, body)).encode() + return hmac.new(secret.encode(), message, hashlib.sha256).hexdigest() + + +def sign(secret, scope, values, max_age): + """Serialize ``values`` into a URL-safe string signed with ``secret``.""" + payload = dict(values, exp=int(time.time()) + max_age) + body = json.dumps(payload, sort_keys=True).encode() + body = base64.urlsafe_b64encode(body).decode().rstrip("=") + return "%s.%s" % (body, _signature(secret, scope, body)) + + +def verify(secret, scope, signed): + """The values given to sign(), or None if tampered with or expired.""" + if not isinstance(signed, str) or "." not in signed: + return None + body, _sep, signature = signed.rpartition(".") + if not consteq(signature, _signature(secret, scope, body)): + return None + try: + payload = json.loads(base64.urlsafe_b64decode(body + "=" * (-len(body) % 4))) + except ValueError: + return None + if not isinstance(payload, dict) or payload.get("exp", 0) < time.time(): + return None + return payload + + +# ---------------------------------------------------------------------- +# Client ID Metadata Documents +# ---------------------------------------------------------------------- + + +def is_ip_literal(hostname): + try: + ipaddress.ip_address(hostname) + except ValueError: + return False + return True + + +def check_metadata_document_url(url): + """Whether ``url`` is acceptable as a client_id to fetch metadata from. + + Besides the rules of the Client ID Metadata Document draft, only the + default https port and host names (no IP literal) are accepted, to limit + what an attacker can make the server request. + """ + parts = _split(url) + if not parts or parts.scheme != "https" or not parts.hostname: + return False + if parts.port is not None or "#" in url: + return False + if parts.username is not None or parts.password is not None: + return False + if is_ip_literal(parts.hostname): + return False + segments = {unquote(segment) for segment in parts.path.split("/")} + if parts.path in ("", "/") or segments & {".", ".."}: + return False + return True + + +def is_public_address(address): + """Only globally routable addresses may be fetched (SSRF protection).""" + try: + ip = ipaddress.ip_address(address) + except ValueError: + # includes IPv6 addresses carrying a zone index + return False + if ip.version == 6 and ( + ip.ipv4_mapped or ip.sixtofour or ip.teredo or ip in NAT64_NETWORK + ): + return False + return ip.is_global + + +def resolve_host(hostname): + infos = socket.getaddrinfo(hostname, 443, type=socket.SOCK_STREAM) + return {info[4][0] for info in infos} + + +def fetch_metadata_document(url): + """GET a Client ID Metadata Document. + + Returns ``(document, cache_control)``. Raises ValueError for anything but + a small JSON document answered directly (no redirect) within the timeout, + and requests.RequestException for network errors. + """ + deadline = time.monotonic() + METADATA_DOCUMENT_TIMEOUT + response = requests.get( + url, + timeout=METADATA_DOCUMENT_TIMEOUT, + allow_redirects=False, + stream=True, + headers={"Accept": "application/json", "Accept-Encoding": "identity"}, + ) + try: + if response.status_code != 200: + raise ValueError("HTTP status %s" % response.status_code) + content_type = response.headers.get("Content-Type", "") + content_type = content_type.split(";")[0].strip().lower() + if content_type != "application/json" and not content_type.endswith("+json"): + raise ValueError("unexpected content type %r" % content_type) + size, chunks = 0, [] + for chunk in response.iter_content(chunk_size=1024): + size += len(chunk) + if size > METADATA_DOCUMENT_MAX_BYTES: + raise ValueError("document larger than %s bytes" % size) + if time.monotonic() > deadline: + raise ValueError("document not received in time") + chunks.append(chunk) + return json.loads(b"".join(chunks)), response.headers.get("Cache-Control", "") + finally: + response.close() + + +def max_age_from_cache_control(header, default=3600, minimum=300, maximum=86400): + """How long to keep a metadata document, bounded to [minimum, maximum].""" + header = (header or "").lower() + if "no-store" in header or "no-cache" in header: + return minimum + match = re.search(r"max-age=(\d+)", header) + seconds = int(match.group(1)) if match else default + return max(minimum, min(maximum, seconds)) diff --git a/auth_oauth_server/views/auth_jwt_validator_views.xml b/auth_oauth_server/views/auth_jwt_validator_views.xml new file mode 100644 index 0000000000..dcc53b625d --- /dev/null +++ b/auth_oauth_server/views/auth_jwt_validator_views.xml @@ -0,0 +1,39 @@ + + + + + auth.jwt.validator.form.oauth_server + auth.jwt.validator + + + + {'readonly': [('user_id_strategy', '=', 'oauth_server')]} + + + {'readonly': [('user_id_strategy', '=', 'oauth_server')]} + + + {'readonly': [('user_id_strategy', '=', 'oauth_server')]} + + + { + 'invisible': [('signature_type', '!=', 'secret')], + 'required': [('signature_type', '=', 'secret')], + 'readonly': [('user_id_strategy', '=', 'oauth_server')]} + + + + + + + diff --git a/auth_oauth_server/views/oauth_server_authorization_views.xml b/auth_oauth_server/views/oauth_server_authorization_views.xml new file mode 100644 index 0000000000..d103b2cd6a --- /dev/null +++ b/auth_oauth_server/views/oauth_server_authorization_views.xml @@ -0,0 +1,102 @@ + + + + oauth.server.authorization.tree + oauth.server.authorization + + + + + + + + + + + + + + + oauth.server.authorization.form + oauth.server.authorization + +
+
+
+ + + + + + + + + + + + + + + + + + +
+
+
+ + oauth.server.authorization.search + oauth.server.authorization + + + + + + + + + + + + + + + + OAuth Authorizations + oauth.server.authorization + tree,form + {'search_default_not_revoked': 1} + +
diff --git a/auth_oauth_server/views/oauth_server_client_views.xml b/auth_oauth_server/views/oauth_server_client_views.xml new file mode 100644 index 0000000000..86a16bf903 --- /dev/null +++ b/auth_oauth_server/views/oauth_server_client_views.xml @@ -0,0 +1,139 @@ + + + + oauth.server.client.tree + oauth.server.client + + + + + + + + + + + + oauth.server.client.form + oauth.server.client + +
+
+
+ + +
+

+ +

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + oauth.server.client.search + oauth.server.client + + + + + + + + + + + + + + + + OAuth Applications + oauth.server.client + tree,form + + + oauth.server.client.secret.form + oauth.server.client.secret + +
+

+ Copy the secret now and give it to the application: it is + not stored and cannot be shown again. +

+ + + + +
+
+
+
+
+
diff --git a/auth_oauth_server/views/oauth_server_menus.xml b/auth_oauth_server/views/oauth_server_menus.xml new file mode 100644 index 0000000000..49303580f1 --- /dev/null +++ b/auth_oauth_server/views/oauth_server_menus.xml @@ -0,0 +1,28 @@ + + + + + + + diff --git a/auth_oauth_server/views/oauth_server_resource_views.xml b/auth_oauth_server/views/oauth_server_resource_views.xml new file mode 100644 index 0000000000..764af6da47 --- /dev/null +++ b/auth_oauth_server/views/oauth_server_resource_views.xml @@ -0,0 +1,79 @@ + + + + oauth.server.resource.tree + oauth.server.resource + + + + + + + + + + + oauth.server.resource.form + oauth.server.resource + +
+
+
+ + +
+

+ +

+
+ + + + + + + + + + + + + + + +
+
+
+
+ + oauth.server.resource.search + oauth.server.resource + + + + + + + + + + Protected Resources + oauth.server.resource + tree,form + +
diff --git a/auth_oauth_server/views/oauth_server_templates.xml b/auth_oauth_server/views/oauth_server_templates.xml new file mode 100644 index 0000000000..c19741c3ba --- /dev/null +++ b/auth_oauth_server/views/oauth_server_templates.xml @@ -0,0 +1,69 @@ + + + + + + diff --git a/auth_oauth_server/views/res_config_settings_views.xml b/auth_oauth_server/views/res_config_settings_views.xml new file mode 100644 index 0000000000..300d198d85 --- /dev/null +++ b/auth_oauth_server/views/res_config_settings_views.xml @@ -0,0 +1,74 @@ + + + + res.config.settings.view.form.oauth_server + res.config.settings + + + +

OAuth Authorization Server

+
+
+
+
+
+
+
+ +
+
+
+
+
+
+ +
+
+
+
+
+
+
+
+
diff --git a/auth_oauth_server/views/res_users_views.xml b/auth_oauth_server/views/res_users_views.xml new file mode 100644 index 0000000000..a0a66e83a9 --- /dev/null +++ b/auth_oauth_server/views/res_users_views.xml @@ -0,0 +1,44 @@ + + + + res.users.preferences.form.oauth_server + res.users + + + + +
+ Applications you allowed to act on your behalf. Revoke + one to disconnect it at once. +
+
+ + + + + + +
+
+
+
+
+
From b84debfc3a99e431bd0ad1dded482ea8288572e7 Mon Sep 17 00:00:00 2001 From: "lorenzo.carta" Date: Tue, 17 Nov 2026 15:47:41 +0100 Subject: [PATCH 2/5] [IMP] auth_oauth_server: pre-commit auto fixes --- auth_oauth_server/pyproject.toml | 3 +++ auth_oauth_server/tests/common.py | 2 +- auth_oauth_server/tests/test_controllers.py | 2 +- auth_oauth_server/tests/test_flow.py | 2 +- auth_oauth_server/tests/test_registration.py | 2 +- auth_oauth_server/views/oauth_server_templates.xml | 4 ++-- 6 files changed, 9 insertions(+), 6 deletions(-) create mode 100644 auth_oauth_server/pyproject.toml diff --git a/auth_oauth_server/pyproject.toml b/auth_oauth_server/pyproject.toml new file mode 100644 index 0000000000..4231d0cccb --- /dev/null +++ b/auth_oauth_server/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/auth_oauth_server/tests/common.py b/auth_oauth_server/tests/common.py index 5846a53eb0..95b3fe311c 100644 --- a/auth_oauth_server/tests/common.py +++ b/auth_oauth_server/tests/common.py @@ -64,7 +64,7 @@ def approve(self, client=None, user=None, scopes="read write"): def exchange(self, code, verifier, client=None, **params): params = dict( {"code": code, "code_verifier": verifier, "redirect_uri": REDIRECT_URI}, - **params + **params, ) return self.env["oauth.server.authorization"]._exchange_code( client or self.client, params diff --git a/auth_oauth_server/tests/test_controllers.py b/auth_oauth_server/tests/test_controllers.py index be508367fb..e017163bb0 100644 --- a/auth_oauth_server/tests/test_controllers.py +++ b/auth_oauth_server/tests/test_controllers.py @@ -60,7 +60,7 @@ def authorize_query(self, client=None, **params): "scope": "read", "state": "xyz", }, - **params + **params, ) return verifier, {key: value for key, value in query.items() if value} diff --git a/auth_oauth_server/tests/test_flow.py b/auth_oauth_server/tests/test_flow.py index 70d6976f76..60f070b3ff 100644 --- a/auth_oauth_server/tests/test_flow.py +++ b/auth_oauth_server/tests/test_flow.py @@ -57,7 +57,7 @@ def request_params(self, **params): "scope": "read", "state": "xyz", }, - **params + **params, ) def test_authorization_request(self): diff --git a/auth_oauth_server/tests/test_registration.py b/auth_oauth_server/tests/test_registration.py index 71e3fc0a39..0b0b6aa9d4 100644 --- a/auth_oauth_server/tests/test_registration.py +++ b/auth_oauth_server/tests/test_registration.py @@ -40,7 +40,7 @@ def metadata_document(**values): "redirect_uris": ["http://127.0.0.1/callback"], "token_endpoint_auth_method": "none", }, - **values + **values, ) diff --git a/auth_oauth_server/views/oauth_server_templates.xml b/auth_oauth_server/views/oauth_server_templates.xml index c19741c3ba..c7d596bad1 100644 --- a/auth_oauth_server/views/oauth_server_templates.xml +++ b/auth_oauth_server/views/oauth_server_templates.xml @@ -20,8 +20,8 @@

Scopes: - - + +

You will then be sent to . From 3e40a69710b1e7da4c6a10fea4a87ff5acaa39ad Mon Sep 17 00:00:00 2001 From: "lorenzo.carta" Date: Tue, 17 Nov 2026 15:54:22 +0100 Subject: [PATCH 3/5] [MIG] auth_oauth_server: Migration to 18.0 - post_init_hook takes the environment; - settings in a block of their own, with the 17.0 setting layout; - attrs turned into Python expressions, tree into list; the fields only used in expressions are no longer declared invisible; the actions have a path; - the token, revocation and registration endpoints declare a read/write cursor: auth="none" routes are read-only by default since 17.2; - the tests remove the auth="jwt_..." methods auth_jwt adds to ir.http for the validators of the resources, which Odoo now reports as leaked; - f-strings and no bare expression, as ruff now requires. --- auth_oauth_server/README.rst | 16 ++- auth_oauth_server/__manifest__.py | 2 +- auth_oauth_server/controllers/main.py | 6 ++ auth_oauth_server/hooks.py | 5 +- .../models/oauth_server_client.py | 4 +- .../models/oauth_server_resource.py | 4 +- .../static/description/index.html | 34 +++--- auth_oauth_server/tests/common.py | 37 ++++++- auth_oauth_server/tests/test_controllers.py | 2 +- auth_oauth_server/tests/test_flow.py | 6 +- auth_oauth_server/tests/test_resource.py | 6 +- auth_oauth_server/utils.py | 12 +-- .../views/auth_jwt_validator_views.xml | 21 ++-- .../oauth_server_authorization_views.xml | 17 ++- .../views/oauth_server_client_views.xml | 26 ++--- .../views/oauth_server_resource_views.xml | 14 +-- .../views/res_config_settings_views.xml | 100 +++++++----------- auth_oauth_server/views/res_users_views.xml | 6 +- 18 files changed, 157 insertions(+), 161 deletions(-) diff --git a/auth_oauth_server/README.rst b/auth_oauth_server/README.rst index 9d0eb737ba..5be767c6f4 100644 --- a/auth_oauth_server/README.rst +++ b/auth_oauth_server/README.rst @@ -1,7 +1,3 @@ -.. image:: https://odoo-community.org/readme-banner-image - :target: https://odoo-community.org/get-involved?utm_source=readme - :alt: Odoo Community Association - ========================== OAuth Authorization Server ========================== @@ -17,17 +13,17 @@ OAuth Authorization Server .. |badge1| image:: https://img.shields.io/badge/maturity-Alpha-red.png :target: https://odoo-community.org/page/development-status :alt: Alpha -.. |badge2| image:: https://img.shields.io/badge/license-LGPL--3-blue.png +.. |badge2| image:: https://img.shields.io/badge/licence-LGPL--3-blue.png :target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html :alt: License: LGPL-3 .. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fserver--auth-lightgray.png?logo=github - :target: https://github.com/OCA/server-auth/tree/16.0/auth_oauth_server + :target: https://github.com/OCA/server-auth/tree/18.0/auth_oauth_server :alt: OCA/server-auth .. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png - :target: https://translation.odoo-community.org/projects/server-auth-16-0/server-auth-16-0-auth_oauth_server + :target: https://translation.odoo-community.org/projects/server-auth-18-0/server-auth-18-0-auth_oauth_server :alt: Translate me on Weblate .. |badge5| image:: https://img.shields.io/badge/runboat-Try%20me-875A7B.png - :target: https://runboat.odoo-community.org/builds?repo=OCA/server-auth&target_branch=16.0 + :target: https://runboat.odoo-community.org/builds?repo=OCA/server-auth&target_branch=18.0 :alt: Try me on Runboat |badge1| |badge2| |badge3| |badge4| |badge5| @@ -165,7 +161,7 @@ Bug Tracker Bugs are tracked on `GitHub Issues `_. In case of trouble, please check there if your issue has already been reported. If you spotted it first, help us to smash it by providing a detailed and welcomed -`feedback `_. +`feedback `_. Do not contact contributors directly about support or help with technical issues. @@ -203,6 +199,6 @@ Current `maintainer `__: |maintainer-eLBati| -This module is part of the `OCA/server-auth `_ project on GitHub. +This module is part of the `OCA/server-auth `_ project on GitHub. You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/auth_oauth_server/__manifest__.py b/auth_oauth_server/__manifest__.py index 0b1292c4d0..65d1a9bca1 100644 --- a/auth_oauth_server/__manifest__.py +++ b/auth_oauth_server/__manifest__.py @@ -4,7 +4,7 @@ { "name": "OAuth Authorization Server", "summary": "Let applications obtain OAuth 2.1 access tokens for Odoo users", - "version": "16.0.1.0.0", + "version": "18.0.1.0.0", "category": "Tools", "license": "LGPL-3", "author": "Lorenzo Battistini, Odoo Community Association (OCA)", diff --git a/auth_oauth_server/controllers/main.py b/auth_oauth_server/controllers/main.py index d1664d1760..f89903f9d0 100644 --- a/auth_oauth_server/controllers/main.py +++ b/auth_oauth_server/controllers/main.py @@ -202,6 +202,9 @@ def _page(template, qcontext, status=200): # ------------------------------------------------------------------ # Token, revocation and registration endpoints # ------------------------------------------------------------------ + # These endpoints write, and auth="none" makes a route read-only by + # default since Odoo 17.2: they declare readonly=False rather than rely on + # the retry on a read/write cursor, which would run the flow twice. @staticmethod def _basic_credentials(): @@ -218,6 +221,7 @@ def _basic_credentials(): cors="*", csrf=False, save_session=False, + readonly=False, ) def token(self, **params): env = self._env() @@ -247,6 +251,7 @@ def token(self, **params): cors="*", csrf=False, save_session=False, + readonly=False, ) def revoke(self, **params): env = self._env() @@ -269,6 +274,7 @@ def revoke(self, **params): cors="*", csrf=False, save_session=False, + readonly=False, ) def register(self): env = self._env() diff --git a/auth_oauth_server/hooks.py b/auth_oauth_server/hooks.py index e8a4ce70bf..9305bb4727 100644 --- a/auth_oauth_server/hooks.py +++ b/auth_oauth_server/hooks.py @@ -1,17 +1,14 @@ # Copyright 2026 Lorenzo Battistini # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). -from odoo import SUPERUSER_ID, api - -def post_init_hook(cr, registry): +def post_init_hook(env): """Pin the issuer to the current base URL and enable client registration. The issuer is a parameter of its own because ``web.base.url`` is rewritten on every administrator login unless frozen, and every change of issuer invalidates the access tokens issued so far. """ - env = api.Environment(cr, SUPERUSER_ID, {}) params = env["ir.config_parameter"] if not params.get_param("auth_oauth_server.issuer"): base_url = params.get_param("web.base.url") or "" diff --git a/auth_oauth_server/models/oauth_server_client.py b/auth_oauth_server/models/oauth_server_client.py index 38789c54a1..9bb601c2a3 100644 --- a/auth_oauth_server/models/oauth_server_client.py +++ b/auth_oauth_server/models/oauth_server_client.py @@ -272,8 +272,8 @@ def _register_dynamic(self, metadata): if not self._are_valid_redirect_uris(uris): raise OAuthError( "invalid_redirect_uri", - "Give 1 to %s redirect URIs using https, or http on localhost." - % MAX_REDIRECT_URIS, + f"Give 1 to {MAX_REDIRECT_URIS} redirect URIs using https, " + "or http on localhost.", ) method = metadata.get("token_endpoint_auth_method", "client_secret_basic") if method not in AUTH_METHODS: diff --git a/auth_oauth_server/models/oauth_server_resource.py b/auth_oauth_server/models/oauth_server_resource.py index 758e040f38..cf6557ca86 100644 --- a/auth_oauth_server/models/oauth_server_resource.py +++ b/auth_oauth_server/models/oauth_server_resource.py @@ -114,7 +114,7 @@ def _create_jwt_validator(self, path): name, counter = base, 1 while validators.search_count([("name", "=", name)]): counter += 1 - name = "%s_%s" % (base, counter) + name = f"{base}_{counter}" return validators.create( { "name": name, @@ -256,7 +256,7 @@ def _www_authenticate(self, error=None, error_description=None, scope=None): if error_description: params.append(("error_description", error_description)) return "Bearer " + ", ".join( - '%s="%s"' % (key, value.replace("\\", "\\\\").replace('"', '\\"')) + '{}="{}"'.format(key, value.replace("\\", "\\\\").replace('"', '\\"')) for key, value in params ) diff --git a/auth_oauth_server/static/description/index.html b/auth_oauth_server/static/description/index.html index ace1999940..c89683e3a9 100644 --- a/auth_oauth_server/static/description/index.html +++ b/auth_oauth_server/static/description/index.html @@ -3,7 +3,7 @@ -README.rst +OAuth Authorization Server -

+
+

OAuth Authorization Server

- - -Odoo Community Association - -
-

OAuth Authorization Server

-

Alpha License: LGPL-3 OCA/server-auth Translate me on Weblate Try me on Runboat

+

Alpha License: LGPL-3 OCA/server-auth Translate me on Weblate Try me on Runboat

This module makes Odoo an OAuth 2.1 authorization server: applications ask a user for access, the user logs in on the usual Odoo login page and approves, and the application receives tokens that let it call an API of @@ -425,7 +420,7 @@

OAuth Authorization Server

-

Configuration

+

Configuration

In Settings > General Settings > OAuth Authorization Server:

  • OAuth Issuer URL: the public HTTPS address of Odoo, as @@ -453,7 +448,7 @@

    Configuration

    without a session, so they cannot work otherwise.

-

Usage

+

Usage

Applications discover the server from <issuer>/.well-known/oauth-authorization-server and each protected API from <issuer>/.well-known/oauth-protected-resource<path>. When a @@ -484,7 +479,7 @@

Usage

-

Known issues / Roadmap

+

Known issues / Roadmap

  • Tokens are signed with a secret (HS256) known only to this database, so only Odoo itself can check them. Asymmetric keys published as a @@ -503,29 +498,29 @@

    Known issues / Roadmap

-

Bug Tracker

+

Bug Tracker

Bugs are tracked on GitHub Issues. In case of trouble, please check there if your issue has already been reported. If you spotted it first, help us to smash it by providing a detailed and welcomed -feedback.

+feedback.

Do not contact contributors directly about support or help with technical issues.

-

Credits

+

Credits

-

Authors

+

Authors

  • Lorenzo Battistini
-

Contributors

+

Contributors

  • Lorenzo Battistini
-

Maintainers

+

Maintainers

This module is maintained by the OCA.

Odoo Community Association @@ -535,11 +530,10 @@

Maintainers

promote its widespread use.

Current maintainer:

eLBati

-

This module is part of the OCA/server-auth project on GitHub.

+

This module is part of the OCA/server-auth project on GitHub.

You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute.

-
diff --git a/auth_oauth_server/tests/common.py b/auth_oauth_server/tests/common.py index 95b3fe311c..7fbc33f481 100644 --- a/auth_oauth_server/tests/common.py +++ b/auth_oauth_server/tests/common.py @@ -22,7 +22,39 @@ def pkce_pair(): return verifier, pkce_s256(verifier) -class OAuthServerMixin: +def _remove_attrs(cls, names): + for name in names & set(vars(cls)): + delattr(cls, name) + + +class AuthMethodsMixin: + """For the test cases that create protected resources. + + auth_jwt adds the ``auth="jwt_"`` methods of each validator, those of + the resources included, to the ir.http class, where they outlive the + records rolled back after a test; Odoo fails the tests that leave such + attributes behind. The methods a test adds are removed after it; call + ``accept_auth_methods()`` at the end of setUpClass to keep those of the + class fixtures until the end of the class. + """ + + @classmethod + def accept_auth_methods(cls): + ir_http = type(cls.env["ir.http"]) + added = set(vars(ir_http)) - cls.attrs_before["ir.http"] + cls.attrs_before["ir.http"] |= added + cls.addClassCleanup(_remove_attrs, ir_http, added) + + def setUp(self): + super().setUp() + ir_http = type(self.env["ir.http"]) + attrs_before = set(vars(ir_http)) + self.addCleanup( + lambda: _remove_attrs(ir_http, set(vars(ir_http)) - attrs_before) + ) + + +class OAuthServerMixin(AuthMethodsMixin): """A resource, a public and a confidential client, and a user.""" @classmethod @@ -35,7 +67,7 @@ def setup_oauth_server(cls): cls.client = env["oauth.server.client"].create( { "name": "Test App", - "redirect_uris": "%s\n%s" % (REDIRECT_URI, LOOPBACK_REDIRECT_URI), + "redirect_uris": f"{REDIRECT_URI}\n{LOOPBACK_REDIRECT_URI}", } ) cls.confidential_client = env["oauth.server.client"].create( @@ -45,6 +77,7 @@ def setup_oauth_server(cls): cls.client_secret = action["context"]["default_secret"] cls.user = new_test_user(env, login="oauth_user") cls.other_user = new_test_user(env, login="oauth_other") + cls.accept_auth_methods() def approve(self, client=None, user=None, scopes="read write"): """What the consent page does: returns (authorization, code, verifier).""" diff --git a/auth_oauth_server/tests/test_controllers.py b/auth_oauth_server/tests/test_controllers.py index e017163bb0..24c19baec2 100644 --- a/auth_oauth_server/tests/test_controllers.py +++ b/auth_oauth_server/tests/test_controllers.py @@ -283,7 +283,7 @@ def test_code_reuse_revokes_over_http(self): def test_confidential_client_basic_auth(self): client = self.confidential_client _authorization, code, verifier = self.approve(client=client) - credentials = "%s:%s" % (client.identifier, self.client_secret) + credentials = f"{client.identifier}:{self.client_secret}" response = self.token_request( { "grant_type": "authorization_code", diff --git a/auth_oauth_server/tests/test_flow.py b/auth_oauth_server/tests/test_flow.py index 60f070b3ff..911fb03df6 100644 --- a/auth_oauth_server/tests/test_flow.py +++ b/auth_oauth_server/tests/test_flow.py @@ -38,7 +38,7 @@ def assertOAuthErrorKeepingChanges(self, error, function, *args, **kwargs): except OAuthError as raised: self.assertEqual(raised.error, error, raised.description) else: - self.fail("%s not raised" % error) + self.fail(f"{error} not raised") # ------------------------------------------------------------------ # Authorization request @@ -328,8 +328,8 @@ def test_access_token_checks(self): ] for index, change in enumerate(changes): with self.subTest(change=index): - user = new_test_user(self.env, login="oauth_change_%s" % index) - client = self.client.copy({"name": "Copy %s" % index}) + user = new_test_user(self.env, login=f"oauth_change_{index}") + client = self.client.copy({"name": f"Copy {index}"}) authorization, tokens = self.tokens(client=client, user=user) self.assertEqual(self.check_token(tokens["access_token"]), user.id) change(authorization.sudo()) diff --git a/auth_oauth_server/tests/test_resource.py b/auth_oauth_server/tests/test_resource.py index f78621a49a..7da7229540 100644 --- a/auth_oauth_server/tests/test_resource.py +++ b/auth_oauth_server/tests/test_resource.py @@ -134,14 +134,14 @@ def test_www_authenticate(self): metadata_url = common.ISSUER + "/.well-known/oauth-protected-resource/test_api" self.assertEqual( self.resource._www_authenticate(), - 'Bearer resource_metadata="%s", scope="read write"' % metadata_url, + f'Bearer resource_metadata="{metadata_url}", scope="read write"', ) self.assertEqual( self.resource._www_authenticate( error="invalid_token", error_description='a "quoted" text', scope="" ), - 'Bearer resource_metadata="%s", error="invalid_token", ' - 'error_description="a \\"quoted\\" text"' % metadata_url, + f'Bearer resource_metadata="{metadata_url}", error="invalid_token", ' + 'error_description="a \\"quoted\\" text"', ) def test_authenticate_bearer(self): diff --git a/auth_oauth_server/utils.py b/auth_oauth_server/utils.py index 5d6825c884..f8c42b86cf 100644 --- a/auth_oauth_server/utils.py +++ b/auth_oauth_server/utils.py @@ -66,7 +66,7 @@ def _split(uri): return None try: parts = urlsplit(uri) - parts.port # pylint: disable=pointless-statement + _port = parts.port # raises ValueError for an invalid port except ValueError: return None return parts @@ -135,7 +135,7 @@ def normalize_uri(uri): def _signature(secret, scope, body): - message = ("%s:%s" % (scope, body)).encode() + message = (f"{scope}:{body}").encode() return hmac.new(secret.encode(), message, hashlib.sha256).hexdigest() @@ -144,7 +144,7 @@ def sign(secret, scope, values, max_age): payload = dict(values, exp=int(time.time()) + max_age) body = json.dumps(payload, sort_keys=True).encode() body = base64.urlsafe_b64encode(body).decode().rstrip("=") - return "%s.%s" % (body, _signature(secret, scope, body)) + return f"{body}.{_signature(secret, scope, body)}" def verify(secret, scope, signed): @@ -234,16 +234,16 @@ def fetch_metadata_document(url): ) try: if response.status_code != 200: - raise ValueError("HTTP status %s" % response.status_code) + raise ValueError(f"HTTP status {response.status_code}") content_type = response.headers.get("Content-Type", "") content_type = content_type.split(";")[0].strip().lower() if content_type != "application/json" and not content_type.endswith("+json"): - raise ValueError("unexpected content type %r" % content_type) + raise ValueError(f"unexpected content type {content_type!r}") size, chunks = 0, [] for chunk in response.iter_content(chunk_size=1024): size += len(chunk) if size > METADATA_DOCUMENT_MAX_BYTES: - raise ValueError("document larger than %s bytes" % size) + raise ValueError(f"document larger than {size} bytes") if time.monotonic() > deadline: raise ValueError("document not received in time") chunks.append(chunk) diff --git a/auth_oauth_server/views/auth_jwt_validator_views.xml b/auth_oauth_server/views/auth_jwt_validator_views.xml index dcc53b625d..b2da13aede 100644 --- a/auth_oauth_server/views/auth_jwt_validator_views.xml +++ b/auth_oauth_server/views/auth_jwt_validator_views.xml @@ -8,30 +8,29 @@ {'readonly': [('user_id_strategy', '=', 'oauth_server')]} + name="readonly" + >user_id_strategy == 'oauth_server' {'readonly': [('user_id_strategy', '=', 'oauth_server')]} + name="readonly" + >user_id_strategy == 'oauth_server' {'readonly': [('user_id_strategy', '=', 'oauth_server')]} + name="readonly" + >user_id_strategy == 'oauth_server' - { - 'invisible': [('signature_type', '!=', 'secret')], - 'required': [('signature_type', '=', 'secret')], - 'readonly': [('user_id_strategy', '=', 'oauth_server')]} + user_id_strategy == 'oauth_server' diff --git a/auth_oauth_server/views/oauth_server_authorization_views.xml b/auth_oauth_server/views/oauth_server_authorization_views.xml index d103b2cd6a..abd7f1815d 100644 --- a/auth_oauth_server/views/oauth_server_authorization_views.xml +++ b/auth_oauth_server/views/oauth_server_authorization_views.xml @@ -1,10 +1,10 @@ - oauth.server.authorization.tree + oauth.server.authorization.list oauth.server.authorization - + @@ -18,7 +18,7 @@ decoration-success="state == 'active'" decoration-muted="state in ('expired', 'revoked')" /> - + @@ -31,8 +31,8 @@ name="action_revoke" type="object" string="Revoke" - attrs="{'invisible': [('state', 'in', ('expired', 'revoked'))]}" confirm="The application loses its access at once. Continue?" + invisible="state in ('expired', 'revoked')" /> @@ -49,11 +49,7 @@ - - + @@ -96,7 +92,8 @@ OAuth Authorizations oauth.server.authorization - tree,form + oauth-server-authorizations + list,form {'search_default_not_revoked': 1} diff --git a/auth_oauth_server/views/oauth_server_client_views.xml b/auth_oauth_server/views/oauth_server_client_views.xml index 86a16bf903..72b734b481 100644 --- a/auth_oauth_server/views/oauth_server_client_views.xml +++ b/auth_oauth_server/views/oauth_server_client_views.xml @@ -1,16 +1,16 @@ - oauth.server.client.tree + oauth.server.client.list oauth.server.client - + - + @@ -23,16 +23,16 @@ name="action_generate_secret" type="object" string="Generate Secret" - attrs="{'invisible': ['|', ('id', '=', False), ('registration_type', '!=', 'manual')]}" confirm="The application must then use the new secret: the previous one stops working. Continue?" + invisible="(not id or registration_type != 'manual')" />

@@ -45,33 +45,32 @@ - - + - + @@ -115,7 +114,8 @@ OAuth Applications oauth.server.client - tree,form + oauth-server-clients + list,form oauth.server.client.secret.form diff --git a/auth_oauth_server/views/oauth_server_resource_views.xml b/auth_oauth_server/views/oauth_server_resource_views.xml index 764af6da47..210b188419 100644 --- a/auth_oauth_server/views/oauth_server_resource_views.xml +++ b/auth_oauth_server/views/oauth_server_resource_views.xml @@ -1,15 +1,15 @@ - oauth.server.resource.tree + oauth.server.resource.list oauth.server.resource - + - + @@ -29,8 +29,8 @@

@@ -43,7 +43,6 @@ - @@ -74,6 +73,7 @@ Protected Resources oauth.server.resource - tree,form + oauth-server-resources + list,form diff --git a/auth_oauth_server/views/res_config_settings_views.xml b/auth_oauth_server/views/res_config_settings_views.xml index 300d198d85..4476ee10b9 100644 --- a/auth_oauth_server/views/res_config_settings_views.xml +++ b/auth_oauth_server/views/res_config_settings_views.xml @@ -5,70 +5,44 @@ res.config.settings - -

OAuth Authorization Server

-
-
-
-
-
-
- -
-
-
-
-
-
- -
-
-
-
-
- + + + + + + diff --git a/auth_oauth_server/views/res_users_views.xml b/auth_oauth_server/views/res_users_views.xml index a0a66e83a9..d118e55227 100644 --- a/auth_oauth_server/views/res_users_views.xml +++ b/auth_oauth_server/views/res_users_views.xml @@ -9,7 +9,7 @@
Applications you allowed to act on your behalf. Revoke @@ -22,7 +22,7 @@ colspan="4" readonly="0" > - + @@ -34,7 +34,7 @@ icon="fa-ban" confirm="The application loses its access at once. Continue?" /> - +
From fcebcbf5d9091bbbdf1b72daed08cad7655a0522 Mon Sep 17 00:00:00 2001 From: "lorenzo.carta" Date: Tue, 17 Nov 2026 16:41:21 +0100 Subject: [PATCH 4/5] [IMP] auth_oauth_server: dynamic registration and metadata documents opt-in Both were enabled at installation, and client metadata documents were accepted from any domain: anyone could register an application under the name of a well-known one, with redirect URIs of their own, and have users approve it from a link. The consent page warns about it, in small print. They now stay off until an administrator enables them in the settings; the readme recommends listing the domains of the metadata documents to accept. The installation hook only pins the issuer. Tests: the hook leaves both off; the fixtures enable them for the tests that use them. --- auth_oauth_server/README.rst | 22 +++++++++++++------ auth_oauth_server/hooks.py | 9 ++++---- auth_oauth_server/readme/CONFIGURE.md | 11 ++++++++-- auth_oauth_server/readme/DESCRIPTION.md | 6 ++--- auth_oauth_server/readme/ROADMAP.md | 4 ++-- .../static/description/index.html | 21 ++++++++++++------ auth_oauth_server/tests/common.py | 6 ++++- auth_oauth_server/tests/test_registration.py | 13 +++++++++++ 8 files changed, 66 insertions(+), 26 deletions(-) diff --git a/auth_oauth_server/README.rst b/auth_oauth_server/README.rst index 5be767c6f4..685534aae4 100644 --- a/auth_oauth_server/README.rst +++ b/auth_oauth_server/README.rst @@ -41,9 +41,9 @@ requires, so MCP clients can connect to an MCP server hosted in Odoo: tokens, rotated on each use; - discovery: authorization server metadata (RFC 8414) and protected resource metadata (RFC 9728); -- applications may be registered by an administrator, register - themselves (RFC 7591), or be identified by the URL of the details - they publish (OAuth Client ID Metadata Documents); +- applications may be registered by an administrator or, once enabled, + register themselves (RFC 7591) or be identified by the URL of the + details they publish (OAuth Client ID Metadata Documents); - tokens bound to the API they were asked for (RFC 8707 resource indicators), ``iss`` in authorization responses (RFC 9207), token revocation (RFC 7009). @@ -83,9 +83,17 @@ In *Settings > General Settings > OAuth Authorization Server*: - **Accept Client Metadata Documents**: let applications identify themselves with the URL of the details they publish, without being registered first. Odoo then fetches that URL, from public addresses - only. Optionally, list the domains to accept. + only. List the domains to accept: when the list is empty, any domain + is. - **Allow Dynamic Client Registration**: let applications register - themselves. + themselves. Enable it only for applications that publish no metadata + document and that you do not want to register by hand. + +Both are off at installation. Whoever may register an application +chooses its name, and could pass it off as a well-known one to have +users approve it: the consent page shows the domain that published a +metadata document, and warns that the name of a self-registered +application is not verified. Then, in *Settings > Users & Companies > OAuth Server > Protected Resources*, declare each API that accepts the tokens: its path on this @@ -147,8 +155,8 @@ Known issues / Roadmap ``private_key_jwt`` client authentication. - Redirect URIs must use https, or http on localhost: private-use schemes of native applications are not supported. -- Dynamic client registration is not rate limited; use a reverse proxy, - or disable it. +- Dynamic client registration is not rate limited: if you enable it, + limit it with a reverse proxy. - A resource created while Odoo runs registers its ``auth="jwt_..."`` route method only in the worker that created it (an ``auth_jwt`` limitation): restart the workers before using it in routes. diff --git a/auth_oauth_server/hooks.py b/auth_oauth_server/hooks.py index 9305bb4727..909e7c6c18 100644 --- a/auth_oauth_server/hooks.py +++ b/auth_oauth_server/hooks.py @@ -3,16 +3,17 @@ def post_init_hook(env): - """Pin the issuer to the current base URL and enable client registration. + """Pin the issuer to the current base URL. The issuer is a parameter of its own because ``web.base.url`` is rewritten on every administrator login unless frozen, and every change of issuer invalidates the access tokens issued so far. + + Dynamic client registration and client metadata documents stay off until + an administrator enables them: otherwise anyone could register an + application under any name and have users approve it. """ params = env["ir.config_parameter"] if not params.get_param("auth_oauth_server.issuer"): base_url = params.get_param("web.base.url") or "" params.set_param("auth_oauth_server.issuer", base_url.rstrip("/")) - for key in ("auth_oauth_server.cimd_enabled", "auth_oauth_server.dcr_enabled"): - if not params.get_param(key): - params.set_param(key, "True") diff --git a/auth_oauth_server/readme/CONFIGURE.md b/auth_oauth_server/readme/CONFIGURE.md index 14a6e344c7..866937c359 100644 --- a/auth_oauth_server/readme/CONFIGURE.md +++ b/auth_oauth_server/readme/CONFIGURE.md @@ -7,9 +7,16 @@ In *Settings > General Settings > OAuth Authorization Server*: their refresh tokens. - **Accept Client Metadata Documents**: let applications identify themselves with the URL of the details they publish, without being registered first. - Odoo then fetches that URL, from public addresses only. Optionally, list the - domains to accept. + Odoo then fetches that URL, from public addresses only. List the domains to + accept: when the list is empty, any domain is. - **Allow Dynamic Client Registration**: let applications register themselves. + Enable it only for applications that publish no metadata document and that + you do not want to register by hand. + +Both are off at installation. Whoever may register an application chooses its +name, and could pass it off as a well-known one to have users approve it: the +consent page shows the domain that published a metadata document, and warns +that the name of a self-registered application is not verified. Then, in *Settings > Users & Companies > OAuth Server > Protected Resources*, declare each API that accepts the tokens: its path on this server, the scopes diff --git a/auth_oauth_server/readme/DESCRIPTION.md b/auth_oauth_server/readme/DESCRIPTION.md index f1ec8daa8f..0ebce737b3 100644 --- a/auth_oauth_server/readme/DESCRIPTION.md +++ b/auth_oauth_server/readme/DESCRIPTION.md @@ -11,9 +11,9 @@ requires, so MCP clients can connect to an MCP server hosted in Odoo: rotated on each use; - discovery: authorization server metadata (RFC 8414) and protected resource metadata (RFC 9728); -- applications may be registered by an administrator, register themselves - (RFC 7591), or be identified by the URL of the details they publish - (OAuth Client ID Metadata Documents); +- applications may be registered by an administrator or, once enabled, + register themselves (RFC 7591) or be identified by the URL of the details + they publish (OAuth Client ID Metadata Documents); - tokens bound to the API they were asked for (RFC 8707 resource indicators), `iss` in authorization responses (RFC 9207), token revocation (RFC 7009). diff --git a/auth_oauth_server/readme/ROADMAP.md b/auth_oauth_server/readme/ROADMAP.md index cccccfe804..46491d6e0b 100644 --- a/auth_oauth_server/readme/ROADMAP.md +++ b/auth_oauth_server/readme/ROADMAP.md @@ -5,8 +5,8 @@ `private_key_jwt` client authentication. - Redirect URIs must use https, or http on localhost: private-use schemes of native applications are not supported. -- Dynamic client registration is not rate limited; use a reverse proxy, or - disable it. +- Dynamic client registration is not rate limited: if you enable it, limit it + with a reverse proxy. - A resource created while Odoo runs registers its `auth="jwt_..."` route method only in the worker that created it (an `auth_jwt` limitation): restart the workers before using it in routes. diff --git a/auth_oauth_server/static/description/index.html b/auth_oauth_server/static/description/index.html index c89683e3a9..70c3267b8d 100644 --- a/auth_oauth_server/static/description/index.html +++ b/auth_oauth_server/static/description/index.html @@ -382,9 +382,9 @@

OAuth Authorization Server

tokens, rotated on each use;
  • discovery: authorization server metadata (RFC 8414) and protected resource metadata (RFC 9728);
  • -
  • applications may be registered by an administrator, register -themselves (RFC 7591), or be identified by the URL of the details -they publish (OAuth Client ID Metadata Documents);
  • +
  • applications may be registered by an administrator or, once enabled, +register themselves (RFC 7591) or be identified by the URL of the +details they publish (OAuth Client ID Metadata Documents);
  • tokens bound to the API they were asked for (RFC 8707 resource indicators), iss in authorization responses (RFC 9207), token revocation (RFC 7009).
  • @@ -432,10 +432,17 @@

    Configuration

  • Accept Client Metadata Documents: let applications identify themselves with the URL of the details they publish, without being registered first. Odoo then fetches that URL, from public addresses -only. Optionally, list the domains to accept.
  • +only. List the domains to accept: when the list is empty, any domain +is.
  • Allow Dynamic Client Registration: let applications register -themselves.
  • +themselves. Enable it only for applications that publish no metadata +document and that you do not want to register by hand. +

    Both are off at installation. Whoever may register an application +chooses its name, and could pass it off as a well-known one to have +users approve it: the consent page shows the domain that published a +metadata document, and warns that the name of a self-registered +application is not verified.

    Then, in Settings > Users & Companies > OAuth Server > Protected Resources, declare each API that accepts the tokens: its path on this server, the scopes applications may ask for, the groups whose users may @@ -488,8 +495,8 @@

    Known issues / Roadmap

    private_key_jwt client authentication.
  • Redirect URIs must use https, or http on localhost: private-use schemes of native applications are not supported.
  • -
  • Dynamic client registration is not rate limited; use a reverse proxy, -or disable it.
  • +
  • Dynamic client registration is not rate limited: if you enable it, +limit it with a reverse proxy.
  • A resource created while Odoo runs registers its auth="jwt_..." route method only in the worker that created it (an auth_jwt limitation): restart the workers before using it in routes.
  • diff --git a/auth_oauth_server/tests/common.py b/auth_oauth_server/tests/common.py index 7fbc33f481..5411c984f2 100644 --- a/auth_oauth_server/tests/common.py +++ b/auth_oauth_server/tests/common.py @@ -60,7 +60,11 @@ class OAuthServerMixin(AuthMethodsMixin): @classmethod def setup_oauth_server(cls): env = cls.env - env["ir.config_parameter"].sudo().set_param("auth_oauth_server.issuer", ISSUER) + params = env["ir.config_parameter"].sudo() + params.set_param("auth_oauth_server.issuer", ISSUER) + # off at installation; the tests turn them off again where needed + params.set_param("auth_oauth_server.dcr_enabled", True) + params.set_param("auth_oauth_server.cimd_enabled", True) cls.resource = env["oauth.server.resource"].create( {"name": "Test API", "path": "/test_api", "scopes": "read write"} ) diff --git a/auth_oauth_server/tests/test_registration.py b/auth_oauth_server/tests/test_registration.py index 0b0b6aa9d4..b3d7f4dada 100644 --- a/auth_oauth_server/tests/test_registration.py +++ b/auth_oauth_server/tests/test_registration.py @@ -11,6 +11,7 @@ from .. import utils from ..exceptions import OAuthError +from ..hooks import post_init_hook from . import common DOCUMENT_URL = "https://app.example.com/oauth/client.json" @@ -57,6 +58,18 @@ def assertOAuthError(self, error, function, *args, **kwargs): function(*args, **kwargs) self.assertEqual(raised.exception.error, error, raised.exception.description) + def test_registration_off_at_installation(self): + """Applications neither register themselves nor present metadata + documents until an administrator allows it.""" + params = self.env["ir.config_parameter"].sudo() + params.set_param("auth_oauth_server.dcr_enabled", False) + params.set_param("auth_oauth_server.cimd_enabled", False) + post_init_hook(self.env) + server = self.env["oauth.server"] + self.assertFalse(server._is_dynamic_registration_enabled()) + self.assertFalse(server._is_metadata_document_enabled()) + self.assertEqual(params.get_param("auth_oauth_server.issuer"), common.ISSUER) + # ------------------------------------------------------------------ # Dynamic client registration # ------------------------------------------------------------------ From 68541de32cda285db4c53e165243236019d41f09 Mon Sep 17 00:00:00 2001 From: "lorenzo.carta" Date: Thu, 26 Nov 2026 16:02:24 +0100 Subject: [PATCH 5/5] [FIX] auth_oauth_server: issues found reviewing the server Security: - Used refresh tokens were deleted a day after their use, so a stolen copy presented later went unnoticed: they are now kept until they expire, and presenting one again revokes the authorization. - Within the grace period, a used refresh token was accepted again as often as asked, each time starting a parallel chain of tokens: the refresh token issued in exchange is now derived from the one presented, so that all those requests get the same one. - A request asking only for scopes unknown to the resource got all of its scopes: it is now refused with invalid_scope. - Client metadata documents: the download connects to the address checked as public, not to a new resolution of the name (DNS rebinding); it is cut when its time is up, however slowly the host answers; and the request, including whether the user is allowed on the resource, is checked before any document is fetched and any client created. Correctness: - Scopes removed from a resource are left out of the tokens of the applications already authorized. - Disabling dynamic registration or metadata documents stops the clients registered that way. - Revoking a token of another client is refused (RFC 7009 2.1), and an access token expired, or of an authorization not valid for now, still revokes its authorization. - The token request must repeat the redirect_uri of the authorization request, if it had one (RFC 6749 4.1.3). - Commas are refused in resource paths (auth_jwt splits the audience on them), validator names are ASCII identifiers, and malformed host names or grant_types give OAuth errors instead of errors 500. The download uses http.client rather than requests, which cannot choose the address it connects to: the HTTPS_PROXY environment variable no longer applies to it. --- auth_oauth_server/README.rst | 7 +- auth_oauth_server/controllers/main.py | 6 +- auth_oauth_server/models/oauth_server.py | 44 ++++-- .../models/oauth_server_authorization.py | 114 ++++++++++----- .../models/oauth_server_client.py | 28 ++-- .../models/oauth_server_refresh_token.py | 29 ++-- .../models/oauth_server_resource.py | 26 ++-- auth_oauth_server/readme/ROADMAP.md | 6 +- .../static/description/index.html | 7 +- auth_oauth_server/tests/common.py | 2 + auth_oauth_server/tests/test_controllers.py | 13 ++ auth_oauth_server/tests/test_flow.py | 132 ++++++++++++++++-- auth_oauth_server/tests/test_registration.py | 80 ++++++++++- auth_oauth_server/tests/test_resource.py | 16 ++- auth_oauth_server/tests/test_utils.py | 96 ++++++++++--- auth_oauth_server/utils.py | 115 +++++++++++---- 16 files changed, 574 insertions(+), 147 deletions(-) diff --git a/auth_oauth_server/README.rst b/auth_oauth_server/README.rst index 685534aae4..f57d06143a 100644 --- a/auth_oauth_server/README.rst +++ b/auth_oauth_server/README.rst @@ -156,7 +156,12 @@ Known issues / Roadmap - Redirect URIs must use https, or http on localhost: private-use schemes of native applications are not supported. - Dynamic client registration is not rate limited: if you enable it, - limit it with a reverse proxy. + limit it with a reverse proxy. Neither are the client metadata + documents fetched for the authorization requests of users allowed on + a resource. +- Client metadata documents are fetched directly, never through the + proxy of the ``HTTPS_PROXY`` environment variable: the server + connects to the address it checked as public. - A resource created while Odoo runs registers its ``auth="jwt_..."`` route method only in the worker that created it (an ``auth_jwt`` limitation): restart the workers before using it in routes. diff --git a/auth_oauth_server/controllers/main.py b/auth_oauth_server/controllers/main.py index f89903f9d0..3aa3946cd0 100644 --- a/auth_oauth_server/controllers/main.py +++ b/auth_oauth_server/controllers/main.py @@ -108,7 +108,9 @@ def authorize(self, **params): ) server = self._env()["oauth.server"] try: - client, redirect_uri = server._get_authorization_client(params) + client, redirect_uri = server._get_authorization_client( + params, request.env.user + ) except OAuthError as error: return self._error_page(error) try: @@ -261,9 +263,9 @@ def revoke(self, **params): params.get("client_secret"), self._basic_credentials(), ) + env["oauth.server.authorization"]._revoke_token(client, params.get("token")) except OAuthError as error: return self._oauth_error_response(error) - env["oauth.server.authorization"]._revoke_token(client, params.get("token")) return request.make_response("", headers=NO_STORE) @http.route( diff --git a/auth_oauth_server/models/oauth_server.py b/auth_oauth_server/models/oauth_server.py index b3b91b1b23..c1001703ff 100644 --- a/auth_oauth_server/models/oauth_server.py +++ b/auth_oauth_server/models/oauth_server.py @@ -9,6 +9,7 @@ from ..exceptions import OAuthError from ..utils import ( PKCE_CHALLENGE_RE, + check_metadata_document_url, is_valid_redirect_uri, redirect_uri_matches, sign, @@ -99,8 +100,8 @@ def _metadata(self): # ------------------------------------------------------------------ @api.model - def _get_authorization_client(self, params): - """The client and redirect URI of an authorization request. + def _get_authorization_client(self, params, user): + """The client and redirect URI of an authorization request of ``user``. The errors raised here must be shown to the user, never redirected: the redirect URI is not trusted yet. @@ -108,6 +109,10 @@ def _get_authorization_client(self, params): identifier = params.get("client_id") if not identifier or not isinstance(identifier, str): raise OAuthError("invalid_request", "Missing client_id.") + if check_metadata_document_url(identifier): + # before fetching a metadata document, and creating a client, on + # behalf of the user: only for valid requests of allowed users + self._check_request(params, user) client = self.env["oauth.server.client"]._get_for_authorization(identifier) registered = client._get_redirect_uris() redirect_uri = params.get("redirect_uri") @@ -128,6 +133,25 @@ def _check_authorization_request(self, client, redirect_uri, params, user): Returns the values to sign into the consent page, from which the decision is taken once the user answers. """ + resource = self._check_request(params, user) + return { + "client": client.id, + "redirect_uri": redirect_uri, + # then the token request must repeat it + "redirect_uri_given": bool(params.get("redirect_uri")), + "resource": resource.id, + "scope": resource._filter_scopes(params.get("scope")), + "code_challenge": params["code_challenge"], + "state": params.get("state"), + "uid": user.id, + } + + @api.model + def _check_request(self, params, user): + """The checks of an authorization request that need no client. + + Returns the resource asked for. + """ if params.get("response_type") != "code": raise OAuthError( "unsupported_response_type", "Only the code response type is supported." @@ -151,15 +175,7 @@ def _check_authorization_request(self, client, redirect_uri, params, user): raise OAuthError( "access_denied", "This user may not give access to this resource." ) - return { - "client": client.id, - "redirect_uri": redirect_uri, - "resource": resource.id, - "scope": resource._filter_scopes(params.get("scope")), - "code_challenge": challenge, - "state": state, - "uid": user.id, - } + return resource @api.model def _get_consent_secret(self): @@ -178,7 +194,7 @@ def _approve(self, values, user): """Record the user's consent; returns the authorization code.""" client = self.env["oauth.server.client"].browse(values["client"]).exists() resource = self.env["oauth.server.resource"].browse(values["resource"]).exists() - if not client.active or not resource.active: + if not client or not client._is_enabled() or not resource.active: raise OAuthError("invalid_request", "The application is no longer allowed.") if not resource._is_user_allowed(user): raise OAuthError( @@ -191,7 +207,7 @@ def _approve(self, values, user): client, resource, values["scope"], - values["redirect_uri"], + values["redirect_uri_given"] and values["redirect_uri"], values["code_challenge"], ) return code @@ -219,7 +235,7 @@ def _authenticate_client(self, client_id, client_secret, basic=None): client = self.env["oauth.server.client"].search( [("identifier", "=", client_id)], limit=1 ) - if not client: + if not client or not client._is_enabled(): raise failure if client.client_type == "confidential" and not client._check_secret( client_secret diff --git a/auth_oauth_server/models/oauth_server_authorization.py b/auth_oauth_server/models/oauth_server_authorization.py index db270705fe..b620baa148 100644 --- a/auth_oauth_server/models/oauth_server_authorization.py +++ b/auth_oauth_server/models/oauth_server_authorization.py @@ -63,7 +63,12 @@ class OAuthServerAuthorization(models.Model): index=True, ) scopes = fields.Char(readonly=True) - redirect_uri = fields.Char(readonly=True) + redirect_uri = fields.Char( + readonly=True, + help="The redirect URI of the authorization request, which the token " + "request must repeat. Empty when the application relied on its only " + "registered redirect URI.", + ) code_hash = fields.Char(readonly=True, copy=False, index=True) code_challenge = fields.Char(readonly=True, copy=False) code_expires_at = fields.Datetime(readonly=True) @@ -190,8 +195,9 @@ def _exchange_code(self, client, params): or authorization.code_expires_at <= fields.Datetime.now() ): raise OAuthError("invalid_grant", "Authorization code expired.") + # required when the authorization request had one (RFC 6749 4.1.3) redirect_uri = params.get("redirect_uri") - if redirect_uri and redirect_uri != authorization.redirect_uri: + if authorization.redirect_uri and redirect_uri != authorization.redirect_uri: raise OAuthError("invalid_grant", "redirect_uri does not match.") if not check_pkce(params.get("code_verifier"), authorization.code_challenge): raise OAuthError("invalid_grant", "Invalid code_verifier.") @@ -218,9 +224,9 @@ def _claim_code(self): @api.model def _refresh(self, client, params): """The refresh_token grant, rotating the refresh token.""" - token = self.env["oauth.server.refresh.token"]._get_by_token( - params.get("refresh_token") - ) + refresh_tokens = self.env["oauth.server.refresh.token"] + value = params.get("refresh_token") + token = refresh_tokens._get_by_token(value) authorization = token.authorization_id if not token or authorization.client_id != client: raise OAuthError("invalid_grant", "Invalid refresh token.") @@ -235,14 +241,23 @@ def _refresh(self, client, params): authorization._check_resource_param(params.get("resource")) authorization._check_still_allowed() scopes = authorization._narrow_scopes(params.get("scope")) - if not token._claim() and token.used_at < now - timedelta( - seconds=REFRESH_REUSE_GRACE - ): - # someone else holds a copy of the token - authorization._revoke("refresh_reuse") - raise OAuthError("invalid_grant", "Refresh token already used.") + successor = refresh_tokens._successor(value) + if token._claim(): + refresh_tokens._create_for(authorization, successor) + else: + # within the grace period, the same successor as the first time, + # as long as it was not used in turn + successor_token = refresh_tokens._get_by_token(successor) + if ( + not successor_token + or successor_token.used_at + or token.used_at < now - timedelta(seconds=REFRESH_REUSE_GRACE) + ): + # someone else holds a copy of the token + authorization._revoke("refresh_reuse") + raise OAuthError("invalid_grant", "Refresh token already used.") authorization.last_refresh = now - return authorization._issue_tokens(scopes) + return authorization._issue_tokens(scopes, successor) def _check_resource_param(self, resource): self.ensure_one() @@ -262,7 +277,7 @@ def _is_valid(self): return ( not self.revoked and self.expires_at > fields.Datetime.now() - and self.client_id.active + and self.client_id._is_enabled() and self.resource_id.active and self.resource_id._is_user_allowed(self.user_id) ) @@ -278,15 +293,22 @@ def _narrow_scopes(self, requested): raise OAuthError("invalid_scope", "Scopes beyond the authorization.") return " ".join(scopes) - def _issue_tokens(self, scopes): + def _issue_tokens(self, scopes, refresh_token=None): + """The token response; a new refresh token unless one is given. + + Scopes the resource no longer has are left out of the tokens. + """ self.ensure_one() + allowed = self.resource_id._get_scopes() + scopes = " ".join(s for s in (scopes or "").split() if s in allowed) access_token, expires_in = self._make_access_token(scopes) return { "access_token": access_token, "token_type": "Bearer", "expires_in": expires_in, "scope": scopes, - "refresh_token": self.env["oauth.server.refresh.token"]._create_for(self), + "refresh_token": refresh_token + or self.env["oauth.server.refresh.token"]._create_for(self), } def _make_access_token(self, scopes): @@ -323,45 +345,56 @@ def _make_access_token(self, scopes): # ------------------------------------------------------------------ @api.model - def _get_for_access_token(self, validator, payload): - """The authorization behind a validated access token payload. - - Refuses tokens of revoked or expired authorizations, of disabled - applications or resources, and of users no longer allowed, so that - revoking takes effect at once rather than when the token expires. - """ - authorization = self.browse() + def _get_for_payload(self, validator, payload): + """The authorization a verified access token payload was issued for.""" try: authorization = self.browse(int(payload.get("authorization_id"))).exists() except (TypeError, ValueError): - authorization = self.browse() + return self.browse() if ( - not authorization - or authorization.resource_id.jwt_validator_id != validator + authorization.resource_id.jwt_validator_id != validator or payload.get("client_id") != authorization.client_id.identifier or payload.get("sub") != str(authorization.user_id.id) - or not authorization._is_valid() ): + return self.browse() + return authorization + + @api.model + def _get_for_access_token(self, validator, payload): + """The authorization behind a validated access token payload. + + Refuses tokens of revoked or expired authorizations, of disabled + applications or resources, and of users no longer allowed, so that + revoking takes effect at once rather than when the token expires. + """ + authorization = self._get_for_payload(validator, payload) + if not authorization or not authorization._is_valid(): raise UnauthorizedInvalidToken() return authorization @api.model def _revoke_token(self, client, token): """Token revocation (RFC 7009) of a refresh or access token of - ``client``. Unknown tokens are ignored, as the RFC requires.""" + ``client``. Unknown tokens are ignored, as the RFC requires, and + tokens of other clients refused.""" if not token or not isinstance(token, str): return refresh_token = self.env["oauth.server.refresh.token"]._get_by_token(token) - if refresh_token: - if refresh_token.authorization_id.client_id == client: - refresh_token.authorization_id._revoke("client") + authorization = ( + refresh_token.authorization_id or self._get_for_signed_access_token(token) + ) + if not authorization: return - authorization = self._get_for_unverified_access_token(token) - if authorization and authorization.client_id == client: + if authorization.client_id != client: + raise OAuthError("invalid_grant", "The token was issued to another client.") + if not authorization.revoked: authorization._revoke("client") @api.model - def _get_for_unverified_access_token(self, token): + def _get_for_signed_access_token(self, token): + """The authorization of an access token whose signature is valid, + even if it expired or its authorization is no longer valid: revoking + must work for those too.""" try: claims = jwt.decode(token, options={"verify_signature": False}) except jwt.PyJWTError: @@ -374,7 +407,14 @@ def _get_for_unverified_access_token(self, token): return self.browse() validator = resource.jwt_validator_id.sudo() try: - payload = validator._decode(token) - return self._get_for_access_token(validator, payload) - except UnauthorizedInvalidToken: + payload = jwt.decode( + token, + key=validator.secret_key, + algorithms=[validator.secret_algorithm], + audience=validator.audience, + issuer=validator.issuer, + options={"require": ["aud", "iss"], "verify_exp": False}, + ) + except jwt.PyJWTError: return self.browse() + return self._get_for_payload(validator, payload) diff --git a/auth_oauth_server/models/oauth_server_client.py b/auth_oauth_server/models/oauth_server_client.py index 9bb601c2a3..700b360a46 100644 --- a/auth_oauth_server/models/oauth_server_client.py +++ b/auth_oauth_server/models/oauth_server_client.py @@ -6,8 +6,6 @@ from datetime import timedelta from urllib.parse import urlsplit -import requests - from odoo import _, api, fields, models from odoo.exceptions import ValidationError from odoo.tools import consteq @@ -105,6 +103,19 @@ def _get_redirect_uris(self): if uri.strip() ] + def _is_enabled(self): + """Active, and registered in a way still enabled: disabling dynamic + registration or metadata documents stops the clients registered so.""" + self.ensure_one() + server = self.env["oauth.server"] + if self.registration_type == "dynamic": + enabled = server._is_dynamic_registration_enabled() + elif self.registration_type == "metadata_document": + enabled = server._is_metadata_document_enabled() + else: + enabled = True + return self.active and enabled + def _check_secret(self, secret): self.ensure_one() if not self.client_secret_hash or not isinstance(secret, str) or not secret: @@ -157,7 +168,7 @@ def _get_for_authorization(self, identifier): else utils.check_metadata_document_url(identifier) ) if not is_document: - if not client: + if not client or not client._is_enabled(): raise OAuthError("invalid_client", "Unknown client.") return client if not self.env["oauth.server"]._is_metadata_document_enabled(): @@ -184,16 +195,14 @@ def _get_metadata_document_client(self, url, client): "invalid_client", "Applications from this domain are not accepted." ) try: - addresses = utils.resolve_host(hostname) - except OSError: - addresses = set() - if not addresses or not all(utils.is_public_address(a) for a in addresses): + utils.resolve_public_address(hostname) + except ValueError as error: raise OAuthError( "invalid_client", "The client metadata host is not a public address." - ) + ) from error try: document, cache_control = utils.fetch_metadata_document(url) - except (requests.RequestException, ValueError) as error: + except ValueError as error: _logger.info("Cannot fetch client metadata document %s: %s", url, error) raise OAuthError( "invalid_client", "Cannot fetch the client metadata document." @@ -283,6 +292,7 @@ def _register_dynamic(self, metadata): grant_types = metadata.get("grant_types", ["authorization_code"]) if ( not isinstance(grant_types, list) + or not all(isinstance(grant, str) for grant in grant_types) or "authorization_code" not in grant_types or not set(grant_types) <= {"authorization_code", "refresh_token"} ): diff --git a/auth_oauth_server/models/oauth_server_refresh_token.py b/auth_oauth_server/models/oauth_server_refresh_token.py index 39696a8a52..c606666f1e 100644 --- a/auth_oauth_server/models/oauth_server_refresh_token.py +++ b/auth_oauth_server/models/oauth_server_refresh_token.py @@ -5,7 +5,7 @@ from odoo import api, fields, models -from ..utils import generate_token, hash_token +from ..utils import derive_token, generate_token, hash_token class OAuthServerRefreshToken(models.Model): @@ -30,9 +30,9 @@ class OAuthServerRefreshToken(models.Model): ] @api.model - def _create_for(self, authorization): + def _create_for(self, authorization, token=None): """Issue a refresh token for ``authorization``; returns its value.""" - token = generate_token() + token = token or generate_token() lifetime = timedelta(days=authorization.resource_id.refresh_token_lifetime) self.create( { @@ -51,6 +51,18 @@ def _get_by_token(self, token): return self.browse() return self.search([("token_hash", "=", hash_token(token))], limit=1) + @api.model + def _successor(self, token): + """The refresh token issued in exchange for ``token``. + + It is derived from ``token``, so that every request presenting + ``token`` gets the same one: concurrent requests of a client continue + a single chain of tokens, and so does a thief holding a copy, whose + next use then reveals the theft. + """ + secret = self.env["ir.config_parameter"].sudo().get_param("database.secret") + return derive_token(secret, "auth_oauth_server.refresh_token", token) + def _claim(self): """Mark the token used, atomically; False if it already was. @@ -71,11 +83,6 @@ def _claim(self): @api.autovacuum def _gc_refresh_tokens(self): - now = fields.Datetime.now() - self.search( - [ - "|", - ("expires_at", "<", now), - ("used_at", "<", now - timedelta(days=1)), - ] - ).unlink() + """Drop expired tokens only: a used one presented again, however + late, reveals a stolen copy and revokes the authorization.""" + self.search([("expires_at", "<", fields.Datetime.now())]).unlink() diff --git a/auth_oauth_server/models/oauth_server_resource.py b/auth_oauth_server/models/oauth_server_resource.py index cf6557ca86..ab0993dbe6 100644 --- a/auth_oauth_server/models/oauth_server_resource.py +++ b/auth_oauth_server/models/oauth_server_resource.py @@ -87,12 +87,13 @@ def _check_path(self): if ( not path.startswith("/") or (path != "/" and path.endswith("/")) - or re.search(r"[\s?#]", path) + # auth_jwt splits the audience, the URI of the resource, on commas + or re.search(r"[\s?#,]", path) ): raise ValidationError( _( "The path %(path)s must start with a slash, and contain " - "no trailing slash, query or fragment.", + "no trailing slash, comma, query or fragment.", path=path, ) ) @@ -110,7 +111,9 @@ def _compute_uri(self): @api.model def _create_jwt_validator(self, path): validators = self.env["auth.jwt.validator"].sudo() - base = "oauth_server_" + (re.sub(r"\W+", "_", path or "").strip("_") or "root") + # a Python identifier, as auth_jwt requires: ASCII only + name = re.sub(r"[^A-Za-z0-9_]+", "_", path or "").strip("_") + base = "oauth_server_" + (name or "root") name, counter = base, 1 while validators.search_count([("name", "=", name)]): counter += 1 @@ -175,14 +178,17 @@ def _get_scopes(self): return (self.scopes or "").split() def _filter_scopes(self, requested): - """The scopes to grant for a request: unknown ones are dropped (RFC - 6749 3.3), and no request at all means every scope.""" + """The scopes to grant for a request: no scope parameter means every + scope, and unknown ones are dropped (RFC 6749 3.3), but a request + for none of the resource's scopes is refused.""" allowed = self._get_scopes() - if isinstance(requested, str): - kept = [scope for scope in requested.split() if scope in allowed] - if kept: - return " ".join(dict.fromkeys(kept)) - return " ".join(allowed) + requested = requested.split() if isinstance(requested, str) else [] + if not requested or not allowed: + return " ".join(allowed) + kept = [scope for scope in requested if scope in allowed] + if not kept: + raise OAuthError("invalid_scope", "Unknown scopes.") + return " ".join(dict.fromkeys(kept)) @api.model def _get_by_uri(self, uri): diff --git a/auth_oauth_server/readme/ROADMAP.md b/auth_oauth_server/readme/ROADMAP.md index 46491d6e0b..030b2464b4 100644 --- a/auth_oauth_server/readme/ROADMAP.md +++ b/auth_oauth_server/readme/ROADMAP.md @@ -6,7 +6,11 @@ - Redirect URIs must use https, or http on localhost: private-use schemes of native applications are not supported. - Dynamic client registration is not rate limited: if you enable it, limit it - with a reverse proxy. + with a reverse proxy. Neither are the client metadata documents fetched for + the authorization requests of users allowed on a resource. +- Client metadata documents are fetched directly, never through the proxy of + the `HTTPS_PROXY` environment variable: the server connects to the address + it checked as public. - A resource created while Odoo runs registers its `auth="jwt_..."` route method only in the worker that created it (an `auth_jwt` limitation): restart the workers before using it in routes. diff --git a/auth_oauth_server/static/description/index.html b/auth_oauth_server/static/description/index.html index 70c3267b8d..65843ed745 100644 --- a/auth_oauth_server/static/description/index.html +++ b/auth_oauth_server/static/description/index.html @@ -496,7 +496,12 @@

    Known issues / Roadmap

  • Redirect URIs must use https, or http on localhost: private-use schemes of native applications are not supported.
  • Dynamic client registration is not rate limited: if you enable it, -limit it with a reverse proxy.
  • +limit it with a reverse proxy. Neither are the client metadata +documents fetched for the authorization requests of users allowed on +a resource. +
  • Client metadata documents are fetched directly, never through the +proxy of the HTTPS_PROXY environment variable: the server +connects to the address it checked as public.
  • A resource created while Odoo runs registers its auth="jwt_..." route method only in the worker that created it (an auth_jwt limitation): restart the workers before using it in routes.
  • diff --git a/auth_oauth_server/tests/common.py b/auth_oauth_server/tests/common.py index 5411c984f2..e252737ce8 100644 --- a/auth_oauth_server/tests/common.py +++ b/auth_oauth_server/tests/common.py @@ -10,6 +10,8 @@ from odoo.tests.common import new_test_user +from odoo.addons.auth_jwt.exceptions import UnauthorizedInvalidToken # noqa: F401 + from ..utils import pkce_s256 ISSUER = "https://erp.example.com" diff --git a/auth_oauth_server/tests/test_controllers.py b/auth_oauth_server/tests/test_controllers.py index 24c19baec2..8c40fcdba5 100644 --- a/auth_oauth_server/tests/test_controllers.py +++ b/auth_oauth_server/tests/test_controllers.py @@ -274,6 +274,7 @@ def test_code_reuse_revokes_over_http(self): "grant_type": "authorization_code", "code": code, "code_verifier": verifier, + "redirect_uri": common.REDIRECT_URI, "client_id": self.client.identifier, } self.assertEqual(self.token_request(data).status_code, 200) @@ -289,6 +290,7 @@ def test_confidential_client_basic_auth(self): "grant_type": "authorization_code", "code": code, "code_verifier": verifier, + "redirect_uri": common.REDIRECT_URI, }, headers={ "Authorization": "Basic " @@ -299,6 +301,17 @@ def test_confidential_client_basic_auth(self): def test_revoke(self): authorization, tokens = self.tokens() + response = self.post( + "/oauth/revoke", + { + "token": tokens["refresh_token"], + "client_id": self.confidential_client.identifier, + "client_secret": self.client_secret, + }, + ) + self.assertEqual(response.status_code, 400) + self.assertEqual(response.json()["error"], "invalid_grant") + self.assertFalse(authorization.revoked) response = self.post( "/oauth/revoke", {"token": tokens["refresh_token"], "client_id": self.client.identifier}, diff --git a/auth_oauth_server/tests/test_flow.py b/auth_oauth_server/tests/test_flow.py index 911fb03df6..1a75503ed8 100644 --- a/auth_oauth_server/tests/test_flow.py +++ b/auth_oauth_server/tests/test_flow.py @@ -63,7 +63,7 @@ def request_params(self, **params): def test_authorization_request(self): server = self.env["oauth.server"] params = self.request_params() - client, redirect_uri = server._get_authorization_client(params) + client, redirect_uri = server._get_authorization_client(params, self.user) self.assertEqual(client, self.client) values = server._check_authorization_request( client, redirect_uri, params, self.user @@ -93,25 +93,28 @@ def test_authorization_request_client_errors(self): self.request_params(redirect_uri=None), ): with self.assertRaises(OAuthError): - server._get_authorization_client(params) + server._get_authorization_client(params, self.user) self.client.active = False self.assertOAuthError( "unauthorized_client", server._get_authorization_client, self.request_params(), + self.user, ) def test_authorization_request_redirect_uri(self): server = self.env["oauth.server"] _client, redirect_uri = server._get_authorization_client( - self.request_params(redirect_uri="http://127.0.0.1:43123/callback") + self.request_params(redirect_uri="http://127.0.0.1:43123/callback"), + self.user, ) self.assertEqual(redirect_uri, "http://127.0.0.1:43123/callback") # the only registered redirect URI is the default _client, redirect_uri = server._get_authorization_client( self.request_params( client_id=self.confidential_client.identifier, redirect_uri=None - ) + ), + self.user, ) self.assertEqual(redirect_uri, common.REDIRECT_URI) @@ -127,6 +130,7 @@ def test_authorization_request_errors(self): ("invalid_request", {"code_challenge": "short"}), ("invalid_request", {"state": "x" * 3000}), ("invalid_target", {"resource": "https://other.example.com/api"}), + ("invalid_scope", {"scope": "admin"}), ] for error, params in cases: with self.subTest(params=params): @@ -205,6 +209,33 @@ def test_code_errors(self): # none of the failures consumed the code self.assertTrue(self.exchange(code, verifier)["access_token"]) + def test_code_redirect_uri(self): + """The token request must repeat the redirect_uri of the authorization + request, if it had one (RFC 6749 4.1.3).""" + server = self.env["oauth.server"] + for given in (True, False): + with self.subTest(given=given): + verifier, challenge = common.pkce_pair() + params = self.request_params(code_challenge=challenge) + if not given: + params.update( + client_id=self.confidential_client.identifier, + redirect_uri=None, + ) + client, redirect_uri = server._get_authorization_client( + params, self.user + ) + values = server._check_authorization_request( + client, redirect_uri, params, self.user + ) + code = server._approve(values, self.user) + exchange = self.env["oauth.server.authorization"]._exchange_code + params = {"code": code, "code_verifier": verifier} + if given: + self.assertOAuthError("invalid_grant", exchange, client, params) + params["redirect_uri"] = common.REDIRECT_URI + self.assertTrue(exchange(client, params)["access_token"]) + def test_code_expired(self): authorization, code, verifier = self.approve() authorization.code_expires_at = fields.Datetime.now() - timedelta(seconds=1) @@ -237,9 +268,18 @@ def test_refresh_rotation(self): self.assertNotEqual(new_tokens["refresh_token"], tokens["refresh_token"]) self.assertEqual(self.check_token(new_tokens["access_token"]), self.user.id) self.assertTrue(authorization.last_refresh) - # concurrent requests of one client may present the same token twice - self.assertTrue(self.refresh(tokens["refresh_token"])["access_token"]) + # concurrent requests of one client may present the same token twice: + # both get the same refresh token, so that a single chain goes on + again = self.refresh(tokens["refresh_token"]) + self.assertEqual(again["refresh_token"], new_tokens["refresh_token"]) + self.assertEqual(self.check_token(again["access_token"]), self.user.id) self.assertFalse(authorization.revoked) + self.assertTrue(self.refresh(new_tokens["refresh_token"])["access_token"]) + # once the chain went on, the first token is a stolen copy + self.assertOAuthErrorKeepingChanges( + "invalid_grant", self.refresh, tokens["refresh_token"] + ) + self.assertEqual(authorization.revoked_reason, "refresh_reuse") def test_refresh_reuse_revokes(self): authorization, tokens = self.tokens() @@ -258,6 +298,29 @@ def test_refresh_reuse_revokes(self): with self.assertRaises(UnauthorizedInvalidToken): self.check_token(new_tokens["access_token"]) + def test_late_refresh_reuse_revokes(self): + authorization, tokens = self.tokens() + self.refresh(tokens["refresh_token"]) + refresh_tokens = self.env["oauth.server.refresh.token"] + old_token = refresh_tokens._get_by_token(tokens["refresh_token"]) + old_token.used_at = fields.Datetime.now() - timedelta(days=2) + refresh_tokens._gc_refresh_tokens() + # used tokens are kept until they expire + self.assertTrue(old_token.exists()) + self.assertOAuthErrorKeepingChanges( + "invalid_grant", self.refresh, tokens["refresh_token"] + ) + self.assertEqual(authorization.revoked_reason, "refresh_reuse") + old_token = refresh_tokens.create( + { + "token_hash": "expired", + "authorization_id": authorization.id, + "expires_at": fields.Datetime.now() - timedelta(seconds=1), + } + ) + refresh_tokens._gc_refresh_tokens() + self.assertFalse(old_token.exists()) + def test_refresh_errors(self): _authorization, tokens = self.tokens() refresh_token = tokens["refresh_token"] @@ -284,6 +347,25 @@ def test_refresh_scope_narrowing(self): payload = self.resource.jwt_validator_id._decode(tokens["access_token"]) self.assertEqual(payload["scope"], "read") + def test_scopes_removed_from_the_resource(self): + authorization, code, verifier = self.approve() + self.resource.scopes = "read" + tokens = self.exchange(code, verifier) + self.assertEqual(tokens["scope"], "read") + self.resource.scopes = "admin" + tokens = self.refresh(tokens["refresh_token"]) + self.assertEqual(tokens["scope"], "") + payload = self.resource.jwt_validator_id._decode(tokens["access_token"]) + self.assertEqual(payload["scope"], "") + # the consent is kept: the scope comes back with the resource + self.resource.scopes = "read write" + self.assertEqual(self.refresh(tokens["refresh_token"])["scope"], "read write") + self.assertEqual(authorization.scopes, "read write") + # a resource without scopes gives tokens without scopes + self.resource.scopes = False + authorization, code, verifier = self.approve(scopes=False) + self.assertEqual(self.exchange(code, verifier)["scope"], "") + def test_refresh_expired(self): _authorization, tokens = self.tokens() token = self.env["oauth.server.refresh.token"]._get_by_token( @@ -389,8 +471,14 @@ def test_users_see_only_their_authorizations(self): def test_revoke_token(self): authorizations = self.env["oauth.server.authorization"] authorization, tokens = self.tokens() - # tokens of another client are ignored - authorizations._revoke_token(self.confidential_client, tokens["refresh_token"]) + # tokens of another client are refused (RFC 7009 2.1) + for token in (tokens["refresh_token"], tokens["access_token"]): + self.assertOAuthError( + "invalid_grant", + authorizations._revoke_token, + self.confidential_client, + token, + ) self.assertFalse(authorization.revoked) authorizations._revoke_token(self.client, tokens["refresh_token"]) self.assertEqual(authorization.revoked_reason, "client") @@ -401,6 +489,34 @@ def test_revoke_token(self): authorizations._revoke_token(self.client, "unknown") authorizations._revoke_token(self.client, None) + def test_revoke_token_no_longer_valid(self): + """Access tokens expired, or of authorizations not valid for now, + revoke their authorization too.""" + authorizations = self.env["oauth.server.authorization"] + authorization, tokens = self.tokens() + payload = self.resource.jwt_validator_id._decode(tokens["access_token"]) + validator = self.resource.jwt_validator_id + expired = jwt.encode( + dict(payload, exp=payload["iat"] - 1), + validator.secret_key, + algorithm=validator.secret_algorithm, + ) + authorizations._revoke_token(self.client, expired) + self.assertTrue(authorization.revoked) + authorization, tokens = self.tokens() + self.resource.group_ids = self.env["res.groups"].create({"name": "API"}) + authorizations._revoke_token(self.client, tokens["access_token"]) + self.assertTrue(authorization.revoked) + # a forged signature is still ignored + self.resource.group_ids = False + authorization, tokens = self.tokens() + payload = self.resource.jwt_validator_id._decode(tokens["access_token"]) + forged = jwt.encode( + payload, "a wrong secret, as long as a real one", algorithm="HS256" + ) + authorizations._revoke_token(self.client, forged) + self.assertFalse(authorization.revoked) + # ------------------------------------------------------------------ # Client authentication # ------------------------------------------------------------------ diff --git a/auth_oauth_server/tests/test_registration.py b/auth_oauth_server/tests/test_registration.py index b3d7f4dada..bbc5ef4ff8 100644 --- a/auth_oauth_server/tests/test_registration.py +++ b/auth_oauth_server/tests/test_registration.py @@ -4,8 +4,6 @@ from datetime import timedelta from unittest import mock -import requests - from odoo import fields from odoo.tests.common import TransactionCase, tagged @@ -133,6 +131,10 @@ def test_register_errors(self): "invalid_client_metadata", {"redirect_uris": uris, "grant_types": ["client_credentials"]}, ), + ( + "invalid_client_metadata", + {"redirect_uris": uris, "grant_types": ["authorization_code", {}]}, + ), ( "invalid_client_metadata", {"redirect_uris": uris, "response_types": ["token"]}, @@ -230,7 +232,6 @@ def test_metadata_document_errors(self): {"document": ["not", "a", "dict"]}, {"addresses": {"10.0.0.5"}}, {"addresses": {PUBLIC_ADDRESS, "127.0.0.1"}}, - {"error": requests.ConnectionError("down")}, {"error": ValueError("too large")}, ] for kwargs in cases: @@ -244,6 +245,79 @@ def test_metadata_document_errors(self): ) self.assertFalse(self.clients.search([("identifier", "=", DOCUMENT_URL)])) + def test_metadata_document_only_for_valid_requests(self): + """No document is fetched for a request that would be refused.""" + _verifier, challenge = common.pkce_pair() + params = { + "client_id": DOCUMENT_URL, + "response_type": "code", + "code_challenge": challenge, + "code_challenge_method": "S256", + "resource": self.resource.uri, + } + portal = common.new_test_user( + self.env, login="oauth_portal", groups="base.group_portal" + ) + server = self.env["oauth.server"] + fetch, resolve = self.patch_network() + with fetch as fetched, resolve: + for error, wrong_params, user in ( + ("unsupported_response_type", {"response_type": "token"}, self.user), + ("invalid_request", {"code_challenge": None}, self.user), + ("invalid_target", {"resource": "https://x.com/api"}, self.user), + ("access_denied", {}, portal), + ): + with self.subTest(error=error): + self.assertOAuthError( + error, + server._get_authorization_client, + dict(params, **wrong_params), + user, + ) + fetched.assert_not_called() + client, _redirect_uri = server._get_authorization_client(params, self.user) + self.assertEqual(client.identifier, DOCUMENT_URL) + + def test_registration_disabled_stops_clients(self): + """Disabling a way of registering stops the clients registered so.""" + params = self.env["ir.config_parameter"].sudo() + response = self.clients._register_dynamic( + { + "redirect_uris": [common.REDIRECT_URI], + "token_endpoint_auth_method": "none", + } + ) + dynamic = self.clients.search([("identifier", "=", response["client_id"])]) + document, _fetched = self.get_client() + server = self.env["oauth.server"] + for client, key in ( + (dynamic, "auth_oauth_server.dcr_enabled"), + (document, "auth_oauth_server.cimd_enabled"), + ): + with self.subTest(key=key): + authorization, tokens = self.tokens(client=client) + params.set_param(key, False) + self.assertOAuthError( + "invalid_client", + server._authenticate_client, + client.identifier, + None, + ) + self.assertOAuthError( + "invalid_grant", self.refresh, tokens["refresh_token"], client + ) + with self.assertRaises(common.UnauthorizedInvalidToken): + self.check_token(tokens["access_token"]) + self.assertOAuthError( + "invalid_client", + self.clients._get_for_authorization, + client.identifier, + ) + # enabled again, they work again + params.set_param(key, True) + self.assertTrue(self.refresh(tokens["refresh_token"], client)) + self.assertFalse(authorization.revoked) + def test_metadata_document_not_a_url(self): fetch, resolve = self.patch_network() with fetch as fetched, resolve: diff --git a/auth_oauth_server/tests/test_resource.py b/auth_oauth_server/tests/test_resource.py index 7da7229540..48e32ec476 100644 --- a/auth_oauth_server/tests/test_resource.py +++ b/auth_oauth_server/tests/test_resource.py @@ -31,6 +31,11 @@ def test_resource_creates_its_validator(self): {"name": "Other", "path": "/test-api"} ) self.assertEqual(other.jwt_validator_id.name, "oauth_server_test_api_2") + # characters that are not ASCII letters or digits, even \w ones + other = self.env["oauth.server.resource"].create( + {"name": "Unicode", "path": "/api²/città"} + ) + self.assertEqual(other.jwt_validator_id.name, "oauth_server_api_citt") def test_root_resource(self): resource = self.env["oauth.server.resource"].create( @@ -44,7 +49,7 @@ def test_root_resource(self): ) def test_invalid_path(self): - for path in ("api", "/api/", "/api?x=1", "/a b"): + for path in ("api", "/api/", "/api?x=1", "/a b", "/api,v2"): with self.assertRaises(ValidationError, msg=path): self.env["oauth.server.resource"].create({"name": "X", "path": path}) @@ -82,8 +87,15 @@ def test_scopes(self): self.assertEqual(self.resource._filter_scopes("write read write"), "write read") # unknown scopes are dropped rather than refused (RFC 6749 3.3) self.assertEqual(self.resource._filter_scopes("admin write"), "write") - self.assertEqual(self.resource._filter_scopes("admin"), "read write") + # but not all of them + with self.assertRaises(OAuthError) as raised: + self.resource._filter_scopes("admin") + self.assertEqual(raised.exception.error, "invalid_scope") self.assertEqual(self.resource._filter_scopes(None), "read write") + self.assertEqual(self.resource._filter_scopes(" "), "read write") + # a resource without scopes ignores the requested ones + self.resource.scopes = False + self.assertEqual(self.resource._filter_scopes("admin"), "") def test_resource_from_request(self): resources = self.env["oauth.server.resource"] diff --git a/auth_oauth_server/tests/test_utils.py b/auth_oauth_server/tests/test_utils.py index d1e0c09b04..0cfac95e59 100644 --- a/auth_oauth_server/tests/test_utils.py +++ b/auth_oauth_server/tests/test_utils.py @@ -1,6 +1,9 @@ # Copyright 2026 Lorenzo Battistini # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). +import socket +import threading +import time from unittest import mock from odoo.tests.common import TransactionCase @@ -9,18 +12,18 @@ class FakeResponse: + """What utils.read_metadata_response uses of an http.client response.""" + def __init__(self, status=200, content_type="application/json", body=b"{}"): - self.status_code = status + self.status = status self.headers = {"Content-Type": content_type, "Cache-Control": "max-age=60"} self.body = body - self.closed = False - def iter_content(self, chunk_size=1): - for start in range(0, len(self.body), chunk_size): - yield self.body[start : start + chunk_size] + def getheader(self, name): + return self.headers.get(name) - def close(self): - self.closed = True + def read(self, amt): # pylint: disable=method-required-super + return self.body[:amt] class TestUtils(TransactionCase): @@ -137,18 +140,29 @@ def test_max_age(self): self.assertEqual(utils.max_age_from_cache_control("no-store"), 300) self.assertEqual(utils.max_age_from_cache_control(""), 3600) - def _fetch(self, response): - with mock.patch.object(utils.requests, "get", return_value=response) as get: - try: - return utils.fetch_metadata_document("https://app.example.com/c.json") - finally: - self.assertTrue(response.closed) - kwargs = get.call_args[1] - self.assertFalse(kwargs["allow_redirects"]) - self.assertTrue(kwargs["timeout"]) - - def test_fetch_metadata_document(self): - document, cache_control = self._fetch(FakeResponse(body=b'{"a": 1}')) + def test_resolve_public_address(self): + resolve = utils.resolve_public_address + with mock.patch.object(utils, "resolve_host", return_value={"93.184.216.34"}): + self.assertEqual(resolve("app.example.com"), "93.184.216.34") + for kwargs in ( + {"return_value": {"10.0.0.5"}}, + {"return_value": {"93.184.216.34", "127.0.0.1"}}, + {"return_value": set()}, + {"side_effect": socket.gaierror("unknown")}, + # an empty label, or one longer than 63 characters + {"side_effect": UnicodeError("label empty or too long")}, + ): + with ( + self.subTest(kwargs=kwargs), + mock.patch.object(utils, "resolve_host", **kwargs), + ): + with self.assertRaises(ValueError): + resolve("app.example.com") + + def test_read_metadata_response(self): + document, cache_control = utils.read_metadata_response( + FakeResponse(body=b'{"a": 1}') + ) self.assertEqual(document, {"a": 1}) self.assertEqual(cache_control, "max-age=60") for response in ( @@ -156,6 +170,48 @@ def test_fetch_metadata_document(self): FakeResponse(content_type="text/html"), FakeResponse(body=b"{" + b" " * 6000 + b"}"), FakeResponse(body=b"not json"), + ): + with ( + self.subTest(response=response.__dict__), + self.assertRaises(ValueError), + ): + utils.read_metadata_response(response) + + def test_fetch_from_private_address(self): + with ( + mock.patch.object(utils, "resolve_host", return_value={"10.0.0.5"}), + mock.patch.object(utils.socket, "create_connection") as connect, ): with self.assertRaises(ValueError): - self._fetch(response) + utils.fetch_metadata_document("https://app.example.com/c.json") + connect.assert_not_called() + + def test_fetch_deadline(self): + """A host answering a byte at a time is cut off at the timeout.""" + server = socket.create_server(("127.0.0.1", 0)) + self.addCleanup(server.close) + + def drip(): + connection, _address = server.accept() + with connection: + # a TLS record announcing 16 KB, then a byte every 0.1 s + connection.sendall(b"\x16\x03\x03\x40\x00") + for _i in range(100): + try: + connection.sendall(b"\x00") + except OSError: + return + time.sleep(0.1) + + threading.Thread(target=drip, daemon=True).start() + with ( + mock.patch.object(utils, "resolve_host", return_value={"127.0.0.1"}), + mock.patch.object(utils, "is_public_address", return_value=True), + mock.patch.object(utils, "HTTPS_PORT", server.getsockname()[1]), + mock.patch.object(utils, "METADATA_DOCUMENT_TIMEOUT", 0.5), + ): + start = time.monotonic() + with self.assertRaises(ValueError) as raised: + utils.fetch_metadata_document("https://app.example.com/c.json") + self.assertLess(time.monotonic() - start, 2) + self.assertIn("in time", str(raised.exception)) diff --git a/auth_oauth_server/utils.py b/auth_oauth_server/utils.py index f8c42b86cf..d1bfa4276b 100644 --- a/auth_oauth_server/utils.py +++ b/auth_oauth_server/utils.py @@ -8,18 +8,20 @@ """ import base64 +import contextlib import hashlib import hmac +import http.client import ipaddress import json import re import secrets import socket +import ssl +import threading import time from urllib.parse import parse_qsl, unquote, urlencode, urlsplit, urlunsplit -import requests - from odoo.tools import consteq TOKEN_BYTES = 32 @@ -30,6 +32,7 @@ LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"} METADATA_DOCUMENT_MAX_BYTES = 5 * 1024 METADATA_DOCUMENT_TIMEOUT = 5 +HTTPS_PORT = 443 NAT64_NETWORK = ipaddress.ip_network("64:ff9b::/96") @@ -42,6 +45,11 @@ def hash_token(token): return hashlib.sha256(token.encode()).hexdigest() +def derive_token(secret, scope, token): + """A token that only the holder of ``secret`` can derive from ``token``.""" + return _signature(secret, scope, token) + + def pkce_s256(verifier): digest = hashlib.sha256(verifier.encode("ascii")).digest() return base64.urlsafe_b64encode(digest).decode("ascii").rstrip("=") @@ -213,43 +221,94 @@ def is_public_address(address): def resolve_host(hostname): - infos = socket.getaddrinfo(hostname, 443, type=socket.SOCK_STREAM) + infos = socket.getaddrinfo(hostname, HTTPS_PORT, type=socket.SOCK_STREAM) return {info[4][0] for info in infos} +def resolve_public_address(hostname): + """An address of ``hostname``, if all of them are public. + + Raises ValueError otherwise, or if the name does not resolve. + """ + try: + addresses = resolve_host(hostname) + except (OSError, UnicodeError) as error: + raise ValueError(f"cannot resolve {hostname}: {error}") from error + if not addresses or not all(is_public_address(a) for a in addresses): + raise ValueError(f"{hostname} has addresses that are not public") + return sorted(addresses)[0] + + def fetch_metadata_document(url): """GET a Client ID Metadata Document. Returns ``(document, cache_control)``. Raises ValueError for anything but - a small JSON document answered directly (no redirect) within the timeout, - and requests.RequestException for network errors. + a small JSON document answered directly (no redirect) by a public + address within the timeout. + + The connection goes to the address checked, not to a new resolution of + the name that a DNS rebinding could point to the internal network, and + is cut when the timeout expires, however slowly the host answers. """ - deadline = time.monotonic() + METADATA_DOCUMENT_TIMEOUT - response = requests.get( - url, - timeout=METADATA_DOCUMENT_TIMEOUT, - allow_redirects=False, - stream=True, - headers={"Accept": "application/json", "Accept-Encoding": "identity"}, + parts = urlsplit(url) + address = resolve_public_address(parts.hostname) + connection = http.client.HTTPSConnection( + parts.hostname, HTTPS_PORT, timeout=METADATA_DOCUMENT_TIMEOUT ) + + def connect(): + sock = socket.create_connection( + (address, HTTPS_PORT), METADATA_DOCUMENT_TIMEOUT + ) + # the handshake after the assignment, so that cut() can interrupt it + connection.sock = ssl.create_default_context().wrap_socket( + sock, server_hostname=parts.hostname, do_handshake_on_connect=False + ) + if expired.is_set(): + raise ValueError("document not received in time") + connection.sock.do_handshake() + + def cut(): + expired.set() + # not connected yet (connect() then gives up), or already closed + with contextlib.suppress(AttributeError, OSError): + connection.sock.shutdown(socket.SHUT_RDWR) + + connection.connect = connect + expired = threading.Event() + timer = threading.Timer(METADATA_DOCUMENT_TIMEOUT, cut) + timer.start() try: - if response.status_code != 200: - raise ValueError(f"HTTP status {response.status_code}") - content_type = response.headers.get("Content-Type", "") - content_type = content_type.split(";")[0].strip().lower() - if content_type != "application/json" and not content_type.endswith("+json"): - raise ValueError(f"unexpected content type {content_type!r}") - size, chunks = 0, [] - for chunk in response.iter_content(chunk_size=1024): - size += len(chunk) - if size > METADATA_DOCUMENT_MAX_BYTES: - raise ValueError(f"document larger than {size} bytes") - if time.monotonic() > deadline: - raise ValueError("document not received in time") - chunks.append(chunk) - return json.loads(b"".join(chunks)), response.headers.get("Cache-Control", "") + connection.request( + "GET", + urlunsplit(("", "", parts.path, parts.query, "")), + headers={ + "Accept": "application/json", + "User-Agent": "Odoo auth_oauth_server", + }, + ) + return read_metadata_response(connection.getresponse()) + except (OSError, http.client.HTTPException) as error: + if expired.is_set(): + raise ValueError("document not received in time") from error + raise ValueError(str(error) or repr(error)) from error finally: - response.close() + timer.cancel() + connection.close() + + +def read_metadata_response(response): + """The document and Cache-Control header of an http.client response.""" + if response.status != 200: + raise ValueError(f"HTTP status {response.status}") + content_type = response.getheader("Content-Type") or "" + content_type = content_type.split(";")[0].strip().lower() + if content_type != "application/json" and not content_type.endswith("+json"): + raise ValueError(f"unexpected content type {content_type!r}") + body = response.read(METADATA_DOCUMENT_MAX_BYTES + 1) + if len(body) > METADATA_DOCUMENT_MAX_BYTES: + raise ValueError(f"document larger than {METADATA_DOCUMENT_MAX_BYTES} bytes") + return json.loads(body), response.getheader("Cache-Control") or "" def max_age_from_cache_control(header, default=3600, minimum=300, maximum=86400):