diff --git a/auth_api_key/README.rst b/auth_api_key/README.rst new file mode 100644 index 0000000000..c6d03abaad --- /dev/null +++ b/auth_api_key/README.rst @@ -0,0 +1,141 @@ +.. image:: https://odoo-community.org/readme-banner-image + :target: https://odoo-community.org/get-involved?utm_source=readme + :alt: Odoo Community Association + +============ +Auth Api Key +============ + +.. + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! This file is generated by oca-gen-addon-readme !! + !! changes will be overwritten. !! + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + !! source digest: sha256:08a9e73e58d720eae5936fe3c94d7f4694c4613c80039ecf33ed5f68392c801c + !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! + +.. |badge1| image:: https://img.shields.io/badge/maturity-Production%2FStable-green.png + :target: https://odoo-community.org/page/development-status + :alt: Production/Stable +.. |badge2| image:: https://img.shields.io/badge/license-LGPL--3-blue.png + :target: http://www.gnu.org/licenses/lgpl-3.0-standalone.html + :alt: License: LGPL-3 +.. |badge3| image:: https://img.shields.io/badge/github-OCA%2Fserver--auth-lightgray.png?logo=github + :target: https://github.com/OCA/server-auth/tree/20.0/auth_api_key + :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-20-0/server-auth-20-0-auth_api_key + :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=20.0 + :alt: Try me on Runboat + +|badge1| |badge2| |badge3| |badge4| |badge5| + +Authenticate http requests from an API key. + +API keys are codes passed in (in the http header API-KEY) by programs +calling an API in order to identify -in this case- the calling program's +user. + +Take care while using this kind of mechanism since information into http +headers are visible in clear. Thus, use it only to authenticate requests +from known sources. + +For unknown sources, it is a good practice to filter out this header at +proxy level. + +Odoo allows users to authenticate ``XMLRPC/JSONRPC`` calls using their +API key instead of a password by native API keys (``res.users.apikey``). +However, ``auth_api_key`` has some special features of its own such as: + +- API keys remain usable even when the user is inactive, if enabled via + settings (e.g., for system users in a shopinvader case). +- Supports dual authentication via Basic Auth and API_KEY in separate + HTTP headers. +- Admins can manage API keys for all users + +Given these advantages, particularly in use case like system user +authentication, we have decided to keep the ``auth_api_key`` module + +**Table of contents** + +.. contents:: + :local: + +Configuration +============= + +The api key menu is available into Settings > Technical in debug mode. +By default, when you create an API key, the key is saved into the +database. + +When you create an API key, a random key is generated automatically. You +can replace it manually, or use the Generate Random Token button if an +existing record has no key. The key field is masked by default, and the +password widget provides a button to reveal the value when needed. + +When a database is neutralized, stored API key values are cleared. + +If you want to manage them via serve environment settings use +auth_api_key_server_env. + +Usage +===== + +To apply this authentication system to your http request you must set +'api_key' as value for the 'auth' parameter of your route definition +into your controller. + +.. code:: python + + class MyController(Controller): + + @route('/my_service', auth='api_key', ...) + def my_service(self, *args, **kwargs): + pass + +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 + +Contributors +------------ + +- Denis Robinet +- Laurent Mignon +- Quentin Groulard +- Sébastien Beau +- Chafique Delli +- Thien Vo Hong + +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. + +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_api_key/__init__.py b/auth_api_key/__init__.py new file mode 100644 index 0000000000..5bf67492bc --- /dev/null +++ b/auth_api_key/__init__.py @@ -0,0 +1,2 @@ +from . import models +from .hooks import post_load_hook diff --git a/auth_api_key/__manifest__.py b/auth_api_key/__manifest__.py new file mode 100644 index 0000000000..6f0f9ee49d --- /dev/null +++ b/auth_api_key/__manifest__.py @@ -0,0 +1,19 @@ +# Copyright 2018 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +{ + "name": "Auth Api Key", + "summary": "Authenticate http requests from an API key", + "version": "20.0.1.0.0", + "license": "LGPL-3", + "author": "ACSONE SA/NV,Odoo Community Association (OCA)", + "website": "https://github.com/OCA/server-auth", + "development_status": "Production/Stable", + "depends": ["base_setup"], + "post_load": "post_load_hook", + "data": [ + "security/ir.access.csv", + "views/auth_api_key.xml", + "views/res_config_settings.xml", + ], +} diff --git a/auth_api_key/data/neutralize.sql b/auth_api_key/data/neutralize.sql new file mode 100644 index 0000000000..d23b229ef7 --- /dev/null +++ b/auth_api_key/data/neutralize.sql @@ -0,0 +1,3 @@ +-- remove API keys +UPDATE auth_api_key + SET key = NULL; diff --git a/auth_api_key/hooks.py b/auth_api_key/hooks.py new file mode 100644 index 0000000000..85f2f29f34 --- /dev/null +++ b/auth_api_key/hooks.py @@ -0,0 +1,52 @@ +# Copyright 2026 Camptocamp SA (https://www.camptocamp.com). +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +from werkzeug.exceptions import HTTPException +from werkzeug.wrappers import Response + +from odoo.http.dispatcher import Dispatcher + + +def patch_dispatcher_pre_dispatch(): + """Patch odoo.http.Dispatcher's pre_dispatch method. + + For routes with cors enabled, Odoo will add a handler for the OPTIONS method, + which will raise an abort HTTPException with a 204 response describing the allowed + methods and headers in the Access-Control-* respnose headers. + + For routes with api_key authentication, we must inform the client that the + API-KEY header is allowed. + """ + original_pre_dispatch = Dispatcher.pre_dispatch + + def pre_dispatch(self, rule, args): + get_header = self.request.future_response.headers.get + set_header = self.request.future_response.headers.set + routing = rule.endpoint.routing + if ( + routing.get("cors") + and routing.get("auth") == "api_key" + and self.request.httprequest.method == "OPTIONS" + ): + try: + return original_pre_dispatch(self, rule, args) + except HTTPException as e: + if ( + isinstance(e.response, Response) + and e.response.status_code == 204 + and get_header("Access-Control-Allow-Headers") + ): + set_header( + "Access-Control-Allow-Headers", + f"{get_header('Access-Control-Allow-Headers')}, API-Key", + ) + raise + else: + return original_pre_dispatch(self, rule, args) + + Dispatcher.pre_dispatch = pre_dispatch + Dispatcher.pre_dispatch._original_method = original_pre_dispatch + + +def post_load_hook(): + patch_dispatcher_pre_dispatch() diff --git a/auth_api_key/i18n/auth_api_key.pot b/auth_api_key/i18n/auth_api_key.pot new file mode 100644 index 0000000000..00b53accdb --- /dev/null +++ b/auth_api_key/i18n/auth_api_key.pot @@ -0,0 +1,163 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# * auth_api_key +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 19.0\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: \n" +"Language-Team: \n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: \n" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_auth_api_key +msgid "API Key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__active +msgid "Active" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.constraint,message:auth_api_key.constraint_auth_api_key_name_uniq +msgid "Api Key name must be unique." +msgstr "" + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.auth_api_key_form_view +msgid "Archived" +msgstr "" + +#. module: auth_api_key +#: model:ir.actions.act_window,name:auth_api_key.auth_api_key_act_window +#: model:ir.ui.menu,name:auth_api_key.auth_api_key_menu +msgid "Auth Api Key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_res_company +msgid "Companies" +msgstr "" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_res_config_settings +msgid "Config Settings" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__create_uid +msgid "Created by" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__create_date +msgid "Created on" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__archived_user_disable_auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__archived_user_disable_auth_api_key +msgid "Disable API key for archived user" +msgstr "" + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.res_config_settings_view_form +msgid "Disable API key when archiving user" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_ir_http__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__display_name +msgid "Display Name" +msgstr "" + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.auth_api_key_form_view +msgid "Generate Random Token" +msgstr "" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_ir_http +msgid "HTTP Routing" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__id +#: model:ir.model.fields,field_description:auth_api_key.field_ir_http__id +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__id +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__id +msgid "ID" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_res_company__archived_user_disable_auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_res_config_settings__archived_user_disable_auth_api_key +msgid "" +"If checked, when a user is archived/unactivated the same change is " +"propagated to his related api key. It is not retroactive (nothing is done " +"when enabling/disabling this option)." +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__key +msgid "Key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__write_uid +msgid "Last Updated by" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__write_date +msgid "Last Updated on" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__name +msgid "Name" +msgstr "" + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "The API key is required." +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_auth_api_key__key +msgid "" +"The API key. Enter a dummy value in this field if it is\n" +" obtained from the server environment configuration." +msgstr "" + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "The key '%s' is not allowed" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_auth_api_key__user_id +msgid "" +"The user used to process the requests authenticated by\n" +" the api key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__user_id +msgid "User" +msgstr "" + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "User is not allowed" +msgstr "" diff --git a/auth_api_key/i18n/it.po b/auth_api_key/i18n/it.po new file mode 100644 index 0000000000..6786d9b125 --- /dev/null +++ b/auth_api_key/i18n/it.po @@ -0,0 +1,183 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# * auth_api_key +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 15.0\n" +"Report-Msgid-Bugs-To: \n" +"PO-Revision-Date: 2026-07-27 11:46+0000\n" +"Last-Translator: mymage \n" +"Language-Team: none\n" +"Language: it\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: nplurals=2; plural=n != 1;\n" +"X-Generator: Weblate 5.15.2\n" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_auth_api_key +msgid "API Key" +msgstr "Chiave API" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__active +msgid "Active" +msgstr "Attiva" + +#. module: auth_api_key +#: model:ir.model.constraint,message:auth_api_key.constraint_auth_api_key_name_uniq +msgid "Api Key name must be unique." +msgstr "La chiave API deve essere univoca." + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.auth_api_key_form_view +msgid "Archived" +msgstr "In archivio" + +#. module: auth_api_key +#: model:ir.actions.act_window,name:auth_api_key.auth_api_key_act_window +#: model:ir.ui.menu,name:auth_api_key.auth_api_key_menu +msgid "Auth Api Key" +msgstr "Chiave API di autenticazione" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_res_company +msgid "Companies" +msgstr "Aziende" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_res_config_settings +msgid "Config Settings" +msgstr "Impostazioni configurazione" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__create_uid +msgid "Created by" +msgstr "Creato da" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__create_date +msgid "Created on" +msgstr "Creato il" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__archived_user_disable_auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__archived_user_disable_auth_api_key +msgid "Disable API key for archived user" +msgstr "Disabilita chiave API per utenti archiviati" + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.res_config_settings_view_form +msgid "Disable API key when archiving user" +msgstr "Disabilita la chiave API quando si archivia un utente" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_ir_http__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__display_name +msgid "Display Name" +msgstr "Nome visualizzato" + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.auth_api_key_form_view +msgid "Generate Random Token" +msgstr "Genera token casuale" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_ir_http +msgid "HTTP Routing" +msgstr "Instradamento HTTP" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__id +#: model:ir.model.fields,field_description:auth_api_key.field_ir_http__id +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__id +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__id +msgid "ID" +msgstr "ID" + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_res_company__archived_user_disable_auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_res_config_settings__archived_user_disable_auth_api_key +msgid "" +"If checked, when a user is archived/unactivated the same change is " +"propagated to his related api key. It is not retroactive (nothing is done " +"when enabling/disabling this option)." +msgstr "" +"Se selezionata, quando un utente viene archiviato/disattivato, la stessa " +"modifica viene propagata alla sua chiave API correlata. Non è retroattivo " +"(non viene fatto nulla quando si abilita/disabilita questa opzione)." + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__key +msgid "Key" +msgstr "Chiave" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__write_uid +msgid "Last Updated by" +msgstr "Ultimo aggiornamento di" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__write_date +msgid "Last Updated on" +msgstr "Ultimo aggiornamento il" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__name +msgid "Name" +msgstr "Nome" + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "The API key is required." +msgstr "La chiave API è richiesta." + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_auth_api_key__key +msgid "" +"The API key. Enter a dummy value in this field if it is\n" +" obtained from the server environment configuration." +msgstr "" +"Chiave API. Se viene acquisita dalla configurazione\n" +" ambiente del server, inserire nel campo un valore fittizio." + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "The key '%s' is not allowed" +msgstr "Chiave '%s' non autorizzata" + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_auth_api_key__user_id +msgid "" +"The user used to process the requests authenticated by\n" +" the api key" +msgstr "" +"Utente utilizzato per elaborare le richieste autenticate\n" +" dalla chiave API" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__user_id +msgid "User" +msgstr "Utente" + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "User is not allowed" +msgstr "Utente non autorizzato" + +#, python-format +#~ msgid "The key %s is not allowed" +#~ msgstr "Chiave %s non autorizzata" + +#~ msgid "Last Modified on" +#~ msgstr "Ultima modifica il" + +#~ msgid "Server Env Defaults" +#~ msgstr "Variabili ambiente predefinite del server" diff --git a/auth_api_key/i18n/ja.po b/auth_api_key/i18n/ja.po new file mode 100644 index 0000000000..2f6c91489f --- /dev/null +++ b/auth_api_key/i18n/ja.po @@ -0,0 +1,164 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# * auth_api_key +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 19.0\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: Automatically generated\n" +"Language-Team: none\n" +"Language: ja\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_auth_api_key +msgid "API Key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__active +msgid "Active" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.constraint,message:auth_api_key.constraint_auth_api_key_name_uniq +msgid "Api Key name must be unique." +msgstr "" + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.auth_api_key_form_view +msgid "Archived" +msgstr "" + +#. module: auth_api_key +#: model:ir.actions.act_window,name:auth_api_key.auth_api_key_act_window +#: model:ir.ui.menu,name:auth_api_key.auth_api_key_menu +msgid "Auth Api Key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_res_company +msgid "Companies" +msgstr "" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_res_config_settings +msgid "Config Settings" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__create_uid +msgid "Created by" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__create_date +msgid "Created on" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__archived_user_disable_auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__archived_user_disable_auth_api_key +msgid "Disable API key for archived user" +msgstr "" + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.res_config_settings_view_form +msgid "Disable API key when archiving user" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_ir_http__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__display_name +msgid "Display Name" +msgstr "" + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.auth_api_key_form_view +msgid "Generate Random Token" +msgstr "" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_ir_http +msgid "HTTP Routing" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__id +#: model:ir.model.fields,field_description:auth_api_key.field_ir_http__id +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__id +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__id +msgid "ID" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_res_company__archived_user_disable_auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_res_config_settings__archived_user_disable_auth_api_key +msgid "" +"If checked, when a user is archived/unactivated the same change is " +"propagated to his related api key. It is not retroactive (nothing is done " +"when enabling/disabling this option)." +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__key +msgid "Key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__write_uid +msgid "Last Updated by" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__write_date +msgid "Last Updated on" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__name +msgid "Name" +msgstr "" + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "The API key is required." +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_auth_api_key__key +msgid "" +"The API key. Enter a dummy value in this field if it is\n" +" obtained from the server environment configuration." +msgstr "" + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "The key '%s' is not allowed" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_auth_api_key__user_id +msgid "" +"The user used to process the requests authenticated by\n" +" the api key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__user_id +msgid "User" +msgstr "" + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "User is not allowed" +msgstr "" diff --git a/auth_api_key/i18n/zh_CN.po b/auth_api_key/i18n/zh_CN.po new file mode 100644 index 0000000000..e4f022d4ce --- /dev/null +++ b/auth_api_key/i18n/zh_CN.po @@ -0,0 +1,164 @@ +# Translation of Odoo Server. +# This file contains the translation of the following modules: +# * auth_api_key +# +msgid "" +msgstr "" +"Project-Id-Version: Odoo Server 18.0\n" +"Report-Msgid-Bugs-To: \n" +"Last-Translator: Automatically generated\n" +"Language-Team: none\n" +"Language: zh_CN\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: \n" +"Plural-Forms: nplurals=1; plural=0;\n" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_auth_api_key +msgid "API Key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__active +msgid "Active" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.constraint,message:auth_api_key.constraint_auth_api_key_name_uniq +msgid "Api Key name must be unique." +msgstr "" + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.auth_api_key_form_view +msgid "Archived" +msgstr "" + +#. module: auth_api_key +#: model:ir.actions.act_window,name:auth_api_key.auth_api_key_act_window +#: model:ir.ui.menu,name:auth_api_key.auth_api_key_menu +msgid "Auth Api Key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_res_company +msgid "Companies" +msgstr "" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_res_config_settings +msgid "Config Settings" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__create_uid +msgid "Created by" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__create_date +msgid "Created on" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__archived_user_disable_auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__archived_user_disable_auth_api_key +msgid "Disable API key for archived user" +msgstr "" + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.res_config_settings_view_form +msgid "Disable API key when archiving user" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_ir_http__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__display_name +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__display_name +msgid "Display Name" +msgstr "" + +#. module: auth_api_key +#: model_terms:ir.ui.view,arch_db:auth_api_key.auth_api_key_form_view +msgid "Generate Random Token" +msgstr "" + +#. module: auth_api_key +#: model:ir.model,name:auth_api_key.model_ir_http +msgid "HTTP Routing" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__id +#: model:ir.model.fields,field_description:auth_api_key.field_ir_http__id +#: model:ir.model.fields,field_description:auth_api_key.field_res_company__id +#: model:ir.model.fields,field_description:auth_api_key.field_res_config_settings__id +msgid "ID" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_res_company__archived_user_disable_auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_res_config_settings__archived_user_disable_auth_api_key +msgid "" +"If checked, when a user is archived/unactivated the same change is " +"propagated to his related api key. It is not retroactive (nothing is done " +"when enabling/disabling this option)." +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__key +msgid "Key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__write_uid +msgid "Last Updated by" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__write_date +msgid "Last Updated on" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__name +msgid "Name" +msgstr "" + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "The API key is required." +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_auth_api_key__key +msgid "" +"The API key. Enter a dummy value in this field if it is\n" +" obtained from the server environment configuration." +msgstr "" + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "The key '%s' is not allowed" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,help:auth_api_key.field_auth_api_key__user_id +msgid "" +"The user used to process the requests authenticated by\n" +" the api key" +msgstr "" + +#. module: auth_api_key +#: model:ir.model.fields,field_description:auth_api_key.field_auth_api_key__user_id +msgid "User" +msgstr "" + +#. module: auth_api_key +#. odoo-python +#: code:addons/auth_api_key/models/auth_api_key.py:0 +msgid "User is not allowed" +msgstr "" diff --git a/auth_api_key/models/__init__.py b/auth_api_key/models/__init__.py new file mode 100644 index 0000000000..7c1ac84290 --- /dev/null +++ b/auth_api_key/models/__init__.py @@ -0,0 +1,4 @@ +from . import ir_http +from . import auth_api_key +from . import res_company +from . import res_config_settings diff --git a/auth_api_key/models/auth_api_key.py b/auth_api_key/models/auth_api_key.py new file mode 100644 index 0000000000..3a5358bef7 --- /dev/null +++ b/auth_api_key/models/auth_api_key.py @@ -0,0 +1,98 @@ +# Copyright 2018 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +import secrets + +from odoo import api, fields, models +from odoo.exceptions import AccessError, ValidationError +from odoo.tools import consteq + + +class AuthApiKey(models.Model): + _name = "auth.api.key" + _description = "API Key" + # Keys are resolved through ormcache'd methods: the ORM clears that cache + # on create, unlink, and on write of these fields. + _clear_cache_name = "default" + _clear_cache_on_fields = ("key", "user_id", "active") + + name = fields.Char(required=True) + key = fields.Char( + default=lambda self: self._generate_random_key_value(), + help="""The API key. Enter a dummy value in this field if it is + obtained from the server environment configuration.""", + ) + user_id = fields.Many2one( + comodel_name="res.users", + required=True, + help="""The user used to process the requests authenticated by + the api key""", + ) + # Not using related to stay backward compatible with having active keys + # for archived users (no need being invoiced by Odoo for api request users) + active = fields.Boolean( + compute="_compute_active", readonly=False, store=True, default=True + ) + + _name_uniq = models.Constraint("unique(name)", "Api Key name must be unique.") + + @api.constrains("key") + def _check_key_required(self): + for api_key in self: + if not api_key.key: + raise ValidationError(self.env._("The API key is required.")) + + @api.model + def _generate_random_key_value(self): + """Return a random API key value. + + The token is generated by the Odoo server instance so XML data and the + UI button can create a secret without storing any default value in the + module sources. + """ + return secrets.token_urlsafe(32) + + def generate_random_key(self, api_key_ids=None): + """Generate a key for records that do not have one yet. + + :param list api_key_ids: optional record IDs, mainly used by XML data + function calls where the method is invoked on the model. + :return: True when the operation completed. + """ + api_keys = self.browse(api_key_ids) if api_key_ids else self + for api_key in api_keys.filtered(lambda record: not record.key): + api_key.key = api_key._generate_random_key_value() + return True + + @api.model + def _retrieve_api_key(self, key): + return self.browse(self._retrieve_api_key_id(key)) + + @api.model + @api.ormcache("key") + def _retrieve_api_key_id(self, key): + if not self.env.user.has_group("base.group_system"): + raise AccessError(self.env._("User is not allowed")) + for api_key in self.search([("key", "!=", False)], limit=None): + if api_key.key and consteq(key, api_key.key): + return api_key.id + raise ValidationError(self.env._("The key '%s' is not allowed", key)) + + @api.model + @api.ormcache("key") + def _retrieve_uid_from_api_key(self, key): + return self._retrieve_api_key(key).user_id.id + + def _clear_key_cache(self): + self.env.transaction.invalidate_ormcache() + + @api.depends( + "user_id.active", "user_id.company_id.archived_user_disable_auth_api_key" + ) + def _compute_active(self): + option_disable_key = self.user_id.company_id.archived_user_disable_auth_api_key + for record in self: + if option_disable_key: + record.active = record.user_id.active + # To stay coherent if the option is disabled the active field is not + # changed. Because the field is stored, it should not be an issue. diff --git a/auth_api_key/models/ir_http.py b/auth_api_key/models/ir_http.py new file mode 100644 index 0000000000..559d352810 --- /dev/null +++ b/auth_api_key/models/ir_http.py @@ -0,0 +1,37 @@ +# Copyright 2018 ACSONE SA/NV +# Copyright 2017 Akretion (http://www.akretion.com). +# @author Sébastien BEAU +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +import logging + +from werkzeug.exceptions import Unauthorized + +from odoo import models +from odoo.http import request + +_logger = logging.getLogger(__name__) + + +class IrHttp(models.AbstractModel): + _inherit = "ir.http" + + @classmethod + def _auth_method_api_key(cls, routing): + headers = request.httprequest.environ + api_key = headers.get("HTTP_API_KEY") + if api_key: + request.update_env(user=1) + auth_api_key = request.env["auth.api.key"]._retrieve_api_key(api_key) + if auth_api_key: + # reset _env on the request since we change the uid... + # the next call to env will instantiate an new + # odoo.api.Environment with the user defined on the + # auth.api_key + request._env = None + request.update_env(user=auth_api_key.user_id.id) + request.auth_api_key = api_key + request.auth_api_key_id = auth_api_key.id + return True + _logger.error("Wrong HTTP_API_KEY, access denied") + raise Unauthorized() diff --git a/auth_api_key/models/res_company.py b/auth_api_key/models/res_company.py new file mode 100644 index 0000000000..adfdf2cb78 --- /dev/null +++ b/auth_api_key/models/res_company.py @@ -0,0 +1,17 @@ +# Copyright 2023 Camptocamp SA +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) + +from odoo import fields, models + + +class ResCompany(models.Model): + _inherit = "res.company" + + archived_user_disable_auth_api_key = fields.Boolean( + string="Disable API key for archived user", + help=( + "If checked, when a user is archived/unactivated the same change is " + "propagated to his related api key. It is not retroactive (nothing is done " + " when enabling/disabling this option)." + ), + ) diff --git a/auth_api_key/models/res_config_settings.py b/auth_api_key/models/res_config_settings.py new file mode 100644 index 0000000000..f7cc3aeaff --- /dev/null +++ b/auth_api_key/models/res_config_settings.py @@ -0,0 +1,12 @@ +# Copyright 2023 Camptocamp SA +# License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl.html) + +from odoo import fields, models + + +class ResConfigSettings(models.TransientModel): + _inherit = "res.config.settings" + + archived_user_disable_auth_api_key = fields.Boolean( + related="company_id.archived_user_disable_auth_api_key", readonly=False + ) diff --git a/auth_api_key/pyproject.toml b/auth_api_key/pyproject.toml new file mode 100644 index 0000000000..4231d0cccb --- /dev/null +++ b/auth_api_key/pyproject.toml @@ -0,0 +1,3 @@ +[build-system] +requires = ["whool"] +build-backend = "whool.buildapi" diff --git a/auth_api_key/readme/CONFIGURE.md b/auth_api_key/readme/CONFIGURE.md new file mode 100644 index 0000000000..12f823bb97 --- /dev/null +++ b/auth_api_key/readme/CONFIGURE.md @@ -0,0 +1,13 @@ +The api key menu is available into Settings \> Technical in debug mode. +By default, when you create an API key, the key is saved into the +database. + +When you create an API key, a random key is generated automatically. You +can replace it manually, or use the Generate Random Token button if an +existing record has no key. The key field is masked by default, and the +password widget provides a button to reveal the value when needed. + +When a database is neutralized, stored API key values are cleared. + +If you want to manage them via serve environment settings use +auth_api_key_server_env. diff --git a/auth_api_key/readme/CONTRIBUTORS.md b/auth_api_key/readme/CONTRIBUTORS.md new file mode 100644 index 0000000000..efda422667 --- /dev/null +++ b/auth_api_key/readme/CONTRIBUTORS.md @@ -0,0 +1,6 @@ +- Denis Robinet \<\> +- Laurent Mignon \<\> +- Quentin Groulard \<\> +- Sébastien Beau \<\> +- Chafique Delli \<\> +- Thien Vo Hong \<\> diff --git a/auth_api_key/readme/DESCRIPTION.md b/auth_api_key/readme/DESCRIPTION.md new file mode 100644 index 0000000000..4cac579599 --- /dev/null +++ b/auth_api_key/readme/DESCRIPTION.md @@ -0,0 +1,19 @@ +Authenticate http requests from an API key. + +API keys are codes passed in (in the http header API-KEY) by programs +calling an API in order to identify -in this case- the calling program's +user. + +Take care while using this kind of mechanism since information into http +headers are visible in clear. Thus, use it only to authenticate requests +from known sources. + +For unknown sources, it is a good practice to filter out this header at +proxy level. + +Odoo allows users to authenticate `XMLRPC/JSONRPC` calls using their API key instead of a password by native API keys (`res.users.apikey`). However, `auth_api_key` has some special features of its own such as: +- API keys remain usable even when the user is inactive, if enabled via settings (e.g., for system users in a shopinvader case). +- Supports dual authentication via Basic Auth and API_KEY in separate HTTP headers. +- Admins can manage API keys for all users + +Given these advantages, particularly in use case like system user authentication, we have decided to keep the `auth_api_key` module \ No newline at end of file diff --git a/auth_api_key/readme/USAGE.md b/auth_api_key/readme/USAGE.md new file mode 100644 index 0000000000..547d48759c --- /dev/null +++ b/auth_api_key/readme/USAGE.md @@ -0,0 +1,11 @@ +To apply this authentication system to your http request you must set +'api_key' as value for the 'auth' parameter of your route definition +into your controller. + +``` python +class MyController(Controller): + + @route('/my_service', auth='api_key', ...) + def my_service(self, *args, **kwargs): + pass +``` diff --git a/auth_api_key/security/ir.access.csv b/auth_api_key/security/ir.access.csv new file mode 100644 index 0000000000..5cd894ed22 --- /dev/null +++ b/auth_api_key/security/ir.access.csv @@ -0,0 +1,2 @@ +id,name,model_id,group_id/id,operation,domain +access_auth_api_key,access_auth_api_key,auth.api.key,base.group_system,crud, diff --git a/auth_api_key/static/description/icon.png b/auth_api_key/static/description/icon.png new file mode 100644 index 0000000000..3a0328b516 Binary files /dev/null and b/auth_api_key/static/description/icon.png differ diff --git a/auth_api_key/static/description/index.html b/auth_api_key/static/description/index.html new file mode 100644 index 0000000000..c6ae473039 --- /dev/null +++ b/auth_api_key/static/description/index.html @@ -0,0 +1,482 @@ + + + + + +Auth Api Key + + + +
+ + + +Odoo Community Association + +
+

Auth Api Key

+ +

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

+

Authenticate http requests from an API key.

+

API keys are codes passed in (in the http header API-KEY) by programs +calling an API in order to identify -in this case- the calling program’s +user.

+

Take care while using this kind of mechanism since information into http +headers are visible in clear. Thus, use it only to authenticate requests +from known sources.

+

For unknown sources, it is a good practice to filter out this header at +proxy level.

+

Odoo allows users to authenticate XMLRPC/JSONRPC calls using their +API key instead of a password by native API keys (res.users.apikey). +However, auth_api_key has some special features of its own such as:

+
    +
  • API keys remain usable even when the user is inactive, if enabled via +settings (e.g., for system users in a shopinvader case).
  • +
  • Supports dual authentication via Basic Auth and API_KEY in separate +HTTP headers.
  • +
  • Admins can manage API keys for all users
  • +
+

Given these advantages, particularly in use case like system user +authentication, we have decided to keep the auth_api_key module

+

Table of contents

+ +
+

Configuration

+

The api key menu is available into Settings > Technical in debug mode. +By default, when you create an API key, the key is saved into the +database.

+

When you create an API key, a random key is generated automatically. You +can replace it manually, or use the Generate Random Token button if an +existing record has no key. The key field is masked by default, and the +password widget provides a button to reveal the value when needed.

+

When a database is neutralized, stored API key values are cleared.

+

If you want to manage them via serve environment settings use +auth_api_key_server_env.

+
+
+

Usage

+

To apply this authentication system to your http request you must set +‘api_key’ as value for the ‘auth’ parameter of your route definition +into your controller.

+
+class MyController(Controller):
+
+    @route('/my_service', auth='api_key', ...)
+    def my_service(self, *args, **kwargs):
+        pass
+
+
+
+

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
  • +
+
+
+

Contributors

+ +
+
+

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.

+

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_api_key/tests/__init__.py b/auth_api_key/tests/__init__.py new file mode 100644 index 0000000000..7cb6186a03 --- /dev/null +++ b/auth_api_key/tests/__init__.py @@ -0,0 +1,3 @@ +from . import test_auth_api_key +from . import test_controllers +from . import test_neutralize diff --git a/auth_api_key/tests/test_auth_api_key.py b/auth_api_key/tests/test_auth_api_key.py new file mode 100644 index 0000000000..1e8ac0ec7e --- /dev/null +++ b/auth_api_key/tests/test_auth_api_key.py @@ -0,0 +1,124 @@ +# Copyright 2018 ACSONE SA/NV +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). +from odoo.exceptions import AccessError, ValidationError +from odoo.tests.common import TransactionCase + + +class TestAuthApiKey(TransactionCase): + @classmethod + def setUpClass(cls, *args, **kwargs): + super().setUpClass(*args, **kwargs) + cls.AuthApiKey = cls.env["auth.api.key"] + cls.partner_demo = cls.env["res.partner"].create( + { + "name": "Demo Partner", + } + ) + cls.demo_user = cls.env["res.users"].create( + { + "partner_id": cls.partner_demo.id, + "login": "demotest", + "password": "demotest", + } + ) + cls.api_key_good = cls.AuthApiKey.create( + {"name": "good", "user_id": cls.demo_user.id, "key": "api_key"} + ) + + def test_create_without_key_generates_random_key(self): + """Test API key creation generates an API key when no key is provided.""" + api_key = self.AuthApiKey.create( + {"name": "generated", "user_id": self.demo_user.id} + ) + self.assertTrue(api_key.key) + self.assertEqual( + self.AuthApiKey._retrieve_uid_from_api_key(api_key.key), + self.demo_user.id, + ) + + def test_generate_random_key_keeps_existing_key(self): + """Test random key generation does not overwrite an existing key.""" + api_key = self.AuthApiKey.create( + {"name": "existing", "user_id": self.demo_user.id, "key": "existing_key"} + ) + api_key.generate_random_key() + self.assertEqual(api_key.key, "existing_key") + + def test_lookup_key_from_db(self): + demo_user = self.demo_user + self.assertEqual( + self.env["auth.api.key"]._retrieve_uid_from_api_key("api_key"), demo_user.id + ) + + def test_wrong_key(self): + with self.assertRaises(ValidationError), self.env.cr.savepoint(): + self.env["auth.api.key"]._retrieve_uid_from_api_key("api_wrong_key") + + def test_empty_key_is_rejected(self): + with self.assertRaises(ValidationError), self.env.cr.savepoint(): + self.AuthApiKey.create( + {"name": "empty", "user_id": self.demo_user.id, "key": ""} + ) + with self.assertRaises(ValidationError), self.env.cr.savepoint(): + self.api_key_good.key = False + + def test_user_not_allowed(self): + # only system users can check for key + with self.assertRaises(AccessError), self.env.cr.savepoint(): + self.env["auth.api.key"].with_user( + user=self.demo_user + )._retrieve_uid_from_api_key("api_wrong_key") + + def test_cache_invalidation(self): + self.assertEqual( + self.env["auth.api.key"]._retrieve_uid_from_api_key("api_key"), + self.demo_user.id, + ) + self.api_key_good.write({"key": "updated_key"}) + self.assertEqual( + self.env["auth.api.key"]._retrieve_uid_from_api_key("updated_key"), + self.demo_user.id, + ) + with self.assertRaises(ValidationError): + self.env["auth.api.key"]._retrieve_uid_from_api_key("api_key") + + def test_cache_invalidation_on_archive(self): + self.assertEqual( + self.AuthApiKey._retrieve_uid_from_api_key("api_key"), self.demo_user.id + ) + self.api_key_good.active = False + with self.assertRaises(ValidationError): + self.AuthApiKey._retrieve_uid_from_api_key("api_key") + + def test_cache_invalidation_on_unlink(self): + self.assertEqual( + self.AuthApiKey._retrieve_uid_from_api_key("api_key"), self.demo_user.id + ) + self.api_key_good.unlink() + with self.assertRaises(ValidationError): + self.AuthApiKey._retrieve_uid_from_api_key("api_key") + + def test_user_archived_unarchived_with_option_on(self): + self.env.company.archived_user_disable_auth_api_key = True + demo_user = self.demo_user + self.assertEqual( + self.env["auth.api.key"]._retrieve_uid_from_api_key("api_key"), demo_user.id + ) + demo_user.active = False + with self.assertRaises(ValidationError): + self.env["auth.api.key"]._retrieve_uid_from_api_key("api_key") + demo_user.active = True + self.assertEqual( + self.env["auth.api.key"]._retrieve_uid_from_api_key("api_key"), demo_user.id + ) + + def test_user_archived_unarchived_with_option_off(self): + self.env.company.archived_user_disable_auth_api_key = False + demo_user = self.demo_user + self.assertEqual( + self.env["auth.api.key"]._retrieve_uid_from_api_key("api_key"), demo_user.id + ) + demo_user.active = False + self.assertEqual( + self.env["auth.api.key"]._retrieve_uid_from_api_key("api_key"), demo_user.id + ) diff --git a/auth_api_key/tests/test_controllers.py b/auth_api_key/tests/test_controllers.py new file mode 100644 index 0000000000..77acc6e77a --- /dev/null +++ b/auth_api_key/tests/test_controllers.py @@ -0,0 +1,59 @@ +# Copyright 2026 Camptocamp SA (https://www.camptocamp.com). +# License AGPL-3.0 or later (https://www.gnu.org/licenses/agpl). + +import json + +from odoo.http import Controller, route +from odoo.tests import HttpCase, new_test_user +from odoo.tools import mute_logger + + +class TestControllers(HttpCase): + @classmethod + def setUpClass(cls): + super().setUpClass() + cls.AuthApiKey = cls.env["auth.api.key"] + cls.test_user = new_test_user( + cls.env, + name="Test User", + login="test", + # Strong enough for password_security, which lands in the same + # database on the CI and enforces its policy on every user. + password="Test!2345", + email="test@test.com", + group_ids=[cls.env.ref("base.group_user").id], + company_id=cls.env.company.id, + ) + cls.api_key = cls.AuthApiKey.create( + {"name": "good", "user_id": cls.test_user.id, "key": "api_key"} + ) + + class DummyController(Controller): + @route("/web/auth-api-key", type="http", auth="api_key", sitemap=False) + def auth_api_key(self, **params): + return json.dumps({"name": self.env.user.name}) + + @route("/web/auth-api-key-cors", type="http", auth="api_key", cors="*") + def auth_api_key_cors(self, **params): + return json.dumps({"name": self.env.user.name}) + + cls.env.transaction.invalidate_ormcache("routing") + cls.addClassCleanup(cls.env.transaction.invalidate_ormcache, "routing") + + def test_auth_api_key_ok(self): + res = self.url_open("/web/auth-api-key", headers={"API-KEY": self.api_key.key}) + self.assertEqual(res.status_code, 200) + self.assertEqual(res.json(), {"name": self.test_user.name}) + + @mute_logger("odoo.addons.base.models.ir_http") + def test_auth_api_key_wrong(self): + with self.assertLogs("odoo.http") as cm: + res = self.url_open("/web/auth-api-key", headers={"API-KEY": "wrong"}) + self.assertEqual(res.status_code, 403) + self.assertIn("Access Denied", cm.output[0]) + + def test_auth_api_key_cors_options(self): + res = self.url_open("/web/auth-api-key-cors", method="OPTIONS") + self.assertEqual(res.status_code, 204) + self.assertEqual(res.headers["Access-Control-Allow-Origin"], "*") + self.assertIn("API-Key", res.headers["Access-Control-Allow-Headers"]) diff --git a/auth_api_key/tests/test_neutralize.py b/auth_api_key/tests/test_neutralize.py new file mode 100644 index 0000000000..4b5d16828b --- /dev/null +++ b/auth_api_key/tests/test_neutralize.py @@ -0,0 +1,25 @@ +# Copyright 2026 Camptocamp SA +# License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl). + +from odoo.modules import neutralize +from odoo.tests import tagged +from odoo.tests.common import TransactionCase + + +@tagged("post_install", "-at_install", "neutralize") +class TestAuthApiKeyNeutralize(TransactionCase): + def test_neutralize_removes_api_key_values(self): + """Test database neutralization clears stored API key secrets.""" + api_key = self.env["auth.api.key"].create( + { + "name": "neutralize", + "user_id": self.env.ref("base.user_admin").id, + "key": "secret-key", + } + ) + + queries = neutralize.get_neutralization_queries(["auth_api_key"]) + for query in queries: + self.cr.execute(query) + api_key.invalidate_recordset(["key"]) + self.assertFalse(api_key.key) diff --git a/auth_api_key/views/auth_api_key.xml b/auth_api_key/views/auth_api_key.xml new file mode 100644 index 0000000000..558c765c0c --- /dev/null +++ b/auth_api_key/views/auth_api_key.xml @@ -0,0 +1,64 @@ + + + + + auth.api.key.form (in auth_api_key) + auth.api.key + +
+ + + + +
+
+
+ + auth.api.key.list (in auth_api_key) + auth.api.key + + + + + + + + + Auth Api Key + auth.api.key + list,form + [] + {} + + + Auth Api Key + + + + +
diff --git a/auth_api_key/views/res_config_settings.xml b/auth_api_key/views/res_config_settings.xml new file mode 100644 index 0000000000..3ef1346c77 --- /dev/null +++ b/auth_api_key/views/res_config_settings.xml @@ -0,0 +1,21 @@ + + + + + res.config.settings.form.inherit + res.config.settings + + + + + + + + + +