import hashlib import io import threading import unittest import urllib.error from unittest.mock import patch import release_transport as transfers class TransferToolsTests(unittest.TestCase): def setUp(self): environment = patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': ''}) environment.start() self.addCleanup(environment.stop) def test_local_api_transport_preserves_authenticated_request_and_public_identity(self): class Response(io.BytesIO): headers = {'Content-Type': 'application/json'} with patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': 'http://127.0.0.1:3000/', 'GITEA_TOKEN': 'test-token'}), \ patch.object(transfers.urllib.request, 'urlopen', return_value=Response(b'{"id":3}')) as open_url: result = transfers.request(transfers.SERVER + '/api/v1/releases?name=a%20b', data=b'package', method='POST', content_type='application/octet-stream') request = open_url.call_args.args[0] self.assertEqual(result, {'id': 3}) self.assertEqual(request.full_url, 'http://127.0.0.1:3000/api/v1/releases?name=a%20b') self.assertEqual(request.get_method(), 'POST') self.assertEqual(request.get_header('Authorization'), 'token test-token') self.assertEqual(request.get_header('Host'), 'git.orangraph.com') self.assertEqual(request.data, b'package') self.assertEqual(transfers.SERVER, 'https://git.orangraph.com') def test_local_verification_routes_validated_attachment_without_changing_its_public_url(self): asset = {'browser_download_url': 'https://git.orangraph.com/attachments/example'} with patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': 'http://127.0.0.1:3000', 'GITEA_TOKEN': 'test-token'}), \ patch.object(transfers.urllib.request, 'urlopen', return_value=io.BytesIO(b'app')) as open_url: result = transfers.fingerprint(asset) self.assertEqual(open_url.call_args.args[0].full_url, 'http://127.0.0.1:3000/attachments/example') self.assertEqual(open_url.call_args.args[0].get_header('Host'), 'git.orangraph.com') self.assertEqual(result['sha256'], hashlib.sha256(b'app').hexdigest()) self.assertEqual(asset['browser_download_url'], 'https://git.orangraph.com/attachments/example') def test_local_ci_archive_request_keeps_local_host_for_signed_redirect(self): class Response(io.BytesIO): headers = {'Content-Type': 'application/zip'} with patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': 'http://127.0.0.1:3000', 'GITEA_TOKEN': 'test-token'}), \ patch.object(transfers.urllib.request, 'urlopen', return_value=Response(b'archive')) as open_url: result = transfers.request(transfers.SERVER + '/api/v1/repos/owner/repo/actions/artifacts/40/zip') request = open_url.call_args.args[0] self.assertEqual(result, b'archive') self.assertEqual(request.full_url, 'http://127.0.0.1:3000/api/v1/repos/owner/repo/actions/artifacts/40/zip') self.assertIsNone(request.get_header('Host')) self.assertEqual(request.get_header('Authorization'), 'token test-token') def test_local_host_exception_does_not_change_other_api_response_links(self): for path, method in [ ('/api/v1/repos/owner/repo/actions/artifacts/40/zip', 'POST'), ('/api/v1/repos/owner/repo/actions/artifacts/not-a-number/zip', None), ('/api/v1/repos/owner/repo/releases/40/zip', None), ]: class Response(io.BytesIO): headers = {'Content-Type': 'application/json'} with self.subTest(path=path, method=method), \ patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': 'http://127.0.0.1:3000', 'GITEA_TOKEN': 'test-token'}), \ patch.object(transfers.urllib.request, 'urlopen', return_value=Response(b'{}')) as open_url: transfers.request(transfers.SERVER + path, method=method) self.assertEqual(open_url.call_args.args[0].get_header('Host'), 'git.orangraph.com') def test_local_transport_rejects_unexpected_endpoint_or_origin_before_sending_credentials(self): for internal, url, message in [ ('http://example.com:3000', transfers.SERVER + '/api/v1/releases', 'internal Gitea endpoint'), ('http://127.0.0.1:3000', 'https://example.com/file', 'transport origin'), ('http://127.0.0.1:3000', 'http://git.orangraph.com/file', 'transport origin'), ]: with self.subTest(internal=internal, url=url), \ patch.dict('os.environ', {'CUTDEX_GITEA_INTERNAL_URL': internal, 'GITEA_TOKEN': 'test-token'}), \ patch.object(transfers.urllib.request, 'urlopen') as open_url: with self.assertRaisesRegex(ValueError, message): transfers.request(url) open_url.assert_not_called() def test_frp_tunnel_not_found_page_is_retried_as_a_temporary_failure(self): calls = 0 def transport(url, data=None, method=None, content_type=None): nonlocal calls if method is None: return [] calls += 1 if calls == 1: body = b'

Not Found

frp' raise urllib.error.HTTPError(url, 404, 'Not Found', {'Content-Type': 'text/html; charset=utf-8'}, io.BytesIO(body)) return {} with patch.object(transfers.time, 'sleep') as sleep: transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport) self.assertEqual(calls, 2) sleep.assert_called_once_with(5) def test_ordinary_html_not_found_and_json_api_errors_are_not_retried(self): for content_type, body in [('text/html', b'

Not Found

'), ('application/json', b'Not Found github.com/fatedier/frp')]: with self.subTest(content_type=content_type): error = urllib.error.HTTPError('url', 404, 'Not Found', {'Content-Type': content_type}, io.BytesIO(body)) self.assertFalse(transfers.transient(error)) def test_transient_upload_failure_retries_without_restarting_other_files(self): calls = [] def transport(url, data=None, method=None, content_type=None): if method is None: return [] calls.append(url) if url.endswith('name=retry.zip') and calls.count(url) == 1: raise urllib.error.URLError('connection reset') return {} with patch.object(transfers.time, 'sleep') as sleep: transfers.upload_contents('base', 3, {'retry.zip': b'a', 'ok.zip': b'b'}, transport=transport) self.assertEqual(sum(url.endswith('name=retry.zip') for url in calls), 2) self.assertEqual(sum(url.endswith('name=ok.zip') for url in calls), 1) sleep.assert_called_once_with(5) def test_response_lost_after_upload_does_not_duplicate_attachment(self): for committed_on in (1, 3): with self.subTest(committed_on=committed_on): calls = 0 assets = [] def transport(url, data=None, method=None, content_type=None): nonlocal calls if method is None: return assets calls += 1 if calls == committed_on: assets.append({'name': 'app.zip'}) raise TimeoutError('response lost') with patch.object(transfers.time, 'sleep'): transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport) self.assertEqual(calls, committed_on) self.assertEqual(len(assets), 1) def test_upload_retries_are_bounded_and_last_error_is_propagated(self): calls = 0 def transport(url, data=None, method=None, content_type=None): nonlocal calls if method is None: return [] calls += 1 raise urllib.error.HTTPError(url, 503, 'Unavailable', {}, None) with patch.object(transfers.time, 'sleep') as sleep: with self.assertRaises(urllib.error.HTTPError): transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport) self.assertEqual(calls, 3) self.assertEqual([call.args[0] for call in sleep.call_args_list], [5, 15]) def test_permanent_upload_errors_fail_without_retries(self): for status in (400, 401, 403, 404, 409, 422): with self.subTest(status=status): calls = 0 def transport(url, data=None, method=None, content_type=None): nonlocal calls if method is None: return [] calls += 1 raise urllib.error.HTTPError(url, status, 'Permanent failure', {}, None) with patch.object(transfers.time, 'sleep') as sleep: with self.assertRaises(urllib.error.HTTPError): transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport) self.assertEqual(calls, 1) sleep.assert_not_called() def test_retry_reconciliation_rejects_duplicate_attachments(self): reads, uploads = 0, 0 def transport(url, data=None, method=None, content_type=None): nonlocal reads, uploads if method is None: reads += 1 return [] if reads == 1 else [{'name': 'app.zip'}, {'name': 'app.zip'}] uploads += 1 raise TimeoutError('response lost') with patch.object(transfers.time, 'sleep'): with self.assertRaisesRegex(ValueError, 'Duplicate Release attachments'): transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport) self.assertEqual(uploads, 1) def test_attachment_list_retries_rate_limiting_before_upload(self): reads, uploads = 0, 0 def transport(url, data=None, method=None, content_type=None): nonlocal reads, uploads if method is None: reads += 1 if reads == 1: raise urllib.error.HTTPError(url, 429, 'Rate limited', {}, None) return [] uploads += 1 return {} with patch.object(transfers.time, 'sleep') as sleep: transfers.upload_contents('base', 3, {'app.zip': b'app'}, transport=transport) self.assertEqual((reads, uploads), (2, 1)) sleep.assert_called_once_with(5) def test_uploads_run_with_at_most_two_workers(self): barrier = threading.Barrier(2) lock = threading.Lock() active, maximum = 0, 0 uploads = [] def transport(url, data=None, method=None, content_type=None): nonlocal active, maximum if method is None: return [] self.assertEqual(method, 'POST') with lock: active += 1 maximum = max(maximum, active) try: barrier.wait(timeout=5) with lock: uploads.append(url) return {} finally: with lock: active -= 1 transfers.upload_contents('base', 3, {f'file-{i}.zip': b'file' for i in range(4)}, transport=transport) self.assertEqual(maximum, 2) self.assertEqual(len(uploads), 4) def test_worker_failure_is_propagated(self): def transport(url, data=None, method=None, content_type=None): if method is None: return [] raise OSError('upload failed') with self.assertRaisesRegex(OSError, 'upload failed'): transfers.upload_contents('base', 3, {'first.zip': b'a', 'second.zip': b'b'}, transport=transport) def test_invalid_filename_is_rejected_before_any_upload(self): with patch.object(transfers, 'request', return_value=[]) as request: with self.assertRaisesRegex(ValueError, 'Unexpected artifact path'): transfers.upload_contents('base', 3, {'valid.zip': b'a', '../invalid.zip': b'b'}) self.assertEqual(request.call_count, 1) def test_streaming_fingerprint_never_reads_entire_response_at_once(self): body = b'a' * (1024 * 1024 + 123) class Response(io.BytesIO): def read(self, size=-1): if size != 1024 * 1024: raise AssertionError('Expected bounded chunk reads') return super().read(size) with patch.dict('os.environ', {'GITEA_TOKEN': 'test-token'}), \ patch.object(transfers.urllib.request, 'urlopen', return_value=Response(body)) as open_url: result = transfers.fingerprint({'browser_download_url': 'http://git.orangraph.com/attachments/example'}) self.assertEqual(result, {'sha256': hashlib.sha256(body).hexdigest(), 'sha1': hashlib.sha1(body).hexdigest(), 'size': len(body)}) self.assertEqual(open_url.call_args.args[0].full_url, 'https://git.orangraph.com/attachments/example') def test_streaming_verification_rejects_unexpected_host(self): with patch.object(transfers.urllib.request, 'urlopen') as open_url: with self.assertRaisesRegex(ValueError, 'Unexpected attachment host'): transfers.fingerprint({'browser_download_url': 'https://example.com/file'}) open_url.assert_not_called() if __name__ == '__main__': unittest.main()