from concurrent.futures import ThreadPoolExecutor from contextlib import closing from io import BytesIO import json import os from pathlib import Path import runpy import sqlite3 import subprocess import sys import tempfile import threading import unittest import wave from unittest.mock import patch from test.upload_photo_test import PNG from test.upload_video_test import VIDEO from utilities.validation import valid_stream_url ROOT = Path(__file__).resolve().parents[1] class SubmissionValidationTest(unittest.TestCase): def setUp(self): self.directory = tempfile.TemporaryDirectory() self.addCleanup(self.directory.cleanup) self.workdir = Path(self.directory.name) self.database = self.workdir / 'test.db' (self.workdir / 'config.json').write_text(json.dumps({ 'database': {'type': 'SQLite', 'name': 'test.db'}, 'upload_location': 'uploads' })) subprocess.run([sys.executable, str(ROOT / 'sc_database_generator.py')], cwd=self.workdir, check=True, capture_output=True) original = Path.cwd() try: os.chdir(self.workdir) self.app = runpy.run_path(str(ROOT / 'sc_webserver.py'))['app'] finally: os.chdir(original) self.app.config['TESTING'] = True self.client = self.app.test_client() def submit(self, kind, name): if kind == 'photo': return self.client.post('/upload/photo', data={ 'name': name, 'files[]': (BytesIO(PNG), 'photo.png')}) if kind == 'video': return self.client.post('/upload/video', data={ 'name': name, 'files[]': (BytesIO(VIDEO), 'video.mp4')}) if kind == 'stream': return self.client.post('/configure/stream', data={ 'buttonName': name, 'streamURL': 'https://example.com/stream'}) return self.client.post('/youtube/download', data={ 'media_name': name, 'youtube_url': 'https://youtu.be/video'}) def test_duplicate_catalog_names_rejected_for_all_workflows(self): with closing(sqlite3.connect(self.database)) as db: db.execute('INSERT INTO media (media_name, media_uri) VALUES (?, ?)', ['Straße', 'old']) db.commit() for kind in ('photo', 'video', 'stream', 'youtube'): with self.subTest(kind=kind): response = self.submit(kind, ' STRASSE ') self.assertEqual(response.status_code, 400) message = response.json['error'] if response.is_json else response.get_data(as_text=True) self.assertIn('already in use', message) self.assertEqual(list((self.workdir / 'Images').glob('*')), []) self.assertEqual(list((self.workdir / 'Videos').glob('*')), []) def test_pending_and_downloading_jobs_reserve_names_but_failed_jobs_do_not(self): for status in ('pending', 'downloading', 'failed', 'downloaded'): with self.subTest(status=status): with closing(sqlite3.connect(self.database)) as db: db.execute('DELETE FROM youtube_download_job') db.execute('DELETE FROM media') db.execute('INSERT INTO youtube_download_job (youtube_download_job_url, ' 'youtube_download_job_media_name, youtube_download_job_status) VALUES (?, ?, ?)', ['https://youtu.be/video', 'Reserved', status]) db.commit() for kind in ('photo', 'video', 'stream', 'youtube'): response = self.submit(kind, ' reserved ') if status in ('pending', 'downloading'): self.assertEqual(response.status_code, 400, kind) else: self.assertIn(response.status_code, (200, 303), kind) # Isolate each submission so successful routes do not reserve the name for the next. with closing(sqlite3.connect(self.database)) as db: db.execute('DELETE FROM media') db.execute("DELETE FROM youtube_download_job WHERE youtube_download_job_status = 'pending'") db.commit() def test_names_must_be_nonempty_bounded_and_without_controls(self): for name in ('', ' ', 'x' * 121, 'x\x00y', 'x\n'): for kind in ('photo', 'video', 'stream', 'youtube'): with self.subTest(name=name, kind=kind): self.assertEqual(self.submit(kind, name).status_code, 400) def test_stream_url_validation_and_error_preserves_input(self): for url in ('https://example.com/live', 'rtsp://192.168.1.20:8554/live', 'rtmp://localhost/live', 'udp://239.1.1.1:1234', 'tcp://[::1]:8000'): self.assertTrue(valid_stream_url(url), url) for url in ('', 'file:///etc/passwd', 'https://', 'https://host:bad/path', 'https://a b/test', 'http://example.com\\@evil/', 'https://-bad.host/test', 'http://host:0/', 'concat:foo', 'http://host/\x00'): self.assertFalse(valid_stream_url(url), repr(url)) response = self.client.post('/configure/stream', data={ 'buttonName': '', 'streamURL': 'not-a-url'}) self.assertEqual(response.status_code, 400) self.assertIn(b'<Name>', response.data) self.assertIn(b'network stream URL', response.data) self.assertEqual(self.client.post('/configure/stream', data={}).status_code, 400) def test_stream_is_atomic_and_checkbox_optional(self): with closing(sqlite3.connect(self.database)) as db: db.execute("""CREATE TRIGGER reject_option BEFORE INSERT ON media_playback_option BEGIN SELECT RAISE(ABORT, 'option failure'); END""") db.commit() with self.assertLogs(self.app.logger, level='ERROR'): response = self.client.post('/configure/stream', data={ 'buttonName': 'Stream', 'streamURL': 'rtsp://example.com/live', 'fullScreen': 'on'}) self.assertEqual(response.status_code, 503) with closing(sqlite3.connect(self.database)) as db: self.assertEqual(db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,)) response = self.client.post('/configure/stream', data={ 'buttonName': 'Stream', 'streamURL': 'rtsp://example.com/live'}) self.assertEqual(response.status_code, 303) with closing(sqlite3.connect(self.database)) as db: self.assertEqual(db.execute('SELECT media_name, media_uri FROM media').fetchall(), [('Stream', 'rtsp://example.com/live')]) def test_youtube_urls_require_specific_video(self): from blueprints.youtube_download.youtube_download import valid_youtube_url for url in ('https://youtu.be/abc', 'https://youtube.com/watch?v=abc', 'https://www.youtube.com/shorts/abc', 'https://youtube.com/live/abc', 'https://youtube.com/embed/abc'): self.assertTrue(valid_youtube_url(url), url) for url in ('https://youtube.com/watch', 'https://youtube.com/watch?v=', 'https://youtube.com/playlist?list=abc', 'https://youtube.com/channel/abc', 'https://youtube.com/unrelated', 'https://youtu.be/', 'https://youtube.com/watch?v=abc&v=def', 'https://youtube.com/watch?v=abc%0A'): self.assertFalse(valid_youtube_url(url), url) def test_uploads_reject_invalid_and_mismatched_content(self): cases = [('/upload/photo', b'not an image', 'image.png'), ('/upload/photo', VIDEO, 'image.png'), ('/upload/photo', PNG, 'image.jpg'), ('/upload/video', b'not a video', 'video.mp4'), ('/upload/video', PNG, 'video.mp4')] for route, content, filename in cases: with self.subTest(route=route, filename=filename): response = self.client.post(route, data={'name': 'Name', 'files[]': (BytesIO(content), filename)}) self.assertEqual(response.status_code, 400) self.assertEqual(response.json['status'], 'FAILED') self.assertEqual(list((self.workdir / 'Images').glob('*')), []) self.assertEqual(list((self.workdir / 'Videos').glob('*')), []) with closing(sqlite3.connect(self.database)) as db: self.assertEqual(db.execute('SELECT COUNT(*) FROM media').fetchone(), (0,)) def test_audio_only_and_truncated_files_are_rejected(self): buffer = BytesIO() with wave.open(buffer, 'wb') as audio: audio.setnchannels(1) audio.setsampwidth(2) audio.setframerate(8000) audio.writeframes(b'\x00\x00' * 800) for route, content, filename in ( ('/upload/video', buffer.getvalue(), 'audio.mp4'), ('/upload/photo', PNG[:35], 'truncated.png'), ('/upload/video', VIDEO[:80], 'truncated.mp4') ): with self.subTest(filename=filename): response = self.client.post(route, data={'name': 'Name', 'files[]': (BytesIO(content), filename)}) self.assertEqual(response.status_code, 400) self.assertEqual(list((self.workdir / 'Images').glob('*')), []) self.assertEqual(list((self.workdir / 'Videos').glob('*')), []) def test_upload_unexpected_extra_files_are_rejected(self): for route, content, filename in (('/upload/photo', PNG, 'photo.png'), ('/upload/video', VIDEO, 'video.mp4')): response = self.client.post(route, data={'name': 'Name', 'files[]': (BytesIO(content), filename), 'extra': (BytesIO(b'bad'), 'other.txt')}) self.assertEqual(response.status_code, 400) def test_probe_unavailable_or_timed_out_is_helpful_and_cleans_up(self): for error in (FileNotFoundError(), subprocess.TimeoutExpired('ffprobe', 30)): with self.subTest(error=error): with patch('utilities.validation.subprocess.run', side_effect=error): with self.assertLogs(self.app.logger, level='WARNING'): response = self.submit('photo', 'Name') self.assertEqual(response.status_code, 503) self.assertIn('validat', response.json['error']) self.assertEqual(list((self.workdir / 'Images').glob('*')), []) def test_corrupt_or_excessive_image_metadata_is_rejected(self): for width, height in ((0, 10), (10000, 10000)): report = json.dumps({'format': {'format_name': 'png_pipe'}, 'streams': [{ 'codec_type': 'video', 'codec_name': 'png', 'width': width, 'height': height }]}).encode() with self.subTest(width=width, height=height): with patch('utilities.validation.subprocess.run', return_value=subprocess.CompletedProcess([], 0, report)): response = self.submit('photo', 'Name') self.assertEqual(response.status_code, 400) self.assertIn('dimensions', response.json['error']) self.assertEqual(list((self.workdir / 'Images').glob('*')), []) def test_database_failure_reports_error_for_forms_and_listing(self): with patch('utilities.database.sqlite.SQLite.query', side_effect=sqlite3.OperationalError('secret')): for kind in ('stream', 'youtube'): with self.subTest(kind=kind): with self.assertLogs(self.app.logger, level='ERROR'): response = self.submit(kind, 'Name') self.assertEqual(response.status_code, 503) self.assertIn(b'database', response.data) self.assertNotIn(b'secret', response.data) for endpoint in ('/youtube/jobs', '/media', '/media/status'): with self.assertLogs(self.app.logger, level='ERROR'): response = self.client.get(endpoint) self.assertEqual(response.status_code, 503) self.assertNotIn(b'secret', response.data) def test_concurrent_submissions_allow_only_one_name(self): barrier = threading.Barrier(2) def submit(kind): with self.app.test_client() as client: barrier.wait(timeout=5) if kind == 'youtube': return client.post('/youtube/download', data={ 'media_name': 'Same Name', 'youtube_url': 'https://youtu.be/video'}).status_code return client.post('/configure/stream', data={ 'buttonName': 'same name', 'streamURL': 'https://example.com/stream'}).status_code with ThreadPoolExecutor(max_workers=2) as executor: results = list(executor.map(submit, ('youtube', 'stream'))) self.assertCountEqual(results, [303, 400]) if __name__ == '__main__': unittest.main()