diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index 3343f3b27..077d5b13f 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -1,6 +1,12 @@ exclude: | (?x) # NOT INSTALLABLE ADDONS + ^base_rest/| + ^base_rest_auth_api_key/| + ^base_rest_pydantic/| + ^extendable/| + ^pydantic/| + ^rest_log/| # END NOT INSTALLABLE ADDONS # Files and folders generated by bots, to avoid loops ^setup/|/static/description/index\.html$| diff --git a/base_rest/__manifest__.py b/base_rest/__manifest__.py index 755c27fe4..ed7d2ac53 100644 --- a/base_rest/__manifest__.py +++ b/base_rest/__manifest__.py @@ -9,7 +9,7 @@ "version": "18.0.1.1.1", "development_status": "Beta", "license": "LGPL-3", - "author": "ACSONE SA/NV, " "Odoo Community Association (OCA)", + "author": "ACSONE SA/NV, Odoo Community Association (OCA)", "maintainers": [], "website": "https://github.com/OCA/rest-framework", "depends": ["component", "web"], diff --git a/base_rest/components/service.py b/base_rest/components/service.py index b8611bcf2..ba10991d9 100644 --- a/base_rest/components/service.py +++ b/base_rest/components/service.py @@ -197,8 +197,7 @@ def _get_openapi_default_responses(self): return { "400": {"description": "One of the given parameter is not valid"}, "401": { - "description": "The user is not authorized. Authentication " - "is required" + "description": "The user is not authorized. Authentication is required" }, "404": {"description": "Requested resource not found"}, "403": { diff --git a/base_rest/http.py b/base_rest/http.py index 71b3c8a18..b5569476a 100644 --- a/base_rest/http.py +++ b/base_rest/http.py @@ -49,11 +49,11 @@ class JSONEncoder(json.JSONEncoder): def default(self, obj): # pylint: disable=E0202,arguments-differ - if isinstance(obj, datetime.datetime): - return obj.isoformat() - elif isinstance(obj, datetime.date): - return obj.isoformat() - elif isinstance(obj, datetime.time): + if ( + isinstance(obj, datetime.datetime) + or isinstance(obj, datetime.date) + or isinstance(obj, datetime.time) + ): return obj.isoformat() elif isinstance(obj, decimal.Decimal): return float(obj) @@ -141,7 +141,7 @@ def pre_dispatch(self, rule, args): try: self.request.params.update(json.loads(data)) except (ValueError, json.decoder.JSONDecodeError) as e: - msg = f"Invalid JSON data: {str(e)}" + msg = f"Invalid JSON data: {e!s}" _logger.info(f"{self.request.httprequest.path}: {msg}") raise BadRequest(msg) from e elif httprequest.mimetype == "multipart/form-data": diff --git a/base_rest/models/rest_service_registration.py b/base_rest/models/rest_service_registration.py index 60e06fd3b..005022411 100644 --- a/base_rest/models/rest_service_registration.py +++ b/base_rest/models/rest_service_registration.py @@ -192,7 +192,7 @@ def build_registry(self, services_registry, states=None, exclude_addons=None): graph = odoo.modules.graph.Graph() graph.add_module(self.env.cr, "base") - query = "SELECT name " "FROM ir_module_module " "WHERE state IN %s " + query = "SELECT name FROM ir_module_module WHERE state IN %s " params = [tuple(states)] if exclude_addons: query += " AND name NOT IN %s " @@ -423,7 +423,7 @@ def _generate_methods(self): methods=[http_method], type="restapi", ) - for attr in {"auth", "cors", "csrf", "save_session"}: + for attr in ("auth", "cors", "csrf", "save_session"): if attr in routing: route_params[attr] = routing[attr] method_exec = http.route(**route_params)(method_exec) diff --git a/extendable/models/extendable_registry_loader.py b/extendable/models/extendable_registry_loader.py index d1f915f5b..9433ffbc8 100644 --- a/extendable/models/extendable_registry_loader.py +++ b/extendable/models/extendable_registry_loader.py @@ -52,7 +52,7 @@ def build_registry( graph = odoo.modules.graph.Graph() graph.add_module(self.env.cr, "base") - query = "SELECT name " "FROM ir_module_module " "WHERE state IN %s " + query = "SELECT name FROM ir_module_module WHERE state IN %s " params = [tuple(states)] if exclude_addons: query += " AND name NOT IN %s " diff --git a/extendable/tests/common.py b/extendable/tests/common.py index 004db33a3..21e34f9d0 100644 --- a/extendable/tests/common.py +++ b/extendable/tests/common.py @@ -3,7 +3,6 @@ from contextlib import contextmanager -import odoo from odoo import SUPERUSER_ID, api from odoo.modules.registry import Registry from odoo.tests import common diff --git a/fastapi/README.rst b/fastapi/README.rst index b1848be3f..481bcc702 100644 --- a/fastapi/README.rst +++ b/fastapi/README.rst @@ -21,13 +21,13 @@ Odoo FastAPI :target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html :alt: License: LGPL-3 .. |badge3| image:: https://img.shields.io/badge/github-OCA%2Frest--framework-lightgray.png?logo=github - :target: https://github.com/OCA/rest-framework/tree/19.0/fastapi + :target: https://github.com/OCA/rest-framework/tree/20.0/fastapi :alt: OCA/rest-framework .. |badge4| image:: https://img.shields.io/badge/weblate-Translate%20me-F47D42.png - :target: https://translation.odoo-community.org/projects/rest-framework-19-0/rest-framework-19-0-fastapi + :target: https://translation.odoo-community.org/projects/rest-framework-20-0/rest-framework-20-0-fastapi :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/rest-framework&target_branch=19.0 + :target: https://runboat.odoo-community.org/builds?repo=OCA/rest-framework&target_branch=20.0 :alt: Try me on Runboat |badge1| |badge2| |badge3| |badge4| |badge5| @@ -1636,7 +1636,7 @@ Bug Tracker Bugs are tracked on `GitHub Issues `_. In case of trouble, please check there if your issue has already been reported. If you spotted it first, help us to smash it by providing a detailed and welcomed -`feedback `_. +`feedback `_. Do not contact contributors directly about support or help with technical issues. @@ -1647,12 +1647,16 @@ Authors ------- * ACSONE SA/NV +* Open2S Contributors ------------ - Laurent Mignon - Lois Rilo +- Open2S (https://www.open2s.com.ec): + + - Danilo Moya Maintainers ----------- @@ -1675,6 +1679,6 @@ Current `maintainer `__: |maintainer-lmignon| -This module is part of the `OCA/rest-framework `_ project on GitHub. +This module is part of the `OCA/rest-framework `_ project on GitHub. You are welcome to contribute. To learn how please visit https://odoo-community.org/page/Contribute. diff --git a/fastapi/__manifest__.py b/fastapi/__manifest__.py index 85928f7b5..0ac9ed2ac 100644 --- a/fastapi/__manifest__.py +++ b/fastapi/__manifest__.py @@ -3,18 +3,16 @@ { "name": "Odoo FastAPI", - "summary": """ - Odoo FastAPI endpoint""", - "version": "19.0.1.1.0", + "summary": "Odoo FastAPI endpoint", + "version": "20.0.1.1.0", "license": "LGPL-3", - "author": "ACSONE SA/NV,Odoo Community Association (OCA)", + "author": "ACSONE SA/NV, Open2S, Odoo Community Association (OCA)", "maintainers": ["lmignon"], "website": "https://github.com/OCA/rest-framework", "depends": ["endpoint_route_handler"], "data": [ "security/res_groups.xml", - "security/fastapi_endpoint.xml", - "security/ir_rule+acl.xml", + "security/ir.access.csv", "views/fastapi_menu.xml", "views/fastapi_endpoint.xml", "views/fastapi_endpoint_demo.xml", @@ -30,5 +28,5 @@ ] }, "development_status": "Beta", - "installable": False, + "installable": True, } diff --git a/fastapi/demo/fastapi_endpoint_demo.xml b/fastapi/demo/fastapi_endpoint_demo.xml index 1b9b13732..a3087f02e 100644 --- a/fastapi/demo/fastapi_endpoint_demo.xml +++ b/fastapi/demo/fastapi_endpoint_demo.xml @@ -1,4 +1,4 @@ - + @@ -31,7 +31,7 @@ This endpoint will be registered on the "/fastapi_demo" path --> - + Fastapi Demo Endpoint bool: path = self._normalize_url_path(path) prefix = self._normalize_url_path(prefix) - if path == prefix: - return True - if path.startswith(prefix + "/"): - return True - return False + return path == prefix or bool(path.startswith(prefix + "/")) @api.model def _find_first_matching_url_path(self, paths, prefix) -> str | None: @@ -296,7 +291,7 @@ def _clear_fastapi_exception_handlers(self, app: FastAPI) -> None: self._clear_fastapi_exception_handlers(route.app) @api.model - @tools.ormcache("path") + @api.ormcache("path") def get_uid(self, path): record = self._get_endpoint(path) if not record: diff --git a/fastapi/models/ir_rule.py b/fastapi/models/ir_rule.py index d46929615..74a86ea1e 100644 --- a/fastapi/models/ir_rule.py +++ b/fastapi/models/ir_rule.py @@ -4,15 +4,10 @@ from odoo import api, models -class IrRule(models.Model): - """Add authenticated_partner_id in record rule evaluation context. +class IrAccess(models.Model): + """Add authenticated_partner_id in record rule/access evaluation context.""" - This come from the env current odoo environment which is - populated by dependency method authenticated_partner_env or authenticated_partner - when a route handler depends one of them and is called by the FastAPI service layer. - """ - - _inherit = "ir.rule" + _inherit = "ir.access" @api.model def _eval_context(self): @@ -22,6 +17,6 @@ def _eval_context(self): ) return ctx - def _compute_domain_keys(self): - """Return the list of context keys to use for caching ``_compute_domain``.""" - return super()._compute_domain_keys() + ["authenticated_partner_id"] + def _get_access_context(self): + yield from super()._get_access_context() + yield self.env.context.get("authenticated_partner_id") diff --git a/fastapi/models/res_lang.py b/fastapi/models/res_lang.py index aaae58ee2..bb74fd739 100644 --- a/fastapi/models/res_lang.py +++ b/fastapi/models/res_lang.py @@ -5,14 +5,14 @@ from accept_language import parse_accept_language -from odoo import api, models, tools +from odoo import api, models class ResLang(models.Model): _inherit = "res.lang" @api.model - @tools.ormcache("accept_language") + @api.ormcache("accept_language") def _get_lang_from_accept_language(self, accept_language): """Get the language from the Accept-Language header. diff --git a/fastapi/patch.py b/fastapi/patch.py index 7904e46aa..7fc17980c 100644 --- a/fastapi/patch.py +++ b/fastapi/patch.py @@ -3,9 +3,18 @@ from urllib.parse import parse_qs, urlparse -from odoo.http import Request, db_filter +try: + import odoo.http.router as http_router + from odoo.http.requestlib import Request + from odoo.http.router import db_filter +except ImportError: + http_router = None + from odoo.http import Request, db_filter -_original_get_session_and_dbname = Request._get_session_and_dbname +_original_set_session_and_dbname = ( + getattr(http_router, "_set_session_and_dbname", None) if http_router else None +) +_original_get_session_and_dbname = getattr(Request, "_get_session_and_dbname", None) def _patched_get_session_and_dbname(self): @@ -28,4 +37,23 @@ def _patched_get_session_and_dbname(self): return session, dbname -Request._get_session_and_dbname = _patched_get_session_and_dbname +def _patched_set_session_and_dbname(request): + _original_set_session_and_dbname(request) + if not getattr(request, "db", None): + db = request.httprequest.args.get("db", "").strip() + if not db: + referer = request.httprequest.headers.get("Referer", "") + if referer: + parsed = urlparse(referer) + db = parse_qs(parsed.query).get("db", [""])[0].strip() + host = request.httprequest.environ.get("HTTP_HOST", "") + if db and db_filter([db], host=host): + request.db = db + if hasattr(request, "session") and request.session: + request.session.db = db + + +if _original_set_session_and_dbname is not None: + http_router._set_session_and_dbname = _patched_set_session_and_dbname +elif _original_get_session_and_dbname is not None: + Request._get_session_and_dbname = _patched_get_session_and_dbname diff --git a/fastapi/pools/fastapi_app.py b/fastapi/pools/fastapi_app.py index 9e04fe011..ef14a3f61 100644 --- a/fastapi/pools/fastapi_app.py +++ b/fastapi/pools/fastapi_app.py @@ -114,7 +114,12 @@ def set_cache_sequence(self, key: str, value: int) -> None: self.__cache_sequences[key] = value def _check_cache(self, env: Environment) -> None: - cache_sequences = env.registry.cache_sequences + cache_sequences = getattr(env.registry, "cache_sequences", None) + if cache_sequences is None: + cache_sequences = { + k: v[0] + for k, v in getattr(env.registry, "registry_caches__", {}).items() + } for key, value in cache_sequences.items(): if ( value != self.get_cache_sequence(key) diff --git a/fastapi/readme/CONTRIBUTORS.md b/fastapi/readme/CONTRIBUTORS.md index bdbfd97ff..83d6e08e7 100644 --- a/fastapi/readme/CONTRIBUTORS.md +++ b/fastapi/readme/CONTRIBUTORS.md @@ -1,2 +1,4 @@ - Laurent Mignon \<\> - Lois Rilo \<\> +- Open2S (https://www.open2s.com.ec): + - Danilo Moya \<\> diff --git a/fastapi/routers/demo_router.py b/fastapi/routers/demo_router.py index a3b94aa10..fccb81b08 100644 --- a/fastapi/routers/demo_router.py +++ b/fastapi/routers/demo_router.py @@ -12,7 +12,14 @@ from odoo.api import Environment from odoo.exceptions import AccessError, MissingError, UserError, ValidationError -from odoo.service.model import MAX_TRIES_ON_CONCURRENCY_FAILURE + +try: + from odoo.http.retrying import MAX_TRIES_ON_CONCURRENCY_FAILURE +except ImportError: + try: + from odoo.service.model import MAX_TRIES_ON_CONCURRENCY_FAILURE + except ImportError: + MAX_TRIES_ON_CONCURRENCY_FAILURE = 5 from odoo.addons.base.models.res_partner import ResPartner diff --git a/fastapi/security/fastapi_endpoint.xml b/fastapi/security/fastapi_endpoint.xml deleted file mode 100644 index 1bb23ac5d..000000000 --- a/fastapi/security/fastapi_endpoint.xml +++ /dev/null @@ -1,24 +0,0 @@ - - - - - fastapi.endpoint view - - - - - - - - - - fastapi.endpoint manage - - - - - - - - diff --git a/fastapi/security/ir.access.csv b/fastapi/security/ir.access.csv new file mode 100644 index 000000000..26addf867 --- /dev/null +++ b/fastapi/security/ir.access.csv @@ -0,0 +1,6 @@ +id,name,model_id,group_id/id,operation,domain +res_user_fastapi_running_user,Fastapi: Running user read users,res.users,fastapi.group_fastapi_endpoint_runner,r,"[('id', '=', user.id)]" +res_partner_fastapi_running_user,Fastapi: Running user read partners,res.partner,fastapi.group_fastapi_endpoint_runner,r,"['|', ('user_ids', '=', user.id), ('id', '=', authenticated_partner_id)]" +fastapi_endpoint_fastapi_running_user,Fastapi: Running user read endpoints,fastapi.endpoint,fastapi.group_fastapi_endpoint_runner,r,"[('user_id', '=', user.id)]" +fastapi_endpoint_access_view,fastapi.endpoint view,fastapi.endpoint,fastapi.group_fastapi_user,r, +fastapi_endpoint_access_manage,fastapi.endpoint manage,fastapi.endpoint,fastapi.group_fastapi_manager,crud, diff --git a/fastapi/security/ir_rule+acl.xml b/fastapi/security/ir_rule+acl.xml deleted file mode 100644 index 99b06ce56..000000000 --- a/fastapi/security/ir_rule+acl.xml +++ /dev/null @@ -1,73 +0,0 @@ - - - - - - Fastapi: Running user read users - - - - - - - - - - - Fastapi: Running user rule - - [('id', '=', user.id)] - - - - - - Fastapi: Running user read partners - - - - - - - - - - - Fastapi: Running user rule - - ['|', ('user_ids', '=', user.id), ('id', '=', authenticated_partner_id)] - - - - - - Fastapi: Running user read endpoints - - - - - - - - - - - Fastapi: Running user rule - - [('user_id', '=', user.id)] - - - diff --git a/fastapi/security/res_groups.xml b/fastapi/security/res_groups.xml index 7043ea69f..08492c107 100644 --- a/fastapi/security/res_groups.xml +++ b/fastapi/security/res_groups.xml @@ -1,17 +1,17 @@ - + - + FastAPI Helps you manage your Fastapi Endpoints - 99 + FastAPI - 99 + diff --git a/fastapi/static/description/index.html b/fastapi/static/description/index.html index 3abdf612f..84ac075f4 100644 --- a/fastapi/static/description/index.html +++ b/fastapi/static/description/index.html @@ -3,7 +3,7 @@ -README.rst +Odoo FastAPI + + +
+ + + +Odoo Community Association + +
+

FastAPI Auth JWT support

+ +

Beta License: LGPL-3 OCA/rest-framework Translate me on Weblate Try me on Runboat

+

This module provides FastAPI Depends to allow authentication +with +auth_jwt.

+

Table of contents

+ +
+

Usage

+

The following FastAPI dependencies are provided and importable from +odoo.addons.fastapi_auth_jwt.dependencies:

+

def auth_jwt_authenticated_payload() -> Payload

+
+Return the authenticated JWT payload. Raise a 401 (unauthorized) if +absent or invalid.
+

def auth_jwt_optionally_authenticated_payload() -> Payload | None

+
+Return the authenticated JWT payload, or None if the +Authorization header and cookie are absent. Raise a 401 +(unauthorized) if present and invalid.
+

def auth_jwt_authenticated_partner() -> Partner

+
+

Obtain the authenticated partner corresponding to the provided JWT +token, according to the partner strategy defined on the auth_jwt +validator. Raise a 401 (unauthorized) if the partner could not be +determined for any reason.

+

This is function suitable and intended to override +odoo.addons.fastapi.dependencies.authenticated_partner_impl.

+

The partner record returned by this function is bound to an +environment that uses the Odoo user obtained from the user strategy +defined on the auth_jwt validator. When used +authenticated_partner_impl this in turn ensures that +odoo.addons.fastapi.dependencies.authenticated_partner_env is +also bound to the correct Odoo user.

+
+

def auth_jwt_optionally_authenticated_partner() -> Partner

+
+Same as auth_jwt_partner except it returns an empty recordset +bound to the public user if the Authorization header and +cookie are absent, or if the JWT validator could not find the partner +and declares that the partner is not required.
+

def auth_jwt_authenticated_odoo_env() -> Environment

+
+

Return an Odoo environment using the the Odoo user obtained from the +user strategy defined on the auth_jwt validator, if the request +could be authenticated using a JWT validator. Raise a 401 +(unauthorized) otherwise.

+

This is function suitable and intended to override +odoo.addons.fastapi.dependencies.authenticated_odoo_env_impl.

+
+

def auth_jwt_default_validator_name() -> str | None

+
+

Return the name of the default JWT validator to use.

+

The default implementation returns None meaning only one active +JWT validator is allowed. This dependency is meant to be overridden.

+
+

def auth_jwt_http_header_authorization() -> str | None

+
+By default, return the credentials part of the Authorization +header, or None if absent. This dependency is meant to be +overridden, in particular with +fastapi.security.OAuth2AuthorizationCodeBearer to let swagger +handle OAuth2 authorization (such override is only necessary for +comfort when using the swagger interface).
+
+
+

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

+
    +
  • ACSONE SA/NV
  • +
+
+
+

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:

+

sbidoul

+

This module is part of the OCA/rest-framework project on GitHub.

+

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

+
+
+
+
+ + diff --git a/fastapi_auth_jwt/tests/__init__.py b/fastapi_auth_jwt/tests/__init__.py new file mode 100644 index 000000000..ae5a81385 --- /dev/null +++ b/fastapi_auth_jwt/tests/__init__.py @@ -0,0 +1 @@ +from . import test_fastapi_auth_jwt diff --git a/fastapi_auth_jwt/tests/test_fastapi_auth_jwt.py b/fastapi_auth_jwt/tests/test_fastapi_auth_jwt.py new file mode 100644 index 000000000..1d3e4e2f7 --- /dev/null +++ b/fastapi_auth_jwt/tests/test_fastapi_auth_jwt.py @@ -0,0 +1,210 @@ +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +import time +from typing import Annotated, Any + +import jwt + +from odoo.api import Environment +from odoo.tests import tagged + +from odoo.addons.base.models.res_partner import ResPartner +from odoo.addons.fastapi.tests.common import FastAPITransactionCase + +from fastapi import APIRouter, Depends + +from ..dependencies import ( + AuthJwtOdooEnv, + AuthJwtPartner, + AuthJwtPayload, + auth_jwt_authenticated_payload, + auth_jwt_default_validator_name, +) + +VALIDATOR = "fastapi_auth_jwt_test" +SECRET = "fastapi-auth-jwt-test-secret-with-enough-entropy" + +router = APIRouter() + + +@router.get("/payload") +def get_payload( + payload: Annotated[ + dict[str, Any], Depends(AuthJwtPayload(validator_name=VALIDATOR)) + ], +): + return payload + + +@router.get("/default_validator") +def get_default_validator_payload( + payload: Annotated[dict[str, Any], Depends(auth_jwt_authenticated_payload)], +): + return payload + + +@router.get("/optional_payload") +def get_optional_payload( + payload: Annotated[ + dict[str, Any] | None, + Depends(AuthJwtPayload(validator_name=VALIDATOR, allow_unauthenticated=True)), + ], +): + return {"payload": payload} + + +@router.get("/partner") +def get_partner( + partner: Annotated[ResPartner, Depends(AuthJwtPartner(validator_name=VALIDATOR))], +): + return {"id": partner.id, "uid": partner.env.uid} + + +@router.get("/optional_partner") +def get_optional_partner( + partner: Annotated[ + ResPartner, + Depends(AuthJwtPartner(validator_name=VALIDATOR, allow_unauthenticated=True)), + ], +): + return {"id": partner.id or None} + + +@router.get("/env") +def get_env( + env: Annotated[Environment, Depends(AuthJwtOdooEnv(validator_name=VALIDATOR))], +): + return {"uid": env.uid} + + +@tagged("post_install", "-at_install") +class TestFastapiAuthJwt(FastAPITransactionCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.user = cls.env["res.users"].create( + {"name": "JWT user", "login": "fastapi_auth_jwt_user"} + ) + cls.partner = cls.env["res.partner"].create( + {"name": "JWT partner", "email": "jwt.partner@example.com"} + ) + cls.validator = cls.env["auth.jwt.validator"].create( + { + "name": VALIDATOR, + "signature_type": "secret", + "secret_algorithm": "HS256", + "secret_key": SECRET, + "audience": "fastapi-test", + "issuer": "fastapi-test-issuer", + "user_id_strategy": "static", + "static_user_id": cls.user.id, + "partner_id_strategy": "email", + "partner_id_required": False, + } + ) + cls.default_fastapi_router = router + cls.default_fastapi_running_user = cls.env.ref("base.user_admin") + + def _token(self, key=SECRET, **claims): + payload = { + "aud": "fastapi-test", + "iss": "fastapi-test-issuer", + "exp": int(time.time()) + 300, + } + payload.update(claims) + return jwt.encode(payload, key, algorithm="HS256") + + def _get(self, path, token=None, **kw): + headers = {"Authorization": f"Bearer {token}"} if token else {} + with self._create_test_client(**kw) as client: + return client.get(path, headers=headers) + + # --- AuthJwtPayload ----------------------------------------------------- + + def test_payload_ok(self): + response = self._get("/payload", self._token(sub="abc")) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(response.json()["sub"], "abc") + + def test_payload_missing_token(self): + self.assertEqual(self._get("/payload").status_code, 401) + + def test_payload_bad_signature(self): + token = self._token(key="another-secret-another-secret-another-secret") + self.assertEqual(self._get("/payload", token).status_code, 401) + + def test_payload_expired(self): + token = self._token(exp=int(time.time()) - 60) + self.assertEqual(self._get("/payload", token).status_code, 401) + + def test_payload_wrong_audience(self): + token = self._token(aud="someone-else") + self.assertEqual(self._get("/payload", token).status_code, 401) + + def test_payload_wrong_issuer(self): + token = self._token(iss="someone-else") + self.assertEqual(self._get("/payload", token).status_code, 401) + + def test_payload_malformed_header(self): + with self._create_test_client() as client: + response = client.get("/payload", headers={"Authorization": "Basic xyz"}) + self.assertEqual(response.status_code, 401) + + def test_default_validator_override(self): + response = self._get( + "/default_validator", + self._token(sub="via-default"), + dependency_overrides={auth_jwt_default_validator_name: lambda: VALIDATOR}, + ) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(response.json()["sub"], "via-default") + + def test_optional_payload_without_token(self): + response = self._get("/optional_payload") + self.assertEqual(response.status_code, 200, response.text) + self.assertIsNone(response.json()["payload"]) + + def test_optional_payload_with_invalid_token(self): + token = self._token(exp=int(time.time()) - 60) + self.assertEqual(self._get("/optional_payload", token).status_code, 401) + + # --- AuthJwtPartner ----------------------------------------------------- + + def test_partner_ok(self): + response = self._get("/partner", self._token(email=self.partner.email)) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(response.json()["id"], self.partner.id) + self.assertEqual(response.json()["uid"], self.user.id) + + def test_partner_not_found(self): + token = self._token(email="nobody@example.com") + self.assertEqual(self._get("/partner", token).status_code, 401) + + def test_partner_without_email_claim(self): + self.assertEqual(self._get("/partner", self._token()).status_code, 401) + + def test_optional_partner_without_token(self): + response = self._get("/optional_partner") + self.assertEqual(response.status_code, 200, response.text) + self.assertIsNone(response.json()["id"]) + + def test_optional_partner_unknown_email(self): + token = self._token(email="nobody@example.com") + response = self._get("/optional_partner", token) + self.assertEqual(response.status_code, 200, response.text) + self.assertIsNone(response.json()["id"]) + + def test_optional_partner_required_by_validator(self): + self.validator.partner_id_required = True + token = self._token(email="nobody@example.com") + self.assertEqual(self._get("/optional_partner", token).status_code, 401) + + # --- AuthJwtOdooEnv ----------------------------------------------------- + + def test_env_runs_as_validator_user(self): + response = self._get("/env", self._token()) + self.assertEqual(response.status_code, 200, response.text) + self.assertEqual(response.json()["uid"], self.user.id) + + def test_env_missing_token(self): + self.assertEqual(self._get("/env").status_code, 401) diff --git a/requirements.txt b/requirements.txt index bcba9b734..b6e3bcdd0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,8 @@ # generated from manifests external_dependencies a2wsgi>=1.10.6 +cryptography fastapi>=0.110.0 parse-accept-language +pyjwt python-multipart ujson diff --git a/rest_log/__manifest__.py b/rest_log/__manifest__.py index 05eed0705..af41263d6 100644 --- a/rest_log/__manifest__.py +++ b/rest_log/__manifest__.py @@ -20,5 +20,5 @@ "views/rest_log_views.xml", "views/menu.xml", ], - 'installable': False, + "installable": False, } diff --git a/test-requirements.txt b/test-requirements.txt index af6c46470..d66ed1a3f 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -1,2 +1,4 @@ odoo_test_helper httpx2 +odoo-addon-auth_jwt @ git+https://github.com/OCA/server-auth.git@refs/pull/1035/head#subdirectory=auth_jwt +odoo-addon-endpoint_route_handler @ git+https://github.com/OCA/web-api.git@refs/pull/177/head#subdirectory=endpoint_route_handler