Files
Django_TasksApp/main/food/test_oauth_mcp.py
T
2026-10-09 14:43:46 +02:00

95 lines
6.0 KiB
Python

import base64
import hashlib
from unittest.mock import patch
from urllib.parse import parse_qs, urlparse
from django.contrib.auth import get_user_model
from django.test import TestCase
from oauth2_provider.models import Application, AccessToken
from .cimd import CompatibleCIMDFetcher
from .models import PersonalAccessToken
class McpOAuthTests(TestCase):
def test_cimd_requires_explicit_public_client_support(self):
metadata = {'token_endpoint_auth_method': 'private_key_jwt',
'token_endpoint_auth_methods_supported': ['private_key_jwt']}
with patch('oauth2_provider.cimd.SafeMetadataFetcher.fetch', return_value=(metadata, 300)):
selected, _ = CompatibleCIMDFetcher().fetch('https://example.com/client.json')
self.assertEqual(selected['token_endpoint_auth_method'], 'private_key_jwt')
def test_chatgpt_cimd_can_select_public_client_method(self):
client_id = 'https://chatgpt.com/oauth/client.json'
redirect_uri = 'https://chatgpt.com/connector_platform_oauth_redirect'
metadata = {
'client_id': client_id,
'redirect_uris': [redirect_uri],
'grant_types': ['authorization_code', 'refresh_token'],
'token_endpoint_auth_method': 'private_key_jwt',
'token_endpoint_auth_methods_supported': ['none', 'private_key_jwt'],
'client_name': 'ChatGPT',
}
user = get_user_model().objects.create_user('chatgpt-cimd-test', password='test')
self.client.force_login(user)
verifier = 'v' * 64
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
with patch('oauth2_provider.cimd.SafeMetadataFetcher.fetch', return_value=(metadata, 300)):
response = self.client.get('/o/authorize/', {
'response_type': 'code', 'client_id': client_id, 'redirect_uri': redirect_uri,
'scope': 'food:read', 'state': 'cimd-test', 'code_challenge': challenge,
'code_challenge_method': 'S256', 'resource': 'https://tasksnest.jorendegraaf.eu',
}, HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
self.assertEqual(response.status_code, 200, response.content[:300])
self.assertContains(response, 'Authorize')
application = Application.objects.get(client_id=client_id)
self.assertEqual(application.client_type, Application.CLIENT_PUBLIC)
def test_authorization_code_issues_hashed_pat_and_revoke_synchronizes(self):
user = get_user_model().objects.create_user('oauth-test', password='test')
application = Application.objects.create(user=user, name='Test MCP client', client_type=Application.CLIENT_PUBLIC,
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
redirect_uris='http://localhost:9876/callback')
self.client.force_login(user)
verifier = 'v' * 64
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
params = {'response_type': 'code', 'client_id': application.client_id,
'redirect_uri': 'http://localhost:9876/callback', 'scope': 'food:read food:write',
'state': 'test-state', 'code_challenge': challenge, 'code_challenge_method': 'S256',
'resource': 'http://localhost:8002/mcp'}
response = self.client.get('/o/authorize/', params, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 200, response.content[:300])
form = response.context['form']
payload = {field.name: field.value() for field in form if field.field.widget.is_hidden and field.value() is not None}
payload['allow'] = 'Authorize'
response = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 302, response.content[:300])
code = parse_qs(urlparse(response['Location']).query)['code'][0]
response = self.client.post('/o/token/', {'grant_type': 'authorization_code', 'code': code,
'redirect_uri': 'http://localhost:9876/callback', 'client_id': application.client_id,
'code_verifier': verifier, 'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 200, response.content[:300])
secret = response.json()['access_token']
self.assertTrue(secret.startswith('tn_'))
pat = PersonalAccessToken.objects.get(user=user, token_hash=hashlib.sha256(secret.encode()).hexdigest())
oauth = AccessToken.objects.get(user=user, token_checksum=pat.token_hash)
self.assertEqual(oauth.token, '')
self.assertEqual(self.client.get('/api/v1/auth/whoami/', HTTP_AUTHORIZATION=f'Bearer {secret}',
HTTP_HOST='localhost').status_code, 200)
refresh = response.json()['refresh_token']
response = self.client.post('/o/token/', {'grant_type': 'refresh_token',
'refresh_token': refresh, 'client_id': application.client_id,
'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
self.assertEqual(response.status_code, 200, response.content[:300])
renewed = response.json()['access_token']
self.assertNotEqual(secret, renewed)
self.assertEqual(self.client.get('/api/v1/auth/whoami/', HTTP_AUTHORIZATION=f'Bearer {secret}',
HTTP_HOST='localhost').status_code, 401)
secret = renewed
pat = PersonalAccessToken.objects.get(user=user, token_hash=hashlib.sha256(secret.encode()).hexdigest())
oauth = AccessToken.objects.get(user=user, token_checksum=pat.token_hash)
self.client.post(f'/food/settings/tokens/{pat.pk}/revoke/', HTTP_HOST='localhost')
self.assertFalse(AccessToken.objects.filter(pk=oauth.pk).exists())
self.assertEqual(self.client.get('/api/v1/auth/whoami/', HTTP_AUTHORIZATION=f'Bearer {secret}',
HTTP_HOST='localhost').status_code, 401)