diff --git a/auth_oauth_server/README.rst b/auth_oauth_server/README.rst new file mode 100644 index 0000000000..5be767c6f4 --- /dev/null +++ b/auth_oauth_server/README.rst @@ -0,0 +1,204 @@ +========================== +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/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/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-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=18.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..65d1a9bca1 --- /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": "18.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..f89903f9d0 --- /dev/null +++ b/auth_oauth_server/controllers/main.py @@ -0,0 +1,299 @@ +# 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 + # ------------------------------------------------------------------ + # 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(): + 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, + readonly=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, + readonly=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, + readonly=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..9305bb4727 --- /dev/null +++ b/auth_oauth_server/hooks.py @@ -0,0 +1,18 @@ +# Copyright 2026 Lorenzo Battistini +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + + +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. + """ + 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..9bb601c2a3 --- /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", + 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: + 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..cf6557ca86 --- /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 = f"{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( + '{}="{}"'.format(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/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/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..c89683e3a9 --- /dev/null +++ b/auth_oauth_server/static/description/index.html @@ -0,0 +1,539 @@ + + + + + +OAuth Authorization Server + + + +
+

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..7fbc33f481 --- /dev/null +++ b/auth_oauth_server/tests/common.py @@ -0,0 +1,121 @@ +# 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) + + +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 + 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": f"{REDIRECT_URI}\n{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") + cls.accept_auth_methods() + + 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..24c19baec2 --- /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 = f"{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..911fb03df6 --- /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(f"{error} not raised") + + # ------------------------------------------------------------------ + # 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=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()) + 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..0b0b6aa9d4 --- /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..7da7229540 --- /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(), + f'Bearer resource_metadata="{metadata_url}", scope="read write"', + ) + self.assertEqual( + self.resource._www_authenticate( + error="invalid_token", error_description='a "quoted" text', scope="" + ), + f'Bearer resource_metadata="{metadata_url}", error="invalid_token", ' + 'error_description="a \\"quoted\\" text"', + ) + + 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..f8c42b86cf --- /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) + _port = parts.port # raises ValueError for an invalid port + 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 = (f"{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 f"{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(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", "") + 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..b2da13aede --- /dev/null +++ b/auth_oauth_server/views/auth_jwt_validator_views.xml @@ -0,0 +1,38 @@ + + + + + auth.jwt.validator.form.oauth_server + auth.jwt.validator + + + + user_id_strategy == 'oauth_server' + + + user_id_strategy == 'oauth_server' + + + 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 new file mode 100644 index 0000000000..abd7f1815d --- /dev/null +++ b/auth_oauth_server/views/oauth_server_authorization_views.xml @@ -0,0 +1,99 @@ + + + + oauth.server.authorization.list + oauth.server.authorization + + + + + + + + + + + + + + + oauth.server.authorization.form + oauth.server.authorization + +
+
+
+ + + + + + + + + + + + + + + + + +
+
+
+ + oauth.server.authorization.search + oauth.server.authorization + + + + + + + + + + + + + + + + OAuth Authorizations + oauth.server.authorization + 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 new file mode 100644 index 0000000000..72b734b481 --- /dev/null +++ b/auth_oauth_server/views/oauth_server_client_views.xml @@ -0,0 +1,139 @@ + + + + oauth.server.client.list + oauth.server.client + + + + + + + + + + + + oauth.server.client.form + oauth.server.client + +
+
+
+ + +
+

+ +

+
+ + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ + oauth.server.client.search + oauth.server.client + + + + + + + + + + + + + + + + OAuth Applications + oauth.server.client + oauth-server-clients + list,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..210b188419 --- /dev/null +++ b/auth_oauth_server/views/oauth_server_resource_views.xml @@ -0,0 +1,79 @@ + + + + oauth.server.resource.list + oauth.server.resource + + + + + + + + + + + oauth.server.resource.form + oauth.server.resource + +
+
+
+ + +
+

+ +

+
+ + + + + + + + + + + + + + +
+
+
+
+ + oauth.server.resource.search + oauth.server.resource + + + + + + + + + + Protected Resources + oauth.server.resource + oauth-server-resources + list,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..c7d596bad1 --- /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..4476ee10b9 --- /dev/null +++ b/auth_oauth_server/views/res_config_settings_views.xml @@ -0,0 +1,48 @@ + + + + res.config.settings.view.form.oauth_server + res.config.settings + + + + + + + + + +
+
+
+ + + +
+
+
+
+
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..d118e55227 --- /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. +
+
+ + + + + + +
+
+
+
+
+