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..bea71be8 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** @@ -46,6 +50,20 @@ HTTP call returns by default the content of the response. A context Configuration ============= +Upgrade from versions prior to 19.0.2.0.1 +----------------------------------------- + +On upgrade from a version prior to ``19.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. + OAuth2 (Client Credentials) --------------------------- @@ -129,10 +147,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/__manifest__.py b/webservice/__manifest__.py index b482d8df..4bff2667 100644 --- a/webservice/__manifest__.py +++ b/webservice/__manifest__.py @@ -6,17 +6,15 @@ { "name": "WebService", "summary": """Defines webservice abstract definition to be used generally""", - "version": "19.0.1.4.0", + "version": "19.0.2.0.1", "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/data/neutralize.sql b/webservice/data/neutralize.sql index 264b1b17..d58b7269 100644 --- a/webservice/data/neutralize.sql +++ b/webservice/data/neutralize.sql @@ -1,9 +1,7 @@ --- remove webservice backend credentials +-- remove webservice backend OAuth2 credentials +-- (base credentials are cleared by webservice_core/data/neutralize.sql) UPDATE webservice_backend - SET username = NULL, - password = NULL, - api_key = NULL, - oauth2_clientid = NULL, + SET oauth2_clientid = NULL, oauth2_client_secret = NULL, oauth2_client_auth_value = NULL, oauth2_token = NULL; diff --git a/webservice/models/webservice_backend.py b/webservice/models/webservice_backend.py index 3b7f6916..e4d7b472 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 `19.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,22 @@ 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.onchange("auth_type") + def _onchange_auth_type(self): + # Keep `oauth2_flow` in sync in the UI as the user edits `auth_type`, + # regardless of whether `server_environment` is installed (see + # `create`/`write` below for the same guarantee on any other write). + if self.auth_type != "oauth2": + self.oauth2_flow = False + + @api.model_create_multi + def create(self, vals_list): + records = super().create(vals_list) + records.filtered( + lambda r: r.auth_type != "oauth2" and r.oauth2_flow + ).oauth2_flow = False + return records @api.constrains( "auth_type", @@ -151,38 +140,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`, - # regardless of whether `server_environment` is installed (see - # `create`/`write` below for the same guarantee on any other write). - if self.auth_type != "oauth2": - self.oauth2_flow = False - - @api.model_create_multi - def create(self, vals_list): - records = super().create(vals_list) - records.filtered( - lambda r: r.auth_type != "oauth2" and r.oauth2_flow - ).oauth2_flow = False - return records - def write(self, vals): res = super().write(vals) if "auth_type" in vals: @@ -192,7 +149,17 @@ def write(self, vals): return res def call(self, method, *args, **kwargs): - _logger.debug("backend %s: call %s %s %s", self.name, 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, + self._sanitize_kwargs_for_log(kwargs), + ) response = getattr(self._get_adapter(), method)(*args, **kwargs) _logger.debug("backend %s: response: \n%s", self.name, response) return response @@ -204,6 +171,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..5cc89fe7 100644 --- a/webservice/readme/CONFIGURE.md +++ b/webservice/readme/CONFIGURE.md @@ -1,3 +1,16 @@ +## Upgrade from versions prior to 19.0.2.0.1 + +On upgrade from a version prior to `19.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. + ## OAuth2 (Client Credentials) For the *Backend Application (Client Credentials Grant)* flow, two extra options 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/security/ir.model.access.csv b/webservice/security/ir.model.access.csv deleted file mode 100644 index f8bb5166..00000000 --- a/webservice/security/ir.model.access.csv +++ /dev/null @@ -1,2 +0,0 @@ -id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink -access_webservice_backend_edit,webservice_backend edit,model_webservice_backend,base.group_system,1,1,1,1 diff --git a/webservice/security/ir_rule.xml b/webservice/security/ir_rule.xml deleted file mode 100644 index 367dfb6c..00000000 --- a/webservice/security/ir_rule.xml +++ /dev/null @@ -1,10 +0,0 @@ - - - - webservice_backend multi-company - - - ['|', ('company_id','=',False), ('company_id', 'in', company_ids)] - - - diff --git a/webservice/static/description/index.html b/webservice/static/description/index.html index 32e0b279..84bf2614 100644 --- a/webservice/static/description/index.html +++ b/webservice/static/description/index.html @@ -377,31 +377,47 @@

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

Configuration

+
+

Upgrade from versions prior to 19.0.2.0.1

+

On upgrade from a version prior to 19.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.

+
-

OAuth2 (Client Credentials)

+

OAuth2 (Client Credentials)

For the Backend Application (Client Credentials Grant) flow, two extra options control how the token is requested, so that endpoints which deviate from the OAuth2 spec can still be used:

@@ -422,7 +438,7 @@

OAuth2 (Client Credentials)
-

Example: custom Authorization header

+

Example: custom Authorization header

Some providers require the credentials in a non-standard Authorization header (for instance Okta uses Authorization: SSWS <token>). Such an endpoint can be configured as:

@@ -442,7 +458,7 @@

Example: custom Authorization hea

-

Bug Tracker

+

Bug Tracker

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

Bug Tracker

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

-

Credits

+

Credits

-

Authors

+

Authors

  • Creu Blanca
  • Camptocamp
-

Maintainers

+

Maintainers

This module is maintained by the OCA.

Odoo Community Association @@ -474,8 +490,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..57f297d2 100644 --- a/webservice/tests/__init__.py +++ b/webservice/tests/__init__.py @@ -1,4 +1,3 @@ +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..41ef4c8a 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): @@ -152,7 +152,7 @@ def test_update_token_with_error(self): ) @responses.activate - def test_call_with_content_only_false_returns_response(self): + def test_call_returns_response(self): now = time.time() duration = 3600 responses.add( @@ -172,7 +172,6 @@ def test_call_with_content_only_false_returns_response(self): "post", url=f"{self.url}endpoint", data="payload", - content_only=False, ) self.assertEqual(response.status_code, 200) diff --git a/webservice/tests/test_utils.py b/webservice/tests/test_utils.py deleted file mode 100644 index a17f8232..00000000 --- a/webservice/tests/test_utils.py +++ /dev/null @@ -1,14 +0,0 @@ -# Copyright 2023 Camptocamp SA -# @author Simone Orsi -# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). - - -from odoo.tests.common import BaseCase - -from odoo.addons.webservice.utils import sanitize_url_for_log - - -class TestUtils(BaseCase): - def test_url_cleanup(self): - url = "https://custom.url/?a=1&apikey=secret&password=moresecret" - self.assertEqual(sanitize_url_for_log(url), "https://custom.url/?a=1") diff --git a/webservice/upgrades/19.0.2.0.1/post-update.py b/webservice/upgrades/19.0.2.0.1/post-update.py new file mode 100644 index 00000000..084cdb26 --- /dev/null +++ b/webservice/upgrades/19.0.2.0.1/post-update.py @@ -0,0 +1,32 @@ +# Copyright 2026 Camptocamp SA +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl). + +from openupgradelib import openupgrade + +from odoo.tools import parse_version + +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. + """ + # Databases coming from 18.0 >= 18.0.2.0.1 already went through the same + # upgrade step there: don't set the parameter back if it was removed. + if version.startswith("18.0.") and parse_version(version) >= parse_version( + "18.0.2.0.1" + ): + return + 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..44e52cde 100644 --- a/webservice/views/webservice_backend.xml +++ b/webservice/views/webservice_backend.xml @@ -3,167 +3,78 @@ 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 - - - - - - + + +
+
+

+ +

+

+ +

+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+ + + + + + +
+
+
+ + + + + + + + + + +