diff --git a/requirements.txt b/requirements.txt index 70c765a0..cc8d360a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,5 +2,7 @@ PyYAML jsonschema oauthlib +openupgradelib +requests requests-oauthlib responses diff --git a/webservice/README.rst b/webservice/README.rst index 654941aa..5ed64f60 100644 --- a/webservice/README.rst +++ b/webservice/README.rst @@ -35,8 +35,12 @@ WebService This module creates WebService frameworks to be used globally. The module introduces support for HTTP Request protocol. The webservice -HTTP call returns by default the content of the response. A context -'content_only' can be passed to get the full response object. +HTTP call returns the full ``requests.Response`` object. + +It builds on top of ``webservice_core`` (which provides the +``webservice.backend`` model with public/username-password/API key +authentication) to add OAuth2 authentication and ``server_environment`` +support. **Table of contents** @@ -86,7 +90,17 @@ endpoint can be configured as: When a database is neutralized, stored webservice backend credentials (username, password, API key, OAuth2 client id/secret/token, custom -OAuth2 auth header value) are cleared. +OAuth2 auth header value) are cleared. On upgrade from a version prior +to ``18.0.2.0.1``, a ``webservice.request_content_only`` system +parameter is created automatically (see that version's migration script) +to preserve the previous default behavior of HTTP calls, which returned +only the response content instead of the full ``requests.Response`` +object. + +If your code relies on that implicit default, keep the parameter for +now. Once it's adapted to use the full response object (see *Usage*), +delete the parameter under *Settings > Technical > System Parameters* - +new installs never get it set. Bug Tracker =========== @@ -129,10 +143,13 @@ promote its widespread use. .. |maintainer-etobella| image:: https://github.com/etobella.png?size=40px :target: https://github.com/etobella :alt: etobella +.. |maintainer-simahawk| image:: https://github.com/simahawk.png?size=40px + :target: https://github.com/simahawk + :alt: simahawk -Current `maintainer `__: +Current `maintainers `__: -|maintainer-etobella| +|maintainer-etobella| |maintainer-simahawk| This module is part of the `OCA/web-api `_ project on GitHub. diff --git a/webservice/__init__.py b/webservice/__init__.py index f64c35ff..6959ecb1 100644 --- a/webservice/__init__.py +++ b/webservice/__init__.py @@ -1,3 +1,4 @@ from . import components from . import models from . import controllers +from .hooks import post_init_hook, uninstall_hook diff --git a/webservice/__manifest__.py b/webservice/__manifest__.py index b482d8df..2d352aad 100644 --- a/webservice/__manifest__.py +++ b/webservice/__manifest__.py @@ -9,14 +9,12 @@ "version": "19.0.1.4.0", "license": "AGPL-3", "development_status": "Production/Stable", - "maintainers": ["etobella"], + "maintainers": ["etobella", "simahawk"], "author": "Creu Blanca, Camptocamp, Odoo Community Association (OCA)", "website": "https://github.com/OCA/web-api", - "depends": ["component"], + "depends": ["webservice_core", "component"], "external_dependencies": {"python": ["requests-oauthlib", "oauthlib", "responses"]}, "data": [ - "security/ir.model.access.csv", - "security/ir_rule.xml", "views/webservice_backend.xml", ], "demo": [], diff --git a/webservice/components/request_adapter.py b/webservice/components/request_adapter.py index 99645343..b733beb2 100644 --- a/webservice/components/request_adapter.py +++ b/webservice/components/request_adapter.py @@ -12,8 +12,7 @@ from requests_oauthlib import OAuth2Session from odoo.addons.component.core import Component - -from ..utils import StaticHeaderAuth, sanitize_url_for_log +from odoo.addons.webservice_core.utils import StaticHeaderAuth, sanitize_url_for_log _logger = logging.getLogger(__name__) @@ -26,7 +25,7 @@ class BaseRestRequestsAdapter(Component): # TODO: url and url_params could come from work_ctx def _request(self, method, url=None, url_params=None, **kwargs): url = self._get_url(url=url, url_params=url_params) - content_only = kwargs.pop("content_only", True) + self.collection._pop_deprecated_content_only_kwarg(kwargs) # TODO: turn on/off debug from webservice setting? url_to_log = self._sanitize_url_for_log(url) _logger.info("%s call to %s", method, url_to_log) @@ -41,7 +40,7 @@ def _request(self, method, url=None, url_params=None, **kwargs): # pylint: disable=E8106 request = requests.request(method, url, **new_kwargs) request.raise_for_status() - if content_only: + if self.collection._get_request_content_only(): return request.content return request @@ -206,7 +205,7 @@ def _token_fetch_kwargs(self, oauth_params): def _request(self, method, url=None, url_params=None, **kwargs): url = self._get_url(url=url, url_params=url_params) - content_only = kwargs.pop("content_only", True) + self.collection._pop_deprecated_content_only_kwarg(kwargs) new_kwargs = kwargs.copy() new_kwargs.update( { @@ -219,7 +218,7 @@ def _request(self, method, url=None, url_params=None, **kwargs): # pylint: disable=E8106 request = session.request(method, url, **new_kwargs) request.raise_for_status() - if content_only: + if self.collection._get_request_content_only(): return request.content return request diff --git a/webservice/hooks.py b/webservice/hooks.py new file mode 100644 index 00000000..a3c3db44 --- /dev/null +++ b/webservice/hooks.py @@ -0,0 +1,35 @@ +# Copyright 2025 Camptocamp SA +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +from odoo.addons.server_environment.uninstall import restore_env_managed_columns + +ENV_MANAGED_FIELDS = [ + "protocol", + "url", + "auth_type", + "username", + "password", + "api_key", + "api_key_header", + "content_type", + "oauth2_flow", + "oauth2_scope", + "oauth2_clientid", + "oauth2_client_secret", + "oauth2_authorization_url", + "oauth2_token_url", + "oauth2_audience", +] + + +def post_init_hook(env): + env["webservice.backend"]._preserve_not_env_managed_data(ENV_MANAGED_FIELDS) + + +def uninstall_hook(env): + """Restore database columns dropped by server.env.mixin.""" + restore_env_managed_columns( + env, + "webservice.backend", + ENV_MANAGED_FIELDS, + ) diff --git a/webservice/models/webservice_backend.py b/webservice/models/webservice_backend.py index 3b7f6916..5d1b9aa6 100644 --- a/webservice/models/webservice_backend.py +++ b/webservice/models/webservice_backend.py @@ -10,29 +10,26 @@ _logger = logging.getLogger(__name__) +# Backward-compat switch for the `content_only` default removal on `_request`. +# Existing databases get it set (see `webservice`'s `18.0.2.0.1` upgrade +# script) to keep returning only the response content; new installs get the +# full `requests.Response` object with no param set. Safe to delete once +# calling code has been adapted; the code checking it can then be dropped +# too. +CONTENT_ONLY_COMPAT_PARAM = "webservice.request_content_only" + class WebserviceBackend(models.Model): _name = "webservice.backend" - _inherit = ["collection.base"] - _description = "WebService Backend" + _inherit = [ + "webservice.backend", + "collection.base", + ] - name = fields.Char(required=True) - tech_name = fields.Char(required=True) - protocol = fields.Selection([("http", "HTTP Request")], required=True) - url = fields.Char(required=True) auth_type = fields.Selection( - selection=[ - ("none", "Public"), - ("user_pwd", "Username & password"), - ("api_key", "API Key"), - ("oauth2", "OAuth2"), - ], - required=True, + selection_add=[("oauth2", "OAuth2")], + ondelete={"oauth2": "cascade"}, ) - username = fields.Char(auth_type="user_pwd") - password = fields.Char(auth_type="user_pwd") - api_key = fields.Char(string="API Key", auth_type="api_key") - api_key_header = fields.Char(string="API Key header", auth_type="api_key") oauth2_flow = fields.Selection( [ ("backend_application", "Backend Application (Client Credentials Grant)"), @@ -86,30 +83,6 @@ class WebserviceBackend(models.Model): help="random key generated when authorization flow starts " "to ensure that no CSRF attack happen" ) - content_type = fields.Selection( - [ - ("application/json", "JSON"), - ("application/xml", "XML"), - ("application/x-www-form-urlencoded", "Form"), - ], - ) - company_id = fields.Many2one("res.company", string="Company") - - @api.constrains("auth_type") - def _check_auth_type(self): - valid_fields = { - k: v for k, v in self._fields.items() if hasattr(v, "auth_type") - } - for rec in self: - if rec.auth_type == "none": - continue - _fields = [v for v in valid_fields.values() if v.auth_type == rec.auth_type] - missing = [] - for _field in _fields: - if not rec[_field.name]: - missing.append(_field) - if missing: - raise exceptions.UserError(rec._msg_missing_auth_param(missing)) @api.constrains( "auth_type", @@ -151,22 +124,6 @@ def _check_oauth2_custom_header(self): if missing: raise exceptions.UserError(rec._msg_missing_auth_param(missing)) - def _msg_missing_auth_param(self, missing_fields): - def get_selection_value(fname): - return self._fields.get(fname).convert_to_export(self[fname], self) - - return self.env._( - "Webservice '%(name)s' requires '%(auth_type)s' authentication. " - "However, the following field(s) are not valued: %(fields)s", - name=self.name, - auth_type=get_selection_value("auth_type"), - fields=", ".join([f.string for f in missing_fields]), - ) - - def _valid_field_parameter(self, field, name): - extra_params = ("auth_type",) - return name in extra_params or super()._valid_field_parameter(field, name) - @api.onchange("auth_type") def _onchange_auth_type(self): # Keep `oauth2_flow` in sync in the UI as the user edits `auth_type`, @@ -192,6 +149,10 @@ def write(self, vals): return res def call(self, method, *args, **kwargs): + if not self.auth_type.startswith("oauth2"): + return super().call(method, *args, **kwargs) + # NOTE: oauth2 still relies on `component` for now, until it gets + # extracted to its own module and reworked to drop that dependency too. _logger.debug("backend %s: call %s %s %s", self.name, method, args, kwargs) response = getattr(self._get_adapter(), method)(*args, **kwargs) _logger.debug("backend %s: response: \n%s", self.name, response) @@ -204,6 +165,50 @@ def _get_adapter(self): webservice_protocol=self._get_adapter_protocol(), ) + def _request(self, method, url=None, url_params=None, **kwargs): + self._pop_deprecated_content_only_kwarg(kwargs) + response = super()._request(method, url=url, url_params=url_params, **kwargs) + if self._get_request_content_only(): + return response.content + return response + + def _pop_deprecated_content_only_kwarg(self, kwargs): + """Drop the removed ``content_only`` call argument, warning if used. + + It used to switch between returning the raw response content or the + full ``requests.Response`` object per call. It's gone: the full + response is always returned now, controlled only (and temporarily) + by the ``CONTENT_ONLY_COMPAT_PARAM`` system parameter for the whole + database - not something to keep sprinkling through call sites. + """ + if "content_only" in kwargs: + kwargs.pop("content_only") + _logger.warning( + "%s: the 'content_only' argument is no longer supported " + "and was ignored; the full response object is always " + "returned now. Remove it from the calling code.", + self.display_name, + ) + + def _get_request_content_only(self): + """Whether to return only the response content (legacy behavior). + + See ``CONTENT_ONLY_COMPAT_PARAM``. + """ + content_only = bool( + self.env["ir.config_parameter"].sudo().get_param(CONTENT_ONLY_COMPAT_PARAM) + ) + if content_only: + _logger.warning( + "%s: returning only the response content because the " + "'%s' system parameter is set (kept for backward " + "compatibility after upgrade). Delete it once the calling " + "code is adapted to use the full response object.", + self.display_name, + CONTENT_ONLY_COMPAT_PARAM, + ) + return content_only + def _get_adapter_protocol(self): protocol = self.protocol if self.auth_type.startswith("oauth2"): diff --git a/webservice/readme/CONFIGURE.md b/webservice/readme/CONFIGURE.md index 4cd9ccc6..e5818fa3 100644 --- a/webservice/readme/CONFIGURE.md +++ b/webservice/readme/CONFIGURE.md @@ -33,3 +33,13 @@ configured as: When a database is neutralized, stored webservice backend credentials (username, password, API key, OAuth2 client id/secret/token, custom OAuth2 auth header value) are cleared. +On upgrade from a version prior to `18.0.2.0.1`, a +`webservice.request_content_only` system parameter is created automatically +(see that version's migration script) to preserve the previous default +behavior of HTTP calls, which returned only the response content instead of +the full `requests.Response` object. + +If your code relies on that implicit default, keep the parameter for now. +Once it's adapted to use the full response object (see *Usage*), delete the +parameter under *Settings > Technical > System Parameters* - new installs +never get it set. diff --git a/webservice/readme/DESCRIPTION.md b/webservice/readme/DESCRIPTION.md index cdd44bd7..74b608df 100644 --- a/webservice/readme/DESCRIPTION.md +++ b/webservice/readme/DESCRIPTION.md @@ -1,3 +1,7 @@ This module creates WebService frameworks to be used globally. -The module introduces support for HTTP Request protocol. The webservice HTTP call returns by default the content of the response. A context 'content_only' can be passed to get the full response object. +The module introduces support for HTTP Request protocol. The webservice HTTP call returns the full `requests.Response` object. + +It builds on top of ``webservice_core`` (which provides the ``webservice.backend`` +model with public/username-password/API key authentication) to add OAuth2 +authentication and ``server_environment`` support. diff --git a/webservice/static/description/index.html b/webservice/static/description/index.html index 32e0b279..fab0af4b 100644 --- a/webservice/static/description/index.html +++ b/webservice/static/description/index.html @@ -377,8 +377,11 @@

WebService

Production/Stable License: AGPL-3 OCA/web-api Translate me on Weblate Try me on Runboat

This module creates WebService frameworks to be used globally.

The module introduces support for HTTP Request protocol. The webservice -HTTP call returns by default the content of the response. A context -‘content_only’ can be passed to get the full response object.

+HTTP call returns the full requests.Response object.

+

It builds on top of webservice_core (which provides the +webservice.backend model with public/username-password/API key +authentication) to add OAuth2 authentication and server_environment +support.

Table of contents

@@ -474,8 +486,8 @@

Maintainers

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:

-

etobella

+

Current maintainers:

+

etobella simahawk

This module is part of the OCA/web-api project on GitHub.

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

diff --git a/webservice/tests/__init__.py b/webservice/tests/__init__.py index 88a07b8f..37c85ace 100644 --- a/webservice/tests/__init__.py +++ b/webservice/tests/__init__.py @@ -1,4 +1,2 @@ +from . import test_content_only_compat from . import test_oauth2 -from . import test_webservice -from . import test_utils -from . import test_neutralize diff --git a/webservice/tests/test_content_only_compat.py b/webservice/tests/test_content_only_compat.py new file mode 100644 index 00000000..3552ebed --- /dev/null +++ b/webservice/tests/test_content_only_compat.py @@ -0,0 +1,64 @@ +# Copyright 2026 Camptocamp SA +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). +import responses + +from .common import CommonWebService + + +class TestContentOnlyCompat(CommonWebService): + """`content_only` removal, and its backward-compat system parameter. + + This lives in `webservice`, not `webservice_core`: the compat switch + only matters for databases that already ran with the old + `content_only=True` default, and that's `webservice`'s history, not + `webservice_core`'s (a new, not-yet-released module nobody depends on + with that old default). + """ + + @classmethod + def _setup_records(cls): + res = super()._setup_records() + cls.url = "https://localhost.demo.odoo/" + cls.webservice = cls.env["webservice.backend"].create( + { + "name": "WebService", + "protocol": "http", + "url": cls.url, + "tech_name": "demo_ws_content_only", + "auth_type": "none", + } + ) + return res + + @responses.activate + def test_returns_full_response_by_default(self): + responses.add(responses.GET, self.url, body="{}") + result = self.webservice.call("get") + self.assertEqual(result.content, b"{}") + self.assertEqual(result.status_code, 200) + + @responses.activate + def test_compat_param_restores_content_only(self): + self.env["ir.config_parameter"].sudo().set_param( + "webservice.request_content_only", "1" + ) + responses.add(responses.GET, self.url, body="{}") + with self.assertLogs( + "odoo.addons.webservice.models.webservice_backend", level="WARNING" + ) as log_catcher: + result = self.webservice.call("get") + self.assertEqual(result, b"{}") + self.assertTrue( + any("webservice.request_content_only" in m for m in log_catcher.output) + ) + + @responses.activate + def test_content_only_kwarg_is_ignored(self): + """The removed `content_only` kwarg no longer has any effect.""" + responses.add(responses.GET, self.url, body="{}") + with self.assertLogs( + "odoo.addons.webservice.models.webservice_backend", level="WARNING" + ) as log_catcher: + result = self.webservice.call("get", content_only=True) + self.assertEqual(result.content, b"{}") + self.assertTrue(any("content_only" in m for m in log_catcher.output)) diff --git a/webservice/tests/test_oauth2.py b/webservice/tests/test_oauth2.py index 1288cda8..5187edb1 100644 --- a/webservice/tests/test_oauth2.py +++ b/webservice/tests/test_oauth2.py @@ -70,7 +70,7 @@ def test_fetch_token(self): delta=1, # Accept a diff of 1s ) self.assertEqual(responses.calls[1].response.content.decode(), "OK") - self.assertEqual(result.decode(), "OK") + self.assertEqual(result.content.decode(), "OK") @responses.activate def test_update_token(self): @@ -112,7 +112,7 @@ def test_update_token(self): delta=1, # Accept a diff of 1s ) self.assertEqual(responses.calls[1].response.content.decode(), "OK") - self.assertEqual(result.decode(), "OK") + self.assertEqual(result.content.decode(), "OK") @responses.activate def test_update_token_with_error(self): diff --git a/webservice/upgrades/18.0.1.1.1/post-update.py b/webservice/upgrades/18.0.1.1.1/post-update.py new file mode 100644 index 00000000..c0fce93f --- /dev/null +++ b/webservice/upgrades/18.0.1.1.1/post-update.py @@ -0,0 +1,22 @@ +# Copyright 2026 Camptocamp SA +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from openupgradelib import openupgrade + +from odoo import exceptions + + +@openupgrade.migrate() +def migrate(env, version): + module = env["ir.module.module"].search([("name", "=", "webservice_server_env")]) + if not module: + raise exceptions.UserError( + env._( + "The 'webservice_server_env' module is not available. " + "It is required to preserve the server environment managed " + "fields of 'webservice.backend'. Make it available on the " + "addons path before upgrading 'webservice'." + ) + ) + if module.state == "uninstalled": + module.button_install() diff --git a/webservice/upgrades/18.0.2.0.1/post-update.py b/webservice/upgrades/18.0.2.0.1/post-update.py new file mode 100644 index 00000000..5c1f3f42 --- /dev/null +++ b/webservice/upgrades/18.0.2.0.1/post-update.py @@ -0,0 +1,24 @@ +# Copyright 2026 Camptocamp SA +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +from openupgradelib import openupgrade + +CONTENT_ONLY_COMPAT_PARAM = "webservice.request_content_only" + + +@openupgrade.migrate() +def migrate(env, version): + """Preserve the pre-upgrade behavior of HTTP webservice calls. + + Before this version, ``webservice.backend.call()`` (and friends) + returned only the response content (raw bytes) by default. That default + is gone: calls now always return the full ``requests.Response`` object. + + Existing databases get ``CONTENT_ONLY_COMPAT_PARAM`` set so their + calling code keeps working unchanged until it's adapted; new installs + never get it, so they see the new behavior right away. Leave the + parameter unset (or delete it) once the calling code is updated. + """ + icp = env["ir.config_parameter"].sudo() + if not icp.search_count([("key", "=", CONTENT_ONLY_COMPAT_PARAM)]): + icp.set_param(CONTENT_ONLY_COMPAT_PARAM, "1") diff --git a/webservice/views/webservice_backend.xml b/webservice/views/webservice_backend.xml index 6b398d92..7c401162 100644 --- a/webservice/views/webservice_backend.xml +++ b/webservice/views/webservice_backend.xml @@ -3,167 +3,55 @@ License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). --> - webservice.backend.form (in webservice) + webservice.backend.form (oauth2, in webservice) webservice.backend + -
-
-
- -
-

- -

-

- -

-
- - - - - - - - - - - - - - - - - - - - - - - - - -
-
-
-
- - - webservice.backend.search (in webservice) - webservice.backend - - - - - - - - - - - - webservice.backend.tree (in webservice) - webservice.backend - - - - - - + +