ai*
This commit is contained in:
13
ai_mcp/tests/__init__.py
Normal file
13
ai_mcp/tests/__init__.py
Normal file
@@ -0,0 +1,13 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from . import common
|
||||
from . import oauth_common
|
||||
from . import test_mcp_access
|
||||
from . import test_mcp_controller
|
||||
from . import test_mcp_request_dispatching
|
||||
from . import test_oauth_client
|
||||
from . import test_oauth_metadata
|
||||
from . import test_dynamic_client_registration
|
||||
from . import test_cimd
|
||||
from . import test_auth_code_generation
|
||||
from . import test_access_token_generation
|
||||
from . import test_bearer_protected_route
|
||||
30
ai_mcp/tests/common.py
Normal file
30
ai_mcp/tests/common.py
Normal file
@@ -0,0 +1,30 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from odoo import SUPERUSER_ID
|
||||
|
||||
from odoo.addons.ai.tests.common import TestAICommon
|
||||
from odoo.addons.ai.utils.ai_utils import format_name_to_llm
|
||||
|
||||
|
||||
class TestMcpCommon(TestAICommon):
|
||||
|
||||
def _create_server_action_on_model(self, model_name, action_name=None, use_in_mcp=True, result=None, group_ids=None):
|
||||
model_id = self.env['ir.model'].sudo()._get_id(model_name)
|
||||
code = f"ai['result'] = {result}" if result else "ai['result'] = 'test action has been executed'"
|
||||
tool_name = action_name if action_name else f'MCP Test {model_name}'
|
||||
vals = {
|
||||
'name': tool_name,
|
||||
'ai_tool_name': format_name_to_llm(tool_name),
|
||||
'model_id': model_id,
|
||||
'state': 'code',
|
||||
'use_in_mcp': use_in_mcp,
|
||||
'code': code,
|
||||
}
|
||||
if group_ids:
|
||||
vals['group_ids'] = group_ids
|
||||
return self.env['ir.actions.server'].sudo().create(vals)
|
||||
|
||||
def _dispatch(self, method, params=None, sudo=False):
|
||||
env = self.env(user=SUPERUSER_ID) if sudo else self.env
|
||||
return env['ai.mcp.request.dispatcher']._mcp_dispatch(
|
||||
{'id': 1, 'method': method, 'params': params or {}}
|
||||
)
|
||||
69
ai_mcp/tests/oauth_common.py
Normal file
69
ai_mcp/tests/oauth_common.py
Normal file
@@ -0,0 +1,69 @@
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
|
||||
from odoo.tests import HttpCase, new_test_user
|
||||
|
||||
from odoo.addons.ai_mcp.utils.oauth_utils import challenge_from_verifier
|
||||
|
||||
REDIRECT_URI = 'https://client.example.com/callback'
|
||||
|
||||
|
||||
class OauthServerCommon(HttpCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
cls.internal_user = new_test_user(cls.env, login='internal_user', groups='base.group_user')
|
||||
cls.regular_user = new_test_user(
|
||||
cls.env, login='regular_user', groups='base.group_user,base.group_user_regular',
|
||||
)
|
||||
cls.portal_user = new_test_user(cls.env, login='portal_user', groups='base.group_portal')
|
||||
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
# Client registrations are rate limited per source IP within a time window. The whole test
|
||||
# run shares one registry and one source IP, so each test has to start from a clean budget.
|
||||
if hasattr(self.env.registry, '_dcr_registration_requests'):
|
||||
del self.env.registry._dcr_registration_requests
|
||||
|
||||
def _authorize(self, allow_redirects=True, **params_overrides):
|
||||
params = {
|
||||
'redirect_uri': REDIRECT_URI,
|
||||
'response_type': 'code',
|
||||
'code_challenge': challenge_from_verifier(self._get_verifier()),
|
||||
'code_challenge_method': 'S256',
|
||||
'state': 'xyz',
|
||||
**params_overrides,
|
||||
}
|
||||
return self.url_open('/oauth/authorize', params=params, allow_redirects=allow_redirects)
|
||||
|
||||
def _submit_consent(self, **params_overrides):
|
||||
params = {
|
||||
'redirect_uri': REDIRECT_URI,
|
||||
'response_type': 'code',
|
||||
'code_challenge': challenge_from_verifier(self._get_verifier()),
|
||||
'code_challenge_method': 'S256',
|
||||
'state': 'xyz',
|
||||
'allow': 'true',
|
||||
'csrf_token': self.csrf_token(),
|
||||
'duration': '1',
|
||||
**params_overrides,
|
||||
}
|
||||
return self.url_open('/oauth/authorize/submit_consent', data=params, allow_redirects=False)
|
||||
|
||||
def _generate_auth_code(self, **params_overrides):
|
||||
consent_response = self._submit_consent(**params_overrides)
|
||||
location = consent_response.headers['Location']
|
||||
return parse_qs(urlsplit(location).query)['code'][0]
|
||||
|
||||
def _generate_access_token(self, code, **params_overrides):
|
||||
params = {
|
||||
'redirect_uri': REDIRECT_URI,
|
||||
'code_verifier': self._get_verifier(),
|
||||
'code': code,
|
||||
'grant_type': 'authorization_code',
|
||||
**params_overrides,
|
||||
}
|
||||
return self.url_open('/oauth/token', data=params)
|
||||
|
||||
def _get_verifier(self):
|
||||
return 'a' * 64
|
||||
324
ai_mcp/tests/test_access_token_generation.py
Normal file
324
ai_mcp/tests/test_access_token_generation.py
Normal file
@@ -0,0 +1,324 @@
|
||||
from datetime import timedelta
|
||||
from unittest.mock import patch
|
||||
|
||||
from odoo import Command, fields
|
||||
from odoo.tests import new_test_user, tagged
|
||||
|
||||
from .oauth_common import REDIRECT_URI, OauthServerCommon
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestAccessTokenGeneration(OauthServerCommon):
|
||||
|
||||
def test_full_authorization_code_exchange_generates_access_token(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
response = self._generate_access_token(code, client_id=client_id)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
response_json = response.json()
|
||||
self.assertEqual(response_json['scope'], 'mcp')
|
||||
self.assertEqual(response_json['token_type'], 'Bearer')
|
||||
|
||||
self.assertEqual(self.env['res.users.apikeys']._check_credentials(scope='mcp', key=response_json['access_token']), self.internal_user.id)
|
||||
|
||||
def test_apikey_name_ignores_a_client_name_sent_by_the_client(self):
|
||||
"""A client must not be able to label its key with a name it did not register."""
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
self._generate_access_token(code, client_id=client_id, client_name='Microsoft Copilot (Verified)')
|
||||
self.assertEqual(
|
||||
self.env['res.users.apikeys'].search([('user_id', '=', self.internal_user.id), ('scope', '=', 'mcp')]).mapped('name'),
|
||||
['Test Client'],
|
||||
)
|
||||
|
||||
def test_access_token_is_not_valid_for_another_scope(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
access_token = self._generate_access_token(code, client_id=client_id).json()['access_token']
|
||||
|
||||
self.assertIsNone(self.env['res.users.apikeys']._check_credentials(scope='other_scope', key=access_token))
|
||||
|
||||
def test_missing_client_id_is_rejected(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
response = self._generate_access_token(code)
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertEqual(response.json()['error'], 'invalid_client')
|
||||
|
||||
def test_token_endpoint_rejects_an_unknown_client_id(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
token_result = {
|
||||
'access_token': 'access_token', 'token_type': 'Bearer', 'expires_in': 600, 'scope': 'mcp',
|
||||
}
|
||||
with patch(
|
||||
'odoo.addons.ai_mcp.models.oauth_authorization_code.OauthAuthorizationCode._redeem',
|
||||
return_value=token_result,
|
||||
) as redeem_mock:
|
||||
response = self._generate_access_token('authorization_code', client_id='unknown-client-id')
|
||||
self.assertEqual(response.status_code, 401, response.text)
|
||||
self.assertEqual(response.json()['error'], 'invalid_client')
|
||||
self.assertEqual(response.json()['error_description'], "Invalid client credentials")
|
||||
redeem_mock.assert_not_called()
|
||||
|
||||
response = self._generate_access_token('authorization_code', client_id=client_id)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
self.assertEqual(response.json(), token_result)
|
||||
redeem_mock.assert_called_once()
|
||||
|
||||
def test_wrong_code_verifier_is_rejected(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
response = self._generate_access_token(
|
||||
code, client_id=client_id, code_verifier='wrong-verifier',
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()['error'], 'invalid_grant')
|
||||
|
||||
def test_code_cannot_be_redeemed_twice(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
|
||||
first_redeem_response = self._generate_access_token(code, client_id=client_id)
|
||||
self.assertEqual(first_redeem_response.status_code, 200)
|
||||
self.assertIn('access_token', first_redeem_response.json())
|
||||
second_redeem_response = self._generate_access_token(code, client_id=client_id)
|
||||
self.assertEqual(second_redeem_response.status_code, 400)
|
||||
self.assertEqual(second_redeem_response.json()['error'], 'invalid_grant')
|
||||
|
||||
def test_redirect_uri_mismatch_at_token_is_rejected(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': f'{REDIRECT_URI}\nhttps://other.example.com/cb',
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id, redirect_uri=REDIRECT_URI)
|
||||
response = self._generate_access_token(
|
||||
code, client_id=client_id,
|
||||
redirect_uri='https://other.example.com/cb',
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()['error'], 'invalid_grant')
|
||||
|
||||
def test_loopback_redirect_uri_port_must_match_exactly_at_token(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': 'http://127.0.0.1:8080/cb'
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
|
||||
code = self._generate_auth_code(client_id=client_id, redirect_uri='http://127.0.0.1:54321/cb')
|
||||
response = self._generate_access_token(
|
||||
code, client_id=client_id,
|
||||
redirect_uri='http://127.0.0.1:9999/cb',
|
||||
)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()['error'], 'invalid_grant')
|
||||
|
||||
response = self._generate_access_token(
|
||||
code, client_id=client_id,
|
||||
redirect_uri='http://127.0.0.1:54321/cb',
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn('access_token', response.json())
|
||||
|
||||
def test_access_denied_at_redemption_if_the_user_is_no_longer_internal(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
self.internal_user.write({'group_ids': [Command.unlink(self.env.ref('base.group_user').id)]})
|
||||
|
||||
response = self._generate_access_token(code, client_id=client_id)
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()['error'], 'invalid_grant')
|
||||
self.assertEqual(response.json()['error_description'], 'Only internal users are allowed to use oauth for mcp')
|
||||
|
||||
def test_revoke_removes_the_access_token(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
access_token = self._generate_access_token(code, client_id=client_id).json()['access_token']
|
||||
|
||||
revoke_response = self.url_open('/oauth/revoke', data={'token': access_token})
|
||||
self.assertEqual(revoke_response.status_code, 200)
|
||||
self.assertFalse(self.env['res.users.apikeys'].search([('user_id', '=', self.internal_user.id), ('scope', '=', 'mcp')]))
|
||||
self.assertIsNone(self.env['res.users.apikeys']._check_credentials(scope='mcp', key=access_token))
|
||||
|
||||
def test_revoke_reports_success_for_an_unknown_token(self):
|
||||
# RFC 7009: the caller must not be able to tell an unknown token from a revoked one.
|
||||
response = self.url_open('/oauth/revoke', data={'token': 'some-token'})
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
self.assertEqual(response.json(), {})
|
||||
|
||||
def test_removing_the_apikey_rejects_the_access_token(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
access_token = self._generate_access_token(code, client_id=client_id).json()['access_token']
|
||||
|
||||
apikey = self.env['res.users.apikeys'].search([('user_id', '=', self.internal_user.id), ('scope', '=', 'mcp')])
|
||||
apikey._remove()
|
||||
|
||||
self.assertFalse(apikey.exists())
|
||||
self.assertIsNone(self.env['res.users.apikeys']._check_credentials(scope='mcp', key=access_token))
|
||||
|
||||
def test_single_client_can_generate_multiple_tokens_for_the_same_user(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
|
||||
first_code = self._generate_auth_code(client_id=client_id)
|
||||
first_token = self._generate_access_token(first_code, client_id=client_id).json()['access_token']
|
||||
second_code = self._generate_auth_code(client_id=client_id)
|
||||
second_token = self._generate_access_token(second_code, client_id=client_id).json()['access_token']
|
||||
|
||||
self.assertNotEqual(first_token, second_token)
|
||||
self.assertEqual(len(self.env['res.users.apikeys'].search([('user_id', '=', self.internal_user.id), ('scope', '=', 'mcp')])), 2)
|
||||
for access_token in (first_token, second_token):
|
||||
self.assertEqual(self.env['res.users.apikeys']._check_credentials(scope='mcp', key=access_token), self.internal_user.id)
|
||||
|
||||
def test_single_client_can_generate_tokens_for_several_users(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
other_user = new_test_user(self.env, login='other_internal_user', groups='base.group_user')
|
||||
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
first_user_token = self._generate_access_token(code, client_id=client_id).json()['access_token']
|
||||
|
||||
self.authenticate('other_internal_user', 'other_internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
other_user_token = self._generate_access_token(code, client_id=client_id).json()['access_token']
|
||||
|
||||
self.assertEqual(self.env['res.users.apikeys']._check_credentials(scope='mcp', key=first_user_token), self.internal_user.id)
|
||||
self.assertEqual(self.env['res.users.apikeys']._check_credentials(scope='mcp', key=other_user_token), other_user.id)
|
||||
|
||||
def test_authorization_code_of_inactive_user_is_rejected(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
|
||||
self.internal_user.active = False
|
||||
response = self._generate_access_token(code, client_id=client_id)
|
||||
self.assertEqual(response.status_code, 400, response.text)
|
||||
self.assertEqual(response.json()['error'], 'invalid_grant')
|
||||
self.assertFalse(self.env['res.users.apikeys'].search([('user_id', '=', self.internal_user.id), ('scope', '=', 'mcp')]))
|
||||
|
||||
self.internal_user.active = True
|
||||
response = self._generate_access_token(code, client_id=client_id)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
self.assertEqual(self.env['res.users.apikeys']._check_credentials(scope='mcp', key=response.json()['access_token']), self.internal_user.id)
|
||||
|
||||
def test_authorization_code_of_inactive_client_is_rejected(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
client = self.env['oauth.client'].search([('client_id', '=', client_id)])
|
||||
|
||||
client.action_archive()
|
||||
response = self._generate_access_token(code, client_id=client_id)
|
||||
self.assertEqual(response.status_code, 401, response.text)
|
||||
self.assertEqual(response.json()['error'], 'invalid_client')
|
||||
self.assertFalse(self.env['res.users.apikeys'].search([('user_id', '=', self.internal_user.id), ('scope', '=', 'mcp')]))
|
||||
|
||||
client.action_unarchive()
|
||||
response = self._generate_access_token(code, client_id=client_id)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
self.assertEqual(self.env['res.users.apikeys']._check_credentials(scope='mcp', key=response.json()['access_token']), self.internal_user.id)
|
||||
|
||||
def test_consented_duration_sets_the_apikey_expiration_date(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('regular_user', 'regular_user')
|
||||
|
||||
code = self._generate_auth_code(client_id=client_id, duration='7')
|
||||
response = self._generate_access_token(code, client_id=client_id)
|
||||
self.assertEqual(response.status_code, 200, response.text)
|
||||
|
||||
expected_expiration_date = fields.Datetime.to_datetime(fields.Date.today() + timedelta(days=7))
|
||||
self.assertEqual(
|
||||
self.env['res.users.apikeys'].search([('user_id', '=', self.regular_user.id), ('scope', '=', 'mcp')]).expiration_date,
|
||||
expected_expiration_date,
|
||||
)
|
||||
self.assertEqual(
|
||||
response.json()['expires_in'],
|
||||
(expected_expiration_date - fields.Datetime.now()).total_seconds(),
|
||||
)
|
||||
|
||||
def test_duration_beyond_the_user_privileges_is_rejected(self):
|
||||
# base.group_user_regular caps the API keys of a regular internal user at 90 days.
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('regular_user', 'regular_user')
|
||||
|
||||
response = self._submit_consent(client_id=client_id, duration='365')
|
||||
self.assertEqual(response.status_code, 400, response.text)
|
||||
self.assertEqual(response.json()['error'], 'authorization_failed')
|
||||
self.assertEqual(response.json()['error_description'], 'You cannot exceed 90.0 days.')
|
||||
|
||||
def test_duration_is_rechecked_when_the_code_is_redeemed(self):
|
||||
# The user consents to a year, then loses the privilege before the client redeems the code.
|
||||
self.env.ref('base.group_user').api_key_duration = 365
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id, duration='365')
|
||||
|
||||
self.env.ref('base.group_user').api_key_duration = 1
|
||||
response = self._generate_access_token(code, client_id=client_id)
|
||||
self.assertEqual(response.status_code, 400, response.text)
|
||||
self.assertEqual(response.json()['error'], 'invalid_grant')
|
||||
self.assertEqual(response.json()['error_description'], 'You cannot exceed 1.0 days.')
|
||||
self.assertFalse(self.env['res.users.apikeys'].search([('user_id', '=', self.internal_user.id), ('scope', '=', 'mcp')]))
|
||||
305
ai_mcp/tests/test_auth_code_generation.py
Normal file
305
ai_mcp/tests/test_auth_code_generation.py
Normal file
@@ -0,0 +1,305 @@
|
||||
import re
|
||||
from urllib.parse import parse_qs, urlsplit, unquote
|
||||
|
||||
from odoo.tests import tagged
|
||||
|
||||
from .oauth_common import REDIRECT_URI, OauthServerCommon
|
||||
from odoo.addons.ai_mcp.utils.oauth_utils import oauth_base_url
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestAuthCodeGeneration(OauthServerCommon):
|
||||
|
||||
def test_not_logged_in_user_is_redirected_to_login(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
response = self._authorize(client_id=client_id, allow_redirects=False)
|
||||
self.assertEqual(response.status_code, 303)
|
||||
self.assertIn('/web/login', response.headers['Location'])
|
||||
|
||||
def test_consent_screen_is_shown_and_not_frameable(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
response = self._authorize(client_id=client_id)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn(
|
||||
"<strong>Test Client</strong> is requesting access to your Odoo account for <strong>MCP (Model Context Protocol)</strong>",
|
||||
re.sub(r"\s+", " ", response.text)
|
||||
)
|
||||
self.assertEqual(response.headers.get('X-Frame-Options'), 'DENY')
|
||||
self.assertIn("frame-ancestors 'none'", response.headers.get('Content-Security-Policy', ''))
|
||||
|
||||
def test_consent_screen_ignores_a_client_name_sent_by_the_client(self):
|
||||
"""A client must not be able to present itself under a name it did not register."""
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
response = self._authorize(client_id=client_id, client_name='Microsoft Copilot (Verified)')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn(
|
||||
"<strong>Test Client</strong> is requesting access to your Odoo account for <strong>MCP (Model Context Protocol)</strong>",
|
||||
re.sub(r"\s+", " ", response.text)
|
||||
)
|
||||
self.assertNotIn('Microsoft Copilot', response.text)
|
||||
|
||||
def test_consent_screen_offers_the_durations_allowed_for_the_user(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('regular_user', 'regular_user')
|
||||
# base.group_user_regular caps API keys at 90 days, so a year is not offered.
|
||||
response = self._authorize(client_id=client_id)
|
||||
self.assertIn('id="oauth_duration_1" value="1"', response.text)
|
||||
self.assertIn('id="oauth_duration_30" value="30" checked', response.text)
|
||||
self.assertNotIn('value="365"', response.text)
|
||||
self.assertNotIn('value="0"', response.text)
|
||||
|
||||
self.env.ref('base.group_user_regular').api_key_duration = 1
|
||||
response = self._authorize(client_id=client_id)
|
||||
self.assertIn('id="oauth_duration_1" value="1" checked', response.text)
|
||||
self.assertNotIn('value="30"', response.text)
|
||||
self.assertNotIn('value="365"', response.text)
|
||||
self.assertNotIn('value="0"', response.text)
|
||||
|
||||
self.authenticate('admin', 'admin')
|
||||
response = self._authorize(client_id=client_id)
|
||||
self.assertIn('id="oauth_duration_1" value="1"', response.text)
|
||||
self.assertIn('id="oauth_duration_30" value="30" checked', response.text)
|
||||
self.assertIn('value="365"', response.text)
|
||||
self.assertIn('value="0"', response.text)
|
||||
|
||||
def test_consent_approval_issues_code_with_iss(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
|
||||
response = self._submit_consent(client_id=client_id)
|
||||
self.assertEqual(response.status_code, 303)
|
||||
location = unquote(response.headers['Location'])
|
||||
self.assertTrue(location.startswith(REDIRECT_URI))
|
||||
self.assertIn('code=', location)
|
||||
self.assertIn(f'iss={oauth_base_url(self.env)}/oauth/mcp', location)
|
||||
|
||||
def test_consent_screen_does_not_echo_the_decision_parameters(self):
|
||||
"""A malicious client must not be able to pre-fill the controls of the consent screen.
|
||||
|
||||
The attack this test asserts is not possible:
|
||||
1. The attacker sends the user an authorization request that already carries the
|
||||
parameters of the consent screen: /oauth/authorize?...&allow=true&duration=0
|
||||
2. The consent screen echoes them back as hidden inputs, which sit in the form before
|
||||
the Allow/Deny buttons, so submitting it sends allow=true and then the clicked value.
|
||||
3. Werkzeug keeps the first value of a duplicated field, so allow=true wins: clicking
|
||||
Deny hands the attacker an authorization code anyway.
|
||||
The same can be done with passing duration=0 which makes the API
|
||||
key behind that code never expire.
|
||||
"""
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
response = self._authorize(
|
||||
client_id=client_id,
|
||||
allow='true',
|
||||
duration='0',
|
||||
csrf_token='forged',
|
||||
)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
hidden_inputs = dict(re.findall(r'<input type="hidden" name="([^"]+)"[^>]*value="([^"]*)"', response.text))
|
||||
self.assertNotIn('allow', hidden_inputs)
|
||||
self.assertNotIn('duration', hidden_inputs)
|
||||
self.assertNotEqual(hidden_inputs['csrf_token'], 'forged')
|
||||
|
||||
def test_consent_denial_redirects_with_access_denied(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
response = self._submit_consent(client_id=client_id, allow='false')
|
||||
self.assertIn('error=access_denied', response.headers['Location'])
|
||||
|
||||
def test_arbitrary_requested_scope_is_ignored(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
response = self._submit_consent(client_id=client_id, scope='read delete_everything')
|
||||
self.assertEqual(response.status_code, 303)
|
||||
|
||||
auth_code = self.env['oauth.authorization.code']._retrieve_record(
|
||||
code=parse_qs(urlsplit(response.headers['Location']).query)['code'][0],
|
||||
client_id=client_id,
|
||||
redirect_uri=REDIRECT_URI,
|
||||
)
|
||||
self.assertTrue(auth_code)
|
||||
|
||||
def test_non_internal_user_is_not_shown_the_consent_screen(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('portal_user', 'portal_user')
|
||||
response = self._authorize(client_id=client_id)
|
||||
self.assertEqual(response.status_code, 400, response.text)
|
||||
|
||||
response_json = response.json()
|
||||
self.assertEqual(response_json['error'], 'authorization_failed')
|
||||
self.assertEqual(response_json['error_description'], "Only internal users are allowed to use oauth for mcp")
|
||||
|
||||
def test_user_access_is_rechecked_when_the_consent_is_submitted(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
# internal_user is allowed, so authorize renders the consent screen.
|
||||
response = self._authorize(client_id=client_id)
|
||||
self.assertIn(
|
||||
"<strong>Test Client</strong> is requesting access to your Odoo account for <strong>MCP (Model Context Protocol)</strong>",
|
||||
re.sub(r"\s+", " ", response.text)
|
||||
)
|
||||
|
||||
self.authenticate('portal_user', 'portal_user')
|
||||
response = self._submit_consent(client_id=client_id)
|
||||
self.assertEqual(response.status_code, 400, response.text)
|
||||
response_json = response.json()
|
||||
self.assertEqual(response_json['error'], 'authorization_failed')
|
||||
self.assertEqual(response_json['error_description'], "Only internal users are allowed to use oauth for mcp")
|
||||
|
||||
client = self.env['oauth.client'].search([('client_id', '=', client_id)])
|
||||
self.assertFalse(self.env['oauth.authorization.code'].search([('client_id', '=', client.client_id)]))
|
||||
|
||||
def test_loopback_redirect_uri_matches_regardless_of_port(self):
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': 'http://127.0.0.1:8080/cb'
|
||||
}).client_id
|
||||
response = self._authorize(client_id=client_id, redirect_uri='http://127.0.0.1:54321/cb')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn(
|
||||
'name="redirect_uri" value="http://127.0.0.1:54321/cb"',
|
||||
response.text
|
||||
)
|
||||
|
||||
def test_localhost_redirect_uri_is_normalized_to_ip(self):
|
||||
""""localhost" resolution can be hijacked (DNS rebinding, hosts file) as per RFC 8252 §8.3.
|
||||
So it is substituted with 127.0.0.1.
|
||||
"""
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
client = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': 'http://localhost:8080/cb'
|
||||
})
|
||||
|
||||
response = self._authorize(client_id=client.client_id, redirect_uri='http://localhost:54321/cb')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
# redirect_uri param of the authorize request is normalized to use 127.0.0.1 instead of localhost
|
||||
self.assertIn(
|
||||
'name="redirect_uri" value="http://127.0.0.1:54321/cb"',
|
||||
response.text
|
||||
)
|
||||
|
||||
consent_response = self._submit_consent(client_id=client.client_id, redirect_uri='http://localhost:54321/cb')
|
||||
self.assertEqual(consent_response.status_code, 303)
|
||||
self.assertTrue(consent_response.headers['Location'].startswith('http://127.0.0.1:54321/cb?'))
|
||||
|
||||
authorization_code = self.env['oauth.authorization.code'].search([('client_id', '=', client.client_id)])
|
||||
self.assertEqual(authorization_code.redirect_uri, 'http://127.0.0.1:54321/cb')
|
||||
|
||||
def test_loopback_redirect_uri_path_mismatch_rejection(self):
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': 'http://127.0.0.1:8080/cb'
|
||||
}).client_id
|
||||
response = self._authorize(client_id=client_id, redirect_uri='http://127.0.0.1:54321/other')
|
||||
self.assertEqual(response.status_code, 400)
|
||||
|
||||
response_json = response.json()
|
||||
self.assertEqual(response_json['error'], 'authorization_failed')
|
||||
self.assertEqual(response_json['error_description'], "redirect_uri is not registered for this client")
|
||||
|
||||
def test_loopback_redirect_uri_query_mismatch_rejection(self):
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': 'http://127.0.0.1:8080/cb'
|
||||
}).client_id
|
||||
response = self._authorize(client_id=client_id, redirect_uri='http://127.0.0.1:8080/cb?injected=1')
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()['error_description'], "redirect_uri is not registered for this client")
|
||||
|
||||
def test_redirect_uri_with_fragment_is_rejected(self):
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': 'http://127.0.0.1:8080/cb'
|
||||
}).client_id
|
||||
response = self._authorize(client_id=client_id, redirect_uri='http://127.0.0.1:8080/cb#fragment')
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertEqual(response.json()['error_description'], "redirect_uri is not registered for this client")
|
||||
|
||||
def test_auth_code_is_appended_to_query_params(self):
|
||||
"""A redirect_uri may already carry query params, which must stay intact"""
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
redirect_uri = 'https://client.example.com/cb?tenant=acme'
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': redirect_uri
|
||||
}).client_id
|
||||
|
||||
for allow, expected_param in [('true', 'code='), ('false', 'error=access_denied')]:
|
||||
with self.subTest(allow=allow):
|
||||
response = self._submit_consent(client_id=client_id, redirect_uri=redirect_uri, allow=allow)
|
||||
location = response.headers['Location']
|
||||
self.assertEqual(location.count('?'), 1)
|
||||
self.assertIn('tenant=acme', location)
|
||||
self.assertIn(expected_param, location)
|
||||
|
||||
def test_unregistered_redirect_uri_is_rejected(self):
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
response = self._authorize(client_id=client_id, redirect_uri='https://evil.example.com/callback')
|
||||
self.assertEqual(response.status_code, 400)
|
||||
|
||||
response_json = response.json()
|
||||
self.assertEqual(response_json['error'], 'authorization_failed')
|
||||
self.assertEqual(response_json['error_description'], "redirect_uri is not registered for this client")
|
||||
|
||||
def test_inactive_client_cannot_generate_an_auth_code(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
client = self.env['oauth.client'].search([('client_id', '=', client_id)])
|
||||
client.action_archive()
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
|
||||
authorize_response = self._authorize(client_id=client_id)
|
||||
self.assertEqual(authorize_response.status_code, 401, authorize_response.text)
|
||||
self.assertEqual(authorize_response.json()['error'], 'invalid_client')
|
||||
self.assertEqual(authorize_response.json()['error_description'], "Invalid client credentials")
|
||||
|
||||
# An archived client can't generate a code from a consent screen rendered before it was archived.
|
||||
consent_response = self._submit_consent(client_id=client_id)
|
||||
self.assertEqual(consent_response.status_code, 401, consent_response.text)
|
||||
self.assertEqual(consent_response.json()['error'], "invalid_client")
|
||||
self.assertEqual(authorize_response.json()['error_description'], "Invalid client credentials")
|
||||
self.assertFalse(self.env['oauth.authorization.code'].search([('client_id', '=', client.client_id)]))
|
||||
36
ai_mcp/tests/test_bearer_protected_route.py
Normal file
36
ai_mcp/tests/test_bearer_protected_route.py
Normal file
@@ -0,0 +1,36 @@
|
||||
import json
|
||||
|
||||
from odoo.tests import tagged
|
||||
|
||||
from odoo.addons.ai_mcp.tests.oauth_common import REDIRECT_URI, OauthServerCommon
|
||||
from odoo.addons.ai_mcp.utils.oauth_utils import oauth_base_url
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestBearerProtectedRoute(OauthServerCommon):
|
||||
|
||||
def test_missing_bearer_token_is_rejected_with_resource_metadata_hint(self):
|
||||
response = self.url_open('/mcp', data='{}')
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertEqual(
|
||||
response.headers.get('WWW-Authenticate'),
|
||||
f'Bearer resource_metadata="{oauth_base_url(self.env)}/.well-known/oauth-protected-resource/mcp"',
|
||||
)
|
||||
|
||||
def test_access_token_of_inactive_user_is_rejected_on_a_bearer_protected_route(self):
|
||||
client_id = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': REDIRECT_URI
|
||||
}).client_id
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
code = self._generate_auth_code(client_id=client_id)
|
||||
access_token = self._generate_access_token(
|
||||
code, client_id=client_id,
|
||||
).json()['access_token']
|
||||
self.authenticate(None, None)
|
||||
mcp_ping = json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': 'ping'})
|
||||
bearer_headers = {'Authorization': f'Bearer {access_token}', 'Content-Type': 'application/json'}
|
||||
self.assertEqual(self.url_open('/mcp', data=mcp_ping, headers=bearer_headers).status_code, 200)
|
||||
|
||||
self.internal_user.active = False
|
||||
self.assertEqual(self.url_open('/mcp', data=mcp_ping, headers=bearer_headers).status_code, 401)
|
||||
144
ai_mcp/tests/test_cimd.py
Normal file
144
ai_mcp/tests/test_cimd.py
Normal file
@@ -0,0 +1,144 @@
|
||||
import json
|
||||
from contextlib import contextmanager
|
||||
from unittest.mock import Mock, patch
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
from odoo.tests import tagged
|
||||
|
||||
from .oauth_common import REDIRECT_URI, OauthServerCommon
|
||||
|
||||
CIMD_CLIENT_ID = 'https://client.example.com/oauth/client.json'
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestClientIdMetadataDocument(OauthServerCommon):
|
||||
|
||||
def _cimd_document(self, **overrides):
|
||||
return {
|
||||
'client_id': CIMD_CLIENT_ID,
|
||||
'client_name': 'CIMD Test Client',
|
||||
'redirect_uris': [REDIRECT_URI],
|
||||
'token_endpoint_auth_method': 'none',
|
||||
**overrides,
|
||||
}
|
||||
|
||||
@contextmanager
|
||||
def _mock_cimd_fetch(self, document=None):
|
||||
# Only the network call is mocked, the document is still validated by the server.
|
||||
response = Mock(status_code=200)
|
||||
response.raw.read.return_value = json.dumps(self._cimd_document() if document is None else document).encode()
|
||||
with patch('odoo.addons.ai_mcp.utils.oauth_utils.requests.get', return_value=response) as mocked_get:
|
||||
yield mocked_get
|
||||
|
||||
def test_authorization_server_metadata_advertises_cimd(self):
|
||||
metadata = self.url_open('/.well-known/oauth-authorization-server/oauth/mcp').json()
|
||||
self.assertTrue(metadata['client_id_metadata_document_supported'])
|
||||
self.assertTrue(metadata['authorization_response_iss_parameter_supported'])
|
||||
|
||||
def test_allowed_cimd_clients(self):
|
||||
self.env['ir.config_parameter'].sudo().set_str('cimd_allowed_urls', CIMD_CLIENT_ID)
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
with self._mock_cimd_fetch():
|
||||
response = self._authorize(client_id=CIMD_CLIENT_ID)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
# Everything shown about the client comes from the document, nothing is registered locally.
|
||||
self.assertIn('CIMD Test Client', response.text)
|
||||
self.assertFalse(self.env['oauth.client'].sudo().search([('client_id', '=', CIMD_CLIENT_ID)]))
|
||||
|
||||
with self._mock_cimd_fetch() as mocked_get:
|
||||
response = self._authorize(client_id="https://www.example.com")
|
||||
mocked_get.assert_not_called()
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertEqual(response.json()['error'], 'invalid_client')
|
||||
self.assertIn("CIMD URL https://www.example.com isn't allowed", response.json()['error_description'])
|
||||
|
||||
def test_removing_the_url_from_the_allow_list_revokes_the_client(self):
|
||||
self.env['ir.config_parameter'].sudo().set_str('cimd_allowed_urls', CIMD_CLIENT_ID)
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
with self._mock_cimd_fetch():
|
||||
response = self._authorize(client_id=CIMD_CLIENT_ID)
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
self.env['ir.config_parameter'].sudo().set_str('cimd_allowed_urls', '')
|
||||
with self._mock_cimd_fetch():
|
||||
response = self._authorize(client_id=CIMD_CLIENT_ID)
|
||||
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertIn(f"CIMD URL {CIMD_CLIENT_ID} isn't allowed", response.json()['error_description'])
|
||||
|
||||
def test_document_client_id_must_match_the_url_it_was_fetched_from(self):
|
||||
self.env['ir.config_parameter'].sudo().set_str('cimd_allowed_urls', CIMD_CLIENT_ID)
|
||||
document = self._cimd_document(client_id='https://client.example.com/oauth/other.json')
|
||||
with self._mock_cimd_fetch(document):
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
response = self._authorize(client_id=CIMD_CLIENT_ID)
|
||||
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertIn(f'The client_id of the metadata document does not match the URL {CIMD_CLIENT_ID} it was fetched from.', response.json()['error_description'])
|
||||
|
||||
def test_a_client_supporting_none_among_other_auth_methods_is_accepted(self):
|
||||
self.env['ir.config_parameter'].sudo().set_str('cimd_allowed_urls', CIMD_CLIENT_ID)
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
document = self._cimd_document(
|
||||
token_endpoint_auth_method='private_key_jwt',
|
||||
token_endpoint_auth_methods_supported=['none', 'private_key_jwt'],
|
||||
)
|
||||
with self._mock_cimd_fetch(document):
|
||||
response = self._authorize(client_id=CIMD_CLIENT_ID)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertIn('CIMD Test Client', response.text)
|
||||
|
||||
def test_a_client_that_does_not_support_none_is_refused(self):
|
||||
self.env['ir.config_parameter'].sudo().set_str('cimd_allowed_urls', CIMD_CLIENT_ID)
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
document = self._cimd_document(
|
||||
token_endpoint_auth_method='private_key_jwt',
|
||||
token_endpoint_auth_methods_supported=['private_key_jwt'],
|
||||
)
|
||||
with self._mock_cimd_fetch(document):
|
||||
response = self._authorize(client_id=CIMD_CLIENT_ID)
|
||||
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertIn('Unsupported token_endpoint_auth_method', response.json()['error_description'])
|
||||
|
||||
def test_redirect_uri_must_be_listed_in_the_document(self):
|
||||
self.env['ir.config_parameter'].sudo().set_str('cimd_allowed_urls', CIMD_CLIENT_ID)
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
with self._mock_cimd_fetch():
|
||||
response = self._authorize(client_id=CIMD_CLIENT_ID, redirect_uri='https://client.example.com/other-callback')
|
||||
|
||||
self.assertEqual(response.status_code, 400)
|
||||
self.assertIn('redirect_uri is not registered', response.json()['error_description'])
|
||||
|
||||
def test_the_submit_consent_endpoint_refuses_a_client_that_is_not_on_the_allow_list(self):
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
with self._mock_cimd_fetch():
|
||||
response = self._submit_consent(client_id=CIMD_CLIENT_ID)
|
||||
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertIn(f"CIMD URL {CIMD_CLIENT_ID} isn't allowed", response.json()['error_description'])
|
||||
|
||||
def test_full_cimd_authorization_code_exchange_generates_an_access_token(self):
|
||||
self.env['ir.config_parameter'].sudo().set_str('cimd_allowed_urls', CIMD_CLIENT_ID)
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
with self._mock_cimd_fetch():
|
||||
consent_response = self._submit_consent(client_id=CIMD_CLIENT_ID)
|
||||
code = parse_qs(urlsplit(consent_response.headers['Location']).query)['code'][0]
|
||||
response = self._generate_access_token(code, client_id=CIMD_CLIENT_ID)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertTrue(response.json()['access_token'])
|
||||
self.assertEqual(response.json()['scope'], 'mcp')
|
||||
|
||||
def test_the_token_endpoint_refuses_a_client_that_is_not_on_the_allow_list(self):
|
||||
self.env['ir.config_parameter'].sudo().set_str('cimd_allowed_urls', CIMD_CLIENT_ID)
|
||||
self.authenticate('internal_user', 'internal_user')
|
||||
with self._mock_cimd_fetch():
|
||||
code = self._generate_auth_code(client_id=CIMD_CLIENT_ID)
|
||||
|
||||
self.env['ir.config_parameter'].sudo().set_str('cimd_allowed_urls', '')
|
||||
response = self._generate_access_token(code, client_id=CIMD_CLIENT_ID)
|
||||
|
||||
self.assertEqual(response.status_code, 401)
|
||||
self.assertIn(f"CIMD URL {CIMD_CLIENT_ID} isn't allowed", response.json()['error_description'])
|
||||
118
ai_mcp/tests/test_dynamic_client_registration.py
Normal file
118
ai_mcp/tests/test_dynamic_client_registration.py
Normal file
@@ -0,0 +1,118 @@
|
||||
import json
|
||||
from unittest.mock import patch
|
||||
|
||||
from odoo.tests import tagged
|
||||
|
||||
from .oauth_common import REDIRECT_URI, OauthServerCommon
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestDynamicClientRegistration(OauthServerCommon):
|
||||
|
||||
def _register_client_dynamically(self, redirect_uris=(REDIRECT_URI,), auth_method='none'):
|
||||
params = {
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': list(redirect_uris),
|
||||
}
|
||||
if auth_method:
|
||||
params['token_endpoint_auth_method'] = auth_method
|
||||
response = self.url_open(
|
||||
'/oauth/register/mcp',
|
||||
data=json.dumps(params),
|
||||
headers={'Content-Type': 'application/json'}
|
||||
)
|
||||
return response.json()
|
||||
|
||||
def _enable_dcr(self):
|
||||
self.env['ir.config_parameter'].sudo().set_bool('enable_dcr', True)
|
||||
|
||||
def _disable_dcr(self):
|
||||
self.env['ir.config_parameter'].sudo().set_bool('enable_dcr', False)
|
||||
|
||||
def _get_authorization_server_metadata(self):
|
||||
with patch(
|
||||
'odoo.addons.ai_mcp.controllers.oauth_server_controller.oauth_base_url',
|
||||
return_value='https://oauth.example.com'
|
||||
):
|
||||
response = self.url_open('/.well-known/oauth-authorization-server/oauth/mcp')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
return response.json()
|
||||
|
||||
def test_authorization_server_metadata_advertises_the_registration_endpoint(self):
|
||||
self._enable_dcr()
|
||||
metadata = self._get_authorization_server_metadata()
|
||||
self.assertEqual(
|
||||
metadata['registration_endpoint'],
|
||||
'https://oauth.example.com/oauth/register/mcp',
|
||||
)
|
||||
|
||||
def test_authorization_server_metadata_hides_the_registration_endpoint_when_dcr_is_disabled(self):
|
||||
self._disable_dcr()
|
||||
metadata = self._get_authorization_server_metadata()
|
||||
|
||||
self.assertNotIn('registration_endpoint', metadata)
|
||||
self.assertTrue(metadata['client_id_metadata_document_supported'])
|
||||
|
||||
def test_registration_is_refused_when_dcr_is_disabled(self):
|
||||
self._disable_dcr()
|
||||
response = self.url_open(
|
||||
'/oauth/register/mcp',
|
||||
data=json.dumps({'client_name': 'Test Client', 'redirect_uris': [REDIRECT_URI]}),
|
||||
headers={'Content-Type': 'application/json'},
|
||||
)
|
||||
|
||||
self.assertEqual(response.status_code, 403)
|
||||
self.assertEqual(response.json()['error'], 'access_denied')
|
||||
self.assertEqual(response.json()['error_description'], 'Dynamic client registration is disabled on this server.')
|
||||
self.assertFalse(self.env['oauth.client'].search([('client_name', '=', 'Test Client')]))
|
||||
|
||||
self._enable_dcr()
|
||||
self.assertIn('client_id', self._register_client_dynamically())
|
||||
|
||||
def test_client_registration(self):
|
||||
self._enable_dcr()
|
||||
# token_endpoint_auth_method defaults to "none" when it is missing.
|
||||
response = self._register_client_dynamically(auth_method=None)
|
||||
self.assertTrue(response['client_id'])
|
||||
self.assertEqual(response['token_endpoint_auth_method'], 'none')
|
||||
|
||||
response = self._register_client_dynamically(auth_method='none')
|
||||
self.assertTrue(response['client_id'])
|
||||
self.assertEqual(response['token_endpoint_auth_method'], 'none')
|
||||
|
||||
for auth_method in ('client_secret_post', 'client_secret_basic', 'private_key_jwt'):
|
||||
response = self._register_client_dynamically(auth_method=auth_method)
|
||||
self.assertEqual(response['error'], 'invalid_client_metadata')
|
||||
self.assertEqual(
|
||||
response['error_description'],
|
||||
f'Unsupported token_endpoint_auth_method {auth_method}',
|
||||
)
|
||||
|
||||
def test_register_allows_https_or_loopback_only_http_redirect_uri(self):
|
||||
self._enable_dcr()
|
||||
response = self._register_client_dynamically(redirect_uris=["https://www.example.com:8080/cb"])
|
||||
self.assertNotIn('error', response)
|
||||
self.assertIn('client_id', response)
|
||||
|
||||
response = self._register_client_dynamically(["http://localhost:8080/cb"])
|
||||
self.assertNotIn('error', response)
|
||||
self.assertIn('client_id', response)
|
||||
|
||||
response = self._register_client_dynamically(["https://www.example.com:1234/cb", "http://localhost:8080/cb"])
|
||||
self.assertNotIn('error', response)
|
||||
self.assertIn('client_id', response)
|
||||
|
||||
response = self._register_client_dynamically(redirect_uris=["http://127.0.0.1:8080/cb"])
|
||||
self.assertNotIn('error', response)
|
||||
self.assertIn('client_id', response)
|
||||
|
||||
response = self._register_client_dynamically(redirect_uris=[])
|
||||
self.assertEqual(response['error'], "invalid_client_metadata")
|
||||
|
||||
response = self._register_client_dynamically(redirect_uris=["http://client.example.com/callback"])
|
||||
self.assertEqual(response['error'], 'invalid_client_metadata')
|
||||
|
||||
def test_register_rejects_redirect_uri_with_fragment(self):
|
||||
self._enable_dcr()
|
||||
response = self._register_client_dynamically(redirect_uris=["https://client.example.com/cb#fragment"])
|
||||
self.assertEqual(response['error'], 'invalid_client_metadata')
|
||||
236
ai_mcp/tests/test_mcp_access.py
Normal file
236
ai_mcp/tests/test_mcp_access.py
Normal file
@@ -0,0 +1,236 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
import re
|
||||
|
||||
from odoo.tests import tagged, users
|
||||
from odoo.tools import mute_logger
|
||||
from odoo.exceptions import AccessError
|
||||
|
||||
from odoo.addons.ai_mcp.tests.common import TestMcpCommon
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestMcpAccess(TestMcpCommon):
|
||||
|
||||
@users('user_internal')
|
||||
def test_create_record_on_accessible_model(self):
|
||||
create_records_tool = self.env.ref('ai.ir_actions_server_create_records').sudo()
|
||||
create_records_tool.use_in_mcp = True
|
||||
result = self._dispatch('tools/call', {
|
||||
'name': create_records_tool.ai_tool_name,
|
||||
'arguments': {
|
||||
'explanation': 'Creating a test discuss channel',
|
||||
'model_name': 'discuss.channel',
|
||||
'values': [{'field_values': [{'field': 'name', 'value': 'Test Discuss Channel'}]}],
|
||||
},
|
||||
})
|
||||
self.assertFalse(result['isError'])
|
||||
channel = self.env['discuss.channel'].search([('name', '=', 'Test Discuss Channel')])
|
||||
self.assertEqual(len(channel), 1)
|
||||
|
||||
@users('user_internal')
|
||||
def test_create_record_on_inaccessible_model(self):
|
||||
create_records_tool = self.env.ref('ai.ir_actions_server_create_records').sudo()
|
||||
create_records_tool.use_in_mcp = True
|
||||
with self.assertRaisesRegex(AccessError, "You are not allowed to create 'AI Session'"):
|
||||
self._dispatch('tools/call', {
|
||||
'name': create_records_tool.ai_tool_name,
|
||||
'arguments': {
|
||||
'explanation': 'Trying to create on restricted model',
|
||||
'model_name': 'ai.session',
|
||||
'values': [{'field_values': [{'field': 'agent_id', 'value': self.agent.id}]}],
|
||||
},
|
||||
})
|
||||
|
||||
@users('user_internal')
|
||||
def test_update_accessible_model_record(self):
|
||||
update_records_tool = self.env.ref('ai.ir_actions_server_update_records').sudo()
|
||||
update_records_tool.use_in_mcp = True
|
||||
channel = self.env['discuss.channel'].create({'name': 'Test Discuss Channel'})
|
||||
result = self._dispatch('tools/call', {
|
||||
'name': update_records_tool.ai_tool_name,
|
||||
'arguments': {
|
||||
'explanation': 'Trying to update discuss.channel model',
|
||||
'preview_menus': [],
|
||||
'updates': [{
|
||||
'model_name': 'discuss.channel',
|
||||
'domain': f"[('id', '=', {channel.id})]",
|
||||
'changes': [{'field': 'name', 'value': 'Updated'}],
|
||||
}],
|
||||
},
|
||||
})
|
||||
self.assertFalse(result['isError'])
|
||||
self.assertEqual(channel.name, 'Updated')
|
||||
|
||||
@users('user_internal')
|
||||
def test_update_inaccessible_model_record(self):
|
||||
update_records_tool = self.env.ref('ai.ir_actions_server_update_records').sudo()
|
||||
update_records_tool.use_in_mcp = True
|
||||
session = self.env['ai.session'].sudo().create({'agent_id': self.agent.id})
|
||||
with self.assertRaisesRegex(AccessError, re.escape("You are not allowed to access 'AI Session' (ai.session)")):
|
||||
self._dispatch('tools/call', {
|
||||
'name': update_records_tool.ai_tool_name,
|
||||
'arguments': {
|
||||
'explanation': 'Trying to update restricted model',
|
||||
'preview_menus': [],
|
||||
'updates': [{
|
||||
'model_name': 'ai.session',
|
||||
'domain': f"[('id', '=', {session.id})]",
|
||||
'changes': [{'field': 'state', 'value': '{}'}],
|
||||
}],
|
||||
},
|
||||
})
|
||||
|
||||
@users('user_internal')
|
||||
def test_get_models_includes_only_accessible_models(self):
|
||||
tool_name = self.env.ref('ai.ir_actions_server_get_models').sudo().ai_tool_name
|
||||
result = self._dispatch('tools/call', {'name': tool_name, 'arguments': {}})
|
||||
self.assertFalse(result['isError'])
|
||||
models_csv = result['content'][0]['text']
|
||||
self.assertIn('res.partner', models_csv)
|
||||
self.assertIn('res.partner.category', models_csv)
|
||||
self.assertIn('discuss.channel', models_csv)
|
||||
self.assertNotIn('ai.session', models_csv)
|
||||
|
||||
sudo_result = self._dispatch('tools/call', {'name': tool_name, 'arguments': {}}, sudo=True)
|
||||
self.assertFalse(sudo_result['isError'])
|
||||
models_csv = sudo_result['content'][0]['text']
|
||||
self.assertIn('res.partner', models_csv)
|
||||
self.assertIn('res.partner.category', models_csv)
|
||||
self.assertIn('discuss.channel', models_csv)
|
||||
self.assertIn('ai.session', models_csv)
|
||||
|
||||
@users('user_internal')
|
||||
def test_get_accessible_model_fields(self):
|
||||
tool_name = self.env.ref('ai.ir_actions_server_get_fields').sudo().ai_tool_name
|
||||
result = self._dispatch('tools/call', {'name': tool_name, 'arguments': {'model_name': 'res.partner'}})
|
||||
self.assertFalse(result['isError'])
|
||||
self.assertIn('name', result['content'][0]['text'])
|
||||
|
||||
@users('user_internal')
|
||||
def test_get_inaccessible_model_fields(self):
|
||||
tool_name = self.env.ref('ai.ir_actions_server_get_fields').sudo().ai_tool_name
|
||||
with self.assertRaisesRegex(AccessError, re.escape("You are not allowed to access 'AI Session' (ai.session)")):
|
||||
self._dispatch('tools/call', {'name': tool_name, 'arguments': {'model_name': 'ai.session'}})
|
||||
|
||||
@users('user_internal')
|
||||
def test_get_fields_includes_only_accessible_fields(self):
|
||||
tool_name = self.env.ref('ai.ir_actions_server_get_fields').sudo().ai_tool_name
|
||||
result = self._dispatch('tools/call', {'name': tool_name, 'arguments': {'model_name': 'discuss.channel'}})
|
||||
self.assertFalse(result['isError'])
|
||||
fields_csv = result['content'][0]['text']
|
||||
self.assertIn('name', fields_csv)
|
||||
self.assertNotIn('sfu_channel_uuid', fields_csv)
|
||||
self.assertNotIn('sfu_server_url', fields_csv)
|
||||
|
||||
sudo_result = self._dispatch('tools/call', {'name': tool_name, 'arguments': {'model_name': 'discuss.channel'}}, sudo=True)
|
||||
self.assertFalse(sudo_result['isError'])
|
||||
fields_csv = sudo_result['content'][0]['text']
|
||||
self.assertIn('name', fields_csv)
|
||||
self.assertIn('sfu_channel_uuid', fields_csv)
|
||||
self.assertIn('sfu_server_url', fields_csv)
|
||||
|
||||
@users('user_internal')
|
||||
def test_search_on_accessible_model(self):
|
||||
self.env['res.partner'].sudo().create({'name': 'name of mcp test partner'})
|
||||
tool_name = self.env.ref('ai.ir_actions_server_search').sudo().ai_tool_name
|
||||
result = self._dispatch('tools/call', {
|
||||
'name': tool_name,
|
||||
'arguments': {'model_name': 'res.partner', 'domain': "[('name', '=', 'name of mcp test partner')]", 'fields': ['name']},
|
||||
})
|
||||
self.assertFalse(result['isError'])
|
||||
self.assertIn('name of mcp test partner', result['content'][0]['text'])
|
||||
|
||||
@users('user_internal')
|
||||
def test_search_on_inaccessible_model(self):
|
||||
tool_name = self.env.ref('ai.ir_actions_server_search').sudo().ai_tool_name
|
||||
with self.assertRaisesRegex(ValueError, re.escape("The model 'ai.session' doesn't exist or is inaccessible to the current user")):
|
||||
self._dispatch('tools/call', {
|
||||
'name': tool_name,
|
||||
'arguments': {'model_name': 'ai.session', 'domain': "[]", 'fields': ['id']},
|
||||
})
|
||||
|
||||
@users('user_internal')
|
||||
def test_read_group_on_accessible_model(self):
|
||||
self.env['res.partner'].sudo().create([{'name': 'Alpha'}, {'name': 'Beta'}])
|
||||
tool_name = self.env.ref('ai.ir_actions_server_read_group').sudo().ai_tool_name
|
||||
result = self._dispatch('tools/call', {
|
||||
'name': tool_name,
|
||||
'arguments': {'model_name': 'res.partner', 'domain': "[]", 'groupby': ['name']},
|
||||
})
|
||||
self.assertFalse(result['isError'])
|
||||
self.assertIn('Alpha', result['content'][0]['text'])
|
||||
self.assertIn('Beta', result['content'][0]['text'])
|
||||
|
||||
@users('user_internal')
|
||||
def test_read_group_on_inaccessible_model(self):
|
||||
tool_name = self.env.ref('ai.ir_actions_server_read_group').sudo().ai_tool_name
|
||||
with self.assertRaisesRegex(ValueError, re.escape("The model 'ai.session' doesn't exist or is inaccessible to the current user")):
|
||||
self._dispatch('tools/call', {
|
||||
'name': tool_name,
|
||||
'arguments': {'model_name': 'ai.session', 'domain': "[]", 'groupby': ['agent_id']},
|
||||
})
|
||||
|
||||
@mute_logger('odoo.addons.base.models.ir_actions')
|
||||
@users('user_internal')
|
||||
def test_only_show_tools_defined_on_accessible_models(self):
|
||||
action = self._create_server_action_on_model('ai.session')
|
||||
tool_name = action.ai_tool_name
|
||||
self.assertNotIn(tool_name, [t['name'] for t in self._dispatch('tools/list')['tools']])
|
||||
self.assertIn(tool_name, [t['name'] for t in self._dispatch('tools/list', sudo=True)['tools']])
|
||||
|
||||
@mute_logger('odoo.addons.base.models.ir_actions')
|
||||
@users('user_internal')
|
||||
def test_server_action_visibility_requires_model_access(self):
|
||||
action = self._create_server_action_on_model('ai.session')
|
||||
tool_name = action.ai_tool_name
|
||||
|
||||
tool_names = [t['name'] for t in self._dispatch('tools/list')['tools']]
|
||||
self.assertNotIn(tool_name, tool_names)
|
||||
|
||||
with self.assertRaises(AccessError):
|
||||
self._dispatch('tools/call', {'name': tool_name})
|
||||
|
||||
tool_names_admin = [t['name'] for t in self._dispatch('tools/list', sudo=True)['tools']]
|
||||
self.assertIn(tool_name, tool_names_admin)
|
||||
|
||||
result = self._dispatch('tools/call', {'name': tool_name}, sudo=True)
|
||||
self.assertFalse(result['isError'])
|
||||
|
||||
@users('user_internal')
|
||||
def test_server_action_with_group_ids_requires_group_membership(self):
|
||||
# Scenario A: user_internal is in the action's group but has no write access to the model.
|
||||
# Group membership overrides model access — user should see and call the tool.
|
||||
mcp_test_group = self.env['res.groups'].sudo().create({'name': 'MCP Test Group With User'})
|
||||
mcp_test_group.write({'user_ids': [(4, self.env.user.id)]})
|
||||
action_group_accessible = self._create_server_action_on_model(
|
||||
'ai.session', action_name='MCP Group Accessible Action', group_ids=[(4, mcp_test_group.id)]
|
||||
)
|
||||
|
||||
tool_names = [t['name'] for t in self._dispatch('tools/list')['tools']]
|
||||
self.assertIn(action_group_accessible.ai_tool_name, tool_names)
|
||||
|
||||
result = self._dispatch('tools/call', {'name': action_group_accessible.ai_tool_name})
|
||||
self.assertFalse(result['isError'])
|
||||
|
||||
# Scenario B: user_internal has write access to the model but is NOT in the action's group.
|
||||
# Model access alone is not enough — group membership is required.
|
||||
group_without_user = self.env['res.groups'].sudo().create({'name': 'MCP Test Group Without User'})
|
||||
action_group_restricted = self._create_server_action_on_model(
|
||||
'res.partner', action_name='MCP Group Restricted Action', group_ids=[(4, group_without_user.id)]
|
||||
)
|
||||
|
||||
tool_names = [t['name'] for t in self._dispatch('tools/list')['tools']]
|
||||
self.assertNotIn(action_group_restricted.ai_tool_name, tool_names)
|
||||
|
||||
with self.assertRaises(AccessError):
|
||||
self._dispatch('tools/call', {'name': action_group_restricted.ai_tool_name})
|
||||
|
||||
@users('user_internal')
|
||||
def test_server_action_tool_in_list_tools_and_callable(self):
|
||||
action = self._create_server_action_on_model('res.partner')
|
||||
tool_name = action.ai_tool_name
|
||||
self.assertIn(tool_name, [t['name'] for t in self._dispatch('tools/list')['tools']])
|
||||
|
||||
result = self._dispatch('tools/call', {'name': tool_name})
|
||||
self.assertFalse(result['isError'])
|
||||
self.assertIn('test action has been executed', result['content'][0]['text'])
|
||||
70
ai_mcp/tests/test_mcp_controller.py
Normal file
70
ai_mcp/tests/test_mcp_controller.py
Normal file
@@ -0,0 +1,70 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from odoo.tests import HttpCase, tagged, users
|
||||
|
||||
from odoo.addons.ai_mcp.tests.common import TestMcpCommon
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestMcpController(TestMcpCommon, HttpCase):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
expiration = datetime.now() + timedelta(hours=12)
|
||||
cls.user_internal = cls.user_internal.with_user(cls.user_internal)
|
||||
cls.mcp_api_key = cls.user_internal.env['res.users.apikeys']._generate('mcp', 'test mcp key', expiration)
|
||||
|
||||
def _mcp_post(self, method, params=None):
|
||||
payload = {'id': 1, 'method': method, 'params': params or {}}
|
||||
response = self.url_open(
|
||||
'/mcp',
|
||||
data=json.dumps(payload),
|
||||
headers={
|
||||
'Authorization': f'Bearer {self.mcp_api_key}',
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
)
|
||||
return response
|
||||
|
||||
@users('user_internal')
|
||||
def test_rollback_on_exception(self):
|
||||
channel = self.env['discuss.channel'].create({'name': 'original_name'})
|
||||
update_records_action = self.env.ref('ai.ir_actions_server_update_records').sudo()
|
||||
update_records_action.use_in_mcp = True
|
||||
response = self._mcp_post('tools/call', {
|
||||
'name': update_records_action.ai_tool_name,
|
||||
'arguments': {
|
||||
'explanation': 'partial write rollback test',
|
||||
'preview_menus': [],
|
||||
'updates': [
|
||||
{
|
||||
'model_name': 'discuss.channel',
|
||||
'domain': f"[('id', '=', {channel.id})]",
|
||||
'changes': [{'field': 'name', 'value': 'SHOULD_BE_ROLLEDBACK'}],
|
||||
},
|
||||
{
|
||||
'model_name': 'discuss.channel',
|
||||
'domain': "[('id', '=', -999999)]",
|
||||
'changes': [{'field': 'name', 'value': 'SHOULD_NOT_APPLY'}],
|
||||
},
|
||||
],
|
||||
},
|
||||
})
|
||||
result = response.json()['result']
|
||||
self.assertTrue(result['isError'])
|
||||
self.assertIn("No records were found corresponding to the domain '[('id', '=', -999999)]", result['content'][0]['text'])
|
||||
self.assertEqual(channel.name, 'original_name')
|
||||
|
||||
@users('user_internal')
|
||||
def test_unknown_method_returns_jsonrpc_error(self):
|
||||
response = self._mcp_post('server/discover')
|
||||
body = response.json()
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertNotIn('result', body)
|
||||
self.assertEqual(body['id'], 1)
|
||||
self.assertEqual(body['error']['code'], -32601)
|
||||
self.assertEqual(body['error']['message'], "Method doesn't exist")
|
||||
self.assertEqual(body['error']['data']['method'], 'server/discover')
|
||||
31
ai_mcp/tests/test_mcp_request_dispatching.py
Normal file
31
ai_mcp/tests/test_mcp_request_dispatching.py
Normal file
@@ -0,0 +1,31 @@
|
||||
# Part of Odoo. See LICENSE file for full copyright and licensing details.
|
||||
from odoo.tests import tagged
|
||||
|
||||
from odoo.addons.ai_mcp.tests.common import TestMcpCommon
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestMcpRequestDispatching(TestMcpCommon):
|
||||
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
super().setUpClass()
|
||||
cls.create_tool_xmlid = 'ai.ir_actions_server_create_records'
|
||||
cls.update_tool_xmlid = 'ai.ir_actions_server_update_records'
|
||||
|
||||
def test_tools_with_use_in_mcp_are_registered(self):
|
||||
mcp_action = self._create_server_action_on_model('res.partner', action_name="mcp_action")
|
||||
non_mcp_action = self._create_server_action_on_model('res.partner', action_name="non_mcp_action", use_in_mcp=False)
|
||||
mcp_action_tool_name = mcp_action.ai_tool_name
|
||||
non_mcp_action_tool_name = non_mcp_action.ai_tool_name
|
||||
|
||||
tool_names = [t['name'] for t in self._dispatch('tools/list')['tools']]
|
||||
self.assertIn(mcp_action_tool_name, tool_names)
|
||||
self.assertNotIn(non_mcp_action_tool_name, tool_names)
|
||||
|
||||
result = self._dispatch('tools/call', {'name': mcp_action_tool_name})
|
||||
self.assertFalse(result['isError'])
|
||||
self.assertIn('test action has been executed', result['content'][0]['text'])
|
||||
|
||||
with self.assertRaisesRegex(ValueError, f"The tool '{non_mcp_action_tool_name}' doesn't exist"):
|
||||
self._dispatch('tools/call', {'name': non_mcp_action_tool_name})
|
||||
28
ai_mcp/tests/test_oauth_client.py
Normal file
28
ai_mcp/tests/test_oauth_client.py
Normal file
@@ -0,0 +1,28 @@
|
||||
from odoo.tests import tagged, TransactionCase
|
||||
from odoo.exceptions import UserError
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestOauthClient(TransactionCase):
|
||||
|
||||
def test_client_id_is_immutable(self):
|
||||
client = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': "https://client.example.com/callback",
|
||||
})
|
||||
|
||||
with self.assertRaises(UserError):
|
||||
client.client_id = 'new client id'
|
||||
|
||||
def test_localhost_redirect_uri_is_stored_as_an_ip(self):
|
||||
client = self.env['oauth.client'].create({
|
||||
'client_name': 'Test Client',
|
||||
'redirect_uris': "http://localhost:8080/cb\nhttps://client.example.com/callback",
|
||||
})
|
||||
self.assertEqual(
|
||||
client.redirect_uris.splitlines(),
|
||||
["http://127.0.0.1:8080/cb", "https://client.example.com/callback"],
|
||||
)
|
||||
|
||||
client.redirect_uris = "http://LocalHost/cb"
|
||||
self.assertEqual(client.redirect_uris, "http://127.0.0.1/cb")
|
||||
44
ai_mcp/tests/test_oauth_metadata.py
Normal file
44
ai_mcp/tests/test_oauth_metadata.py
Normal file
@@ -0,0 +1,44 @@
|
||||
from unittest.mock import patch
|
||||
|
||||
from odoo.tests import HttpCase, tagged
|
||||
|
||||
OAUTH_BASE_URL = 'https://oauth.example.com'
|
||||
|
||||
|
||||
@tagged('post_install', '-at_install')
|
||||
class TestOauthServerMetadata(HttpCase):
|
||||
|
||||
def test_protected_resource_metadata(self):
|
||||
with patch(
|
||||
'odoo.addons.ai_mcp.controllers.oauth_server_controller.oauth_base_url',
|
||||
return_value=OAUTH_BASE_URL
|
||||
):
|
||||
response = self.url_open('/.well-known/oauth-protected-resource/mcp')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json(), {
|
||||
'resource': f'{OAUTH_BASE_URL}/mcp',
|
||||
'authorization_servers': [f'{OAUTH_BASE_URL}/oauth/mcp'],
|
||||
})
|
||||
|
||||
def test_authorization_server_metadata(self):
|
||||
with patch(
|
||||
'odoo.addons.ai_mcp.controllers.oauth_server_controller.oauth_base_url',
|
||||
return_value=OAUTH_BASE_URL
|
||||
):
|
||||
response = self.url_open('/.well-known/oauth-authorization-server/oauth/mcp')
|
||||
self.assertEqual(response.status_code, 200)
|
||||
|
||||
expected_metadata = {
|
||||
'issuer': f'{OAUTH_BASE_URL}/oauth/mcp',
|
||||
'authorization_endpoint': f'{OAUTH_BASE_URL}/oauth/authorize',
|
||||
'token_endpoint': f'{OAUTH_BASE_URL}/oauth/token',
|
||||
'revocation_endpoint': f'{OAUTH_BASE_URL}/oauth/revoke',
|
||||
'response_types_supported': ['code'],
|
||||
'grant_types_supported': ['authorization_code'],
|
||||
'code_challenge_methods_supported': ['S256'],
|
||||
'token_endpoint_auth_methods_supported': ['none'],
|
||||
'scopes_supported': ['mcp'],
|
||||
'client_id_metadata_document_supported': True,
|
||||
'authorization_response_iss_parameter_supported': True,
|
||||
}
|
||||
self.assertEqual(response.json(), expected_metadata)
|
||||
Reference in New Issue
Block a user