This commit is contained in:
Joren de Graaf
2026-10-09 14:43:46 +02:00
parent c825cd474e
commit 559c51e9bb
20 changed files with 322 additions and 27 deletions
+43 -1
View File
@@ -16,15 +16,33 @@ import httpx2
from PIL import Image
from django.conf import settings
from django.contrib.auth import get_user_model
from django.test import LiveServerTestCase
from django.test import LiveServerTestCase, SimpleTestCase
from django.utils import timezone
from mcp import Client
from mcp.client.streamable_http import streamable_http_client
from mcp.server.mcpserver.exceptions import ToolError
from oauth2_provider.models import Application
from food.api import create_token
from food.models import FoodLogEntry, FoodProduct, InventoryLocation, KitchenInventoryItem
from planner.timezones import localdate_for_user
from .server import ClientImageFile, _allowed_file_host, _resolve_image
class ImageHostLoggingTests(SimpleTestCase):
def test_chatgpt_blob_account_is_allowed_without_allowing_other_blob_accounts(self):
self.assertTrue(_allowed_file_host('oaisdmntprukwest.blob.core.windows.net'))
self.assertFalse(_allowed_file_host('other.blob.core.windows.net'))
self.assertFalse(_allowed_file_host('not-oaisdmntprukwest.blob.core.windows.net'))
def test_rejected_file_logs_only_hostname(self):
image = ClientImageFile(download_url='https://files.example.invalid/private?signature=secret', file_id='test')
with self.assertLogs('mcp_server.server', level='WARNING') as captured:
with self.assertRaisesRegex(ToolError, 'not an allowed HTTPS file host'):
asyncio.run(_resolve_image(None, image, None, 'image'))
self.assertIn('files.example.invalid', captured.output[0])
self.assertNotIn('/private', captured.output[0])
self.assertNotIn('signature=secret', captured.output[0])
class McpHttpTests(LiveServerTestCase):
@@ -58,6 +76,8 @@ class McpHttpTests(LiveServerTestCase):
try:
response = httpx2.get(f'http://127.0.0.1:{self.port}/.well-known/oauth-protected-resource/mcp', timeout=1)
if response.status_code == 200:
self.assertEqual(response.json()['scopes_supported'],
['food:read', 'food:write', 'inventory:read', 'inventory:write'])
break
except httpx2.RequestError:
pass
@@ -80,6 +100,11 @@ class McpHttpTests(LiveServerTestCase):
def test_authentication_and_scope_boundaries(self):
async def check():
async with httpx2.AsyncClient(timeout=10) as http:
response = await http.post(self.mcp_url, headers={'Authorization': 'Bearer ' + self.secret,
'Host': 'untrusted.example', 'Accept': 'application/json, text/event-stream'},
json={'jsonrpc': '2.0', 'id': 1, 'method': 'tools/list'})
self.assertEqual(response.status_code, 421)
for secret in ('bad-token', self.expired_secret, self.revoked_secret):
async with httpx2.AsyncClient(timeout=10) as http:
response = await http.post(self.mcp_url, headers={'Authorization': 'Bearer ' + secret,
@@ -122,6 +147,9 @@ class McpHttpTests(LiveServerTestCase):
asyncio.run(self._client(secret, check))
def test_food_inventory_tools_and_user_isolation(self):
previous_day = localdate_for_user(self.a) - timedelta(days=1)
FoodLogEntry.objects.create(user=self.a, date=previous_day, meal='breakfast',
product_name_snapshot='Yesterday oats', amount=Decimal('100'), unit='g', calories_kcal=Decimal('120'))
image = Image.new('RGB', (2, 2), 'red')
output = io.BytesIO()
image.save(output, format='PNG')
@@ -132,6 +160,11 @@ class McpHttpTests(LiveServerTestCase):
self.assertEqual(len(names), 12)
today = (await client.call_tool('food_get_today')).structured_content
self.assertEqual(today['meals']['lunch'], [])
yesterday = (await client.call_tool('food_get_today', {'date': previous_day.isoformat()})).structured_content
self.assertEqual(yesterday['date'], previous_day.isoformat())
self.assertEqual(yesterday['meals']['breakfast'][0]['name'], 'Yesterday oats')
self.assertEqual(yesterday['totals']['calories_kcal'], '120')
self.assertTrue((await client.call_tool('food_get_today', {'date': 'yesterday'})).is_error)
products = (await client.call_tool('food_search_products', {'query': 'Pasta'})).structured_content
self.assertEqual(products['count'], 1)
self.assertEqual((await client.call_tool('food_search_products', {'query': 'Private rice'})).structured_content['count'], 0)
@@ -148,6 +181,15 @@ class McpHttpTests(LiveServerTestCase):
'image_base64': encoded, 'mime_type': 'image/png', 'filename': 'meal.png',
'idempotency_key': 'mcp-image-1'})).structured_content
self.assertTrue(image_result['success'])
unsafe_file = await client.call_tool('food_attach_image', {'entry_id': entry_id,
'image_file': {'download_url': 'http://127.0.0.1/private', 'file_id': 'test'}})
self.assertTrue(unsafe_file.is_error)
unknown_host = await client.call_tool('food_attach_image', {'entry_id': entry_id,
'image_file': {'download_url': 'https://files.example.invalid/private?signature=secret',
'file_id': 'test'}})
self.assertTrue(unknown_host.is_error)
self.assertNotIn('files.example.invalid', str(unknown_host.content))
self.assertNotIn('signature=secret', str(unknown_host.content))
combined_food = {'meal': 'lunch', 'amount': '1', 'unit': 'g',
'product_name': 'Estimated meal', 'calories_kcal': '850'}
combined = (await client.call_tool('food_log_with_image', {'food': combined_food,