import hashlib import io import os import tempfile import unittest from pathlib import Path from types import SimpleNamespace from unittest.mock import patch import httpx from fastapi import HTTPException from starlette.datastructures import UploadFile from apps.admin.services import ConfigService from apps.base.models import KeyValue, UploadChunk from apps.base.views import validate_file_size from core.security import validate_outbound_endpoint, validate_outbound_hostname from core.settings import settings from tests.helpers import init_memory_db, close_db class EndpointValidationTests(unittest.TestCase): def test_production_rejects_internal_urls_and_hostname_bypasses(self): dns = [(None, None, None, None, ('127.0.0.1', 0))] with patch.dict(os.environ, {'APP_ENV': 'production'}), patch('core.security.socket.getaddrinfo', return_value=dns): for value in ['http://127.0.0.1', 'http://169.254.169.254', 'http://clouddrive:19798/dav', 'http://127.1', 'http://2130706433', 'https://dns-trick.example', 'file:///etc/passwd', 'gopher://127.0.0.1']: with self.subTest(value=value), self.assertRaises(ValueError): validate_outbound_endpoint(value) for value in ['localhost', '127.1', '[::1]:9000', 'evil.example@127.0.0.1', 'https://public.example', 'nas.local', 'dns-trick.example']: with self.subTest(value=value), self.assertRaises(ValueError): validate_outbound_hostname(value) def test_public_endpoints_normalize_and_development_keeps_internal_support(self): dns = [(None, None, None, None, ('8.8.8.8', 0))] with patch.dict(os.environ, {'APP_ENV': 'production'}), patch('core.security.socket.getaddrinfo', return_value=dns): self.assertEqual(validate_outbound_endpoint(' https://public.example:9000 '), 'https://public.example:9000') self.assertEqual(validate_outbound_hostname(' public.example:9000 '), 'public.example:9000') self.assertEqual(validate_outbound_endpoint(''), '') with patch.dict(os.environ, {'APP_ENV': 'development'}): self.assertEqual(validate_outbound_endpoint('http://clouddrive:19798/dav'), 'http://clouddrive:19798/dav') self.assertEqual(validate_outbound_hostname('127.0.0.1:9000'), '127.0.0.1:9000') class Upgrade271IntegrationTests(unittest.IsolatedAsyncioTestCase): async def asyncSetUp(self): self.original = dict(settings.user_config) await init_memory_db() async def asyncTearDown(self): settings.user_config = self.original await close_db() async def test_existing_internal_dav_survives_unrelated_settings_save(self): config = {**settings.default_config, 'webdav_url': 'http://clouddrive:19798/dav', 's3_hostname': 'nas.local'} await KeyValue.create(key='settings', value=config) with patch.dict(os.environ, {'APP_ENV': 'production'}): await ConfigService().update_config({'name': 'new title', 'webdav_url': config['webdav_url']}) stored = (await KeyValue.get(key='settings')).value self.assertEqual(stored['webdav_url'], config['webdav_url']) self.assertEqual(stored['name'], 'new title') for update in [{'webdav_url': 'http://127.0.0.1'}, {'s3_hostname': 'evil.example@127.0.0.1'}, {'s3_endpoint_url': 'http://169.254.169.254'}]: with self.subTest(update=update), self.assertRaises(HTTPException) as error: await ConfigService().update_config(update) self.assertEqual(error.exception.status_code, 400) self.assertEqual((await KeyValue.get(key='settings')).value, stored) async def test_unknown_upload_size_measures_and_resets_file(self): for spool in [False, True]: file_obj = tempfile.SpooledTemporaryFile(max_size=2) if spool else io.BytesIO() file_obj.write(b'payload');file_obj.seek(3) file = UploadFile(file=file_obj, filename='size.bin', size=None) try: self.assertEqual(await validate_file_size(file, 7), 7) self.assertEqual(await file.read(), b'payload') with self.assertRaises(HTTPException) as error: await validate_file_size(file, 6) self.assertEqual(error.exception.status_code, 403) finally: await file.close() async def test_api_404_is_json_and_unknown_html_navigation_keeps_spa(self): from main import app from core.utils import hash_password await KeyValue.create(key='settings', value={**settings.default_config, 'admin_token': hash_password('test-271'), 'jwt_secret': 's'*48}) with tempfile.TemporaryDirectory() as tmp: Path(tmp, 'index.html').write_text('test SPA') with patch('main.resolve_theme_root', return_value=Path(tmp)), patch('main.resolve_theme_file', return_value=Path(tmp, 'index.html')): async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client: missing = await client.get('/no-such-api', headers={'Accept': 'application/json'}) self.assertEqual(missing.status_code, 404);self.assertEqual(missing.json()['code'], 404) endpoint404 = await client.get('/chunk/upload/status/not-present', headers={'Accept':'text/html'}) self.assertEqual(endpoint404.status_code,404);self.assertIn('application/json',endpoint404.headers['content-type']) navigation = await client.get('/some/spa/path', headers={'Accept': 'text/html'}) self.assertEqual(navigation.status_code, 200);self.assertIn('test SPA', navigation.text) # A matched endpoint's HTTPException must never become a successful HTML page. from main import not_found_handler request = SimpleNamespace(url=SimpleNamespace(path='/share/file'),method='GET',headers={'accept':'text/html'},scope={'route':object()}) self.assertEqual((await not_found_handler(request)).status_code, 404) async def test_download_accepts_time_windows_and_rejects_wrong_or_unicode_keys(self): from fastapi import FastAPI from apps.base.views import share_api from core.utils import get_select_token from apps.base.utils import ip_limit settings.user_config = {**settings.default_config, 'file_storage': 'local', 'jwt_secret': 'test-271-key-'*4} for limiter in ip_limit.values(): limiter.ips.clear() app = FastAPI();app.include_router(share_api) async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app), base_url='http://test') as client: uploaded = await client.post('/share/text/',data={'text':'boundary test','expire_style':'day'}) self.assertEqual(uploaded.status_code,200,uploaded.text) code = uploaded.json()['detail']['code'] for offset in (0,1): token = await get_select_token(code,offset=offset) response = await client.get('/share/download',params={'code':code,'key':token}) self.assertEqual(response.status_code,200,response.text) for key in ('wrong','密钥'*32,await get_select_token('other-code')): response = await client.get('/share/download',params={'code':code,'key':key}) self.assertEqual(response.status_code,403,response.text) async def test_s3_small_chunks_merge_with_legal_parts_and_abort_corruption(self): from moto.server import ThreadedMotoServer from core.storage import S3FileStorage server = ThreadedMotoServer('127.0.0.1', 0);server.start() endpoint = f'http://127.0.0.1:{server._server.server_port}' settings.user_config = {**self.original, 's3_endpoint_url': endpoint, 's3_access_key_id': 'testing', 's3_secret_access_key': 'testing', 's3_bucket_name': 'test-271-bucket', 's3_region_name': 'us-east-1', 's3_signature_version': 's3v4'} try: storage = S3FileStorage() async with storage._client() as s3: await s3.create_bucket(Bucket=storage.bucket_name) chunks = [b'a'*(2*1024*1024), b'b'*(2*1024*1024), b'c'*(2*1024*1024), b'last'] info = SimpleNamespace(total_chunks=len(chunks), chunk_size=2*1024*1024, file_size=sum(map(len,chunks))) path = 'share/data/271/combined.bin' for index, data in enumerate(chunks): await storage.save_chunk('s3-271', index, data, hashlib.sha256(data).hexdigest(), path) await UploadChunk.create(upload_id='s3-271', chunk_index=index, chunk_hash=hashlib.sha256(data).hexdigest(), completed=True, total_chunks=info.total_chunks, file_size=info.file_size, chunk_size=info.chunk_size, file_name='combined.bin', save_path=path) _, digest = await storage.merge_chunks('s3-271', info, path) self.assertEqual(digest, hashlib.sha256(b''.join(chunks)).hexdigest()) async with storage._client() as s3: response = await s3.get_object(Bucket=storage.bucket_name, Key=path) self.assertEqual(await response['Body'].read(), b''.join(chunks)) await UploadChunk.filter(upload_id='s3-271',chunk_index=2).update(chunk_hash='invalid') with self.assertRaises(ValueError): await storage.merge_chunks('s3-271', info, path) async with storage._client() as s3: pending = await s3.list_multipart_uploads(Bucket=storage.bucket_name) self.assertFalse(pending.get('Uploads')) finally: server.stop()