231 lines
15 KiB
Python
231 lines
15 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, override_settings
|
|
from oauth2_provider.models import Application, AccessToken
|
|
|
|
from .cimd import CompatibleCIMDFetcher
|
|
from .models import PersonalAccessToken
|
|
from .oauth_authorize import CHATGPT_CLIENT_ID
|
|
|
|
|
|
class McpOAuthTests(TestCase):
|
|
def test_chatgpt_reconnect_without_resource_offers_journal_access(self):
|
|
user = get_user_model().objects.create_user('chatgpt-journal-reconnect', password='test')
|
|
Application.objects.create(user=user, name='ChatGPT', client_id=CHATGPT_CLIENT_ID,
|
|
client_type=Application.CLIENT_PUBLIC,
|
|
authorization_grant_type=Application.GRANT_AUTHORIZATION_CODE,
|
|
redirect_uris='https://chatgpt.com/connector_platform_oauth_redirect')
|
|
self.client.force_login(user)
|
|
verifier = 'v' * 64
|
|
challenge = base64.urlsafe_b64encode(hashlib.sha256(verifier.encode()).digest()).decode().rstrip('=')
|
|
consent = self.client.get('/o/authorize/', {
|
|
'response_type': 'code', 'client_id': CHATGPT_CLIENT_ID,
|
|
'redirect_uri': 'https://chatgpt.com/connector_platform_oauth_redirect',
|
|
'scope': 'food:read food:write inventory:read inventory:write',
|
|
'state': 'chatgpt-reconnect', 'code_challenge': challenge,
|
|
'code_challenge_method': 'S256',
|
|
}, HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
|
|
self.assertEqual(consent.status_code, 200)
|
|
self.assertContains(consent, 'grant_journal_scopes')
|
|
form = consent.context['form']
|
|
self.assertFalse(form['resource'].value())
|
|
payload = {field.name: field.value() for field in form
|
|
if field.field.widget.is_hidden and field.value() is not None}
|
|
payload.update(allow='Authorize', grant_journal_scopes='on',
|
|
journal_scope_offer=consent.context['journal_scope_offer'])
|
|
redirect = self.client.post('/o/authorize/', payload,
|
|
HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
|
|
self.assertEqual(redirect.status_code, 302, redirect.content[:200])
|
|
code = parse_qs(urlparse(redirect['Location']).query)['code'][0]
|
|
token = self.client.post('/o/token/', {'grant_type': 'authorization_code', 'code': code,
|
|
'redirect_uri': 'https://chatgpt.com/connector_platform_oauth_redirect',
|
|
'client_id': CHATGPT_CLIENT_ID, 'code_verifier': verifier},
|
|
HTTP_HOST='tasksnest.jorendegraaf.eu', secure=True)
|
|
self.assertEqual(token.status_code, 200, token.content[:200])
|
|
self.assertEqual(set(token.json()['scope'].split()),
|
|
{'food:read', 'food:write', 'inventory:read', 'inventory:write', 'journal:read', 'journal:write'})
|
|
|
|
@override_settings(TASKNEST_MCP_PUBLIC_URL='http://localhost:8002/mcp')
|
|
def test_existing_client_can_explicitly_add_journal_scopes_on_reconnect(self):
|
|
user = get_user_model().objects.create_user('journal-upgrade', password='test')
|
|
application = Application.objects.create(user=user, name='Existing assistant',
|
|
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('=')
|
|
old_scopes = 'food:read food:write inventory:read inventory:write'
|
|
metadata = self.client.get('/.well-known/oauth-authorization-server', HTTP_HOST='localhost').json()
|
|
self.assertTrue({'journal:read', 'journal:write'} <= set(metadata['scopes_supported']))
|
|
|
|
def connect(state, add_journal=False):
|
|
params = {'response_type': 'code', 'client_id': application.client_id,
|
|
'redirect_uri': 'http://localhost:9876/callback', 'scope': old_scopes,
|
|
'state': state, 'code_challenge': challenge, 'code_challenge_method': 'S256',
|
|
'resource': 'http://localhost:8002/mcp'}
|
|
consent = self.client.get('/o/authorize/', params, HTTP_HOST='localhost')
|
|
self.assertEqual(consent.status_code, 200)
|
|
self.assertContains(consent, 'grant_journal_scopes')
|
|
form = consent.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'
|
|
if add_journal:
|
|
payload['grant_journal_scopes'] = 'on'
|
|
payload['journal_scope_offer'] = consent.context['journal_scope_offer']
|
|
redirect = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
|
|
self.assertEqual(redirect.status_code, 302, redirect.content[:200])
|
|
code = parse_qs(urlparse(redirect['Location']).query)['code'][0]
|
|
token_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(token_response.status_code, 200, token_response.content[:200])
|
|
return token_response.json()
|
|
|
|
original = connect('old-grant')
|
|
old_scope_set = set(original['scope'].split())
|
|
self.assertEqual(old_scope_set, set(old_scopes.split()))
|
|
self.assertEqual(self.client.get('/api/v1/dreams/',
|
|
HTTP_AUTHORIZATION=f"Bearer {original['access_token']}", HTTP_HOST='localhost').status_code, 403)
|
|
old_refresh = self.client.post('/o/token/', {'grant_type': 'refresh_token',
|
|
'refresh_token': original['refresh_token'], 'client_id': application.client_id,
|
|
'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
|
|
self.assertEqual(old_refresh.status_code, 200)
|
|
self.assertEqual(set(old_refresh.json()['scope'].split()), old_scope_set)
|
|
|
|
upgraded = connect('upgraded-grant', add_journal=True)
|
|
expected = set(old_scopes.split()) | {'journal:read', 'journal:write'}
|
|
self.assertEqual(set(upgraded['scope'].split()), expected)
|
|
self.assertEqual(self.client.get('/api/v1/dreams/',
|
|
HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}", HTTP_HOST='localhost').status_code, 200)
|
|
dream = self.client.post('/api/v1/dreams/',
|
|
data='{"wake_up_date":"2026-10-18","title":"Test","narrative":"User supplied."}',
|
|
content_type='application/json', HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}",
|
|
HTTP_HOST='localhost')
|
|
self.assertEqual(dream.status_code, 201, dream.content[:200])
|
|
self.assertEqual(self.client.get('/api/v1/stress/',
|
|
HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}", HTTP_HOST='localhost').status_code, 200)
|
|
self.assertEqual(self.client.get('/api/v1/food/today/',
|
|
HTTP_AUTHORIZATION=f"Bearer {upgraded['access_token']}", HTTP_HOST='localhost').status_code, 200)
|
|
refreshed = self.client.post('/o/token/', {'grant_type': 'refresh_token',
|
|
'refresh_token': upgraded['refresh_token'], 'client_id': application.client_id,
|
|
'resource': 'http://localhost:8002/mcp'}, HTTP_HOST='localhost')
|
|
self.assertEqual(refreshed.status_code, 200)
|
|
self.assertEqual(set(refreshed.json()['scope'].split()), expected)
|
|
|
|
@override_settings(TASKNEST_MCP_PUBLIC_URL='http://localhost:8002/mcp')
|
|
def test_journal_upgrade_rejects_missing_or_changed_offer(self):
|
|
user = get_user_model().objects.create_user('journal-offer', password='test')
|
|
application = Application.objects.create(user=user, name='Offer test',
|
|
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('=')
|
|
consent = self.client.get('/o/authorize/', {'response_type': 'code',
|
|
'client_id': application.client_id, 'redirect_uri': 'http://localhost:9876/callback',
|
|
'scope': 'food:read', 'state': 'offer-test', 'code_challenge': challenge,
|
|
'code_challenge_method': 'S256', 'resource': 'http://localhost:8002/mcp'},
|
|
HTTP_HOST='localhost')
|
|
form = consent.context['form']
|
|
payload = {field.name: field.value() for field in form
|
|
if field.field.widget.is_hidden and field.value() is not None}
|
|
payload.update(allow='Authorize', grant_journal_scopes='on')
|
|
response = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
|
|
self.assertEqual(response.status_code, 200)
|
|
self.assertContains(response, 'Journal permission offer expired')
|
|
payload['journal_scope_offer'] = consent.context['journal_scope_offer']
|
|
payload['scope'] = 'food:write'
|
|
response = self.client.post('/o/authorize/', payload, HTTP_HOST='localhost')
|
|
self.assertEqual(response.status_code, 200)
|
|
self.assertContains(response, 'Journal permission offer changed')
|
|
|
|
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)
|