From 6ee3ceac4d8ce7c8e3441825295ba9f8e40a7bba Mon Sep 17 00:00:00 2001 From: Jorge Date: Thu, 28 May 2026 18:04:51 -0400 Subject: [PATCH 1/3] Fail fast on unsanitized plugin output in FSLinkStorage --- pfcon/copy_worker.py | 7 ++- pfcon/resources.py | 35 ++++++++--- pfcon/storage/fslink_storage.py | 25 +++++++- tests/test_resources_fslink.py | 107 +++++++++++++++++++++++++++++++- 4 files changed, 162 insertions(+), 12 deletions(-) diff --git a/pfcon/copy_worker.py b/pfcon/copy_worker.py index 6f371be..c372b08 100755 --- a/pfcon/copy_worker.py +++ b/pfcon/copy_worker.py @@ -164,7 +164,12 @@ def main(): key_dir = args[0] if subcommand == 'copy': - do_copy(key_dir) + try: + do_copy(key_dir) + except Exception as e: + logger.error(f'Copy worker failed for {key_dir}, ' + f'detail: {str(e)}') + sys.exit(1) elif subcommand == 'upload': do_upload(key_dir) elif subcommand == 'delete': diff --git a/pfcon/resources.py b/pfcon/resources.py index 709b999..1a4b7e8 100755 --- a/pfcon/resources.py +++ b/pfcon/resources.py @@ -474,8 +474,13 @@ def get(self, job_id): else: storage = FSLinkStorage(app.config) - content = storage.get_data(job_id, outgoing_dir, - job_output_path=job_output_path) + try: + content = storage.get_data(job_id, outgoing_dir, + job_output_path=job_output_path) + except Exception as e: + logger.error(f'Error fetching job {job_id} output data, ' + f'detail: {str(e)}') + abort(500, message=str(e)) download_name = f'{job_id}.json' mimetype = 'application/json' @@ -486,6 +491,7 @@ def get(self, job_id): job_output_path = job_output_path.lstrip('/') job_dir = os.path.join(self.storebase_mount, 'key-' + job_id) outgoing_dir = os.path.join(job_dir, 'outgoing') + if not os.path.exists(outgoing_dir): os.mkdir(outgoing_dir) @@ -493,9 +499,14 @@ def get(self, job_id): storage = SwiftStorage(app.config) else: storage = S3Storage(app.config) - content = storage.get_output_metadata( - job_id, outgoing_dir, - job_output_path=job_output_path) + try: + content = storage.get_output_metadata( + job_id, outgoing_dir, + job_output_path=job_output_path) + except Exception as e: + logger.error(f'Error fetching job {job_id} output ' + f'metadata, detail: {str(e)}') + abort(500, message=str(e)) download_name = f'{job_id}.json' mimetype = 'application/json' @@ -509,7 +520,12 @@ def get(self, job_id): os.mkdir(outgoing_dir) storage = ZipFileStorage(app.config) - content = storage.get_data(job_id, outgoing_dir) + try: + content = storage.get_data(job_id, outgoing_dir) + except Exception as e: + logger.error(f'Error fetching job {job_id} output data, ' + f'detail: {str(e)}') + abort(500, message=str(e)) else: job_dir = os.path.join(self.storebase_mount, 'key-' + job_id) if not os.path.isdir(job_dir): @@ -521,7 +537,12 @@ def get(self, job_id): if self.storage_env == 'zipfile': storage = ZipFileStorage(app.config) - content = storage.get_data(job_id, outgoing_dir) + try: + content = storage.get_data(job_id, outgoing_dir) + except Exception as e: + logger.error(f'Error fetching job {job_id} output data, ' + f'detail: {str(e)}') + abort(500, message=str(e)) logger.info(f'Successfully retrieved job {job_id} output data') diff --git a/pfcon/storage/fslink_storage.py b/pfcon/storage/fslink_storage.py index 334fd80..382b552 100755 --- a/pfcon/storage/fslink_storage.py +++ b/pfcon/storage/fslink_storage.py @@ -81,7 +81,8 @@ def get_data(self, job_id, job_outgoing_dir, **kwargs): list of relative file paths. Any .chrislink files found in the outgoing directory are removed: ChRIS links - may only be authored by upstream CUBE, never by plugin output. + may only be authored by upstream CUBE, never by plugin output. In addition, any + symlinks found in the outgoing directory are also removed. """ fs_rel_file_paths = [] job_output_path = kwargs['job_output_path'] @@ -96,6 +97,8 @@ def get_data(self, job_id, job_outgoing_dir, **kwargs): local_file_path = os.path.join(root, filename) if filename.endswith('.chrislink'): + # a non-deletable attacker-controlled link left in an output + # dir is a security-relevant state: fail the job logger.warning(f'Removing unauthorized .chrislink file ' f'{local_file_path} from job {job_id} output; ' f'plugins are not allowed to create ChRIS links') @@ -105,10 +108,26 @@ def get_data(self, job_id, job_outgoing_dir, **kwargs): logger.error(f'Failed to remove unauthorized .chrislink file ' f'{local_file_path} for job {job_id}, ' f'detail: {str(e)}') + raise + continue + + if os.path.islink(local_file_path): + # symlinks can point anywhere on the mounted filesystem; + # same blast radius as .chrislink, so treat as fatal on + # removal failure + logger.warning(f'Removing unauthorized symlink ' + f'{local_file_path} from job {job_id} output; ' + f'plugins are not allowed to create symlinks') + try: + os.remove(local_file_path) + except OSError as e: + logger.error(f'Failed to remove unauthorized symlink ' + f'{local_file_path} for job {job_id}, ' + f'detail: {str(e)}') + raise continue - if not os.path.islink(local_file_path): - fs_rel_file_paths.append(os.path.join(rel_path, filename)) + fs_rel_file_paths.append(os.path.join(rel_path, filename)) data = {'job_output_path': job_output_path, 'rel_file_paths': fs_rel_file_paths} diff --git a/tests/test_resources_fslink.py b/tests/test_resources_fslink.py index c7c743e..8e66112 100755 --- a/tests/test_resources_fslink.py +++ b/tests/test_resources_fslink.py @@ -17,9 +17,10 @@ from pathlib import Path import shutil import os +import tempfile import time import json -from unittest import TestCase +from unittest import TestCase, mock from flask import url_for @@ -27,6 +28,7 @@ from pfcon.compute.container_user import ContainerUser from pfcon.compute.abstractmgr import ManagerException from pfcon.base_resources import get_compute_mgr +from pfcon.storage.fslink_storage import FSLinkStorage class NewResourcesFsLinkTests(TestCase): @@ -306,3 +308,106 @@ def test_post_noop_when_no_key_dir(self): 'finishedSuccessfully') self.assertEqual(response.json['compute']['message'], 'deleteSkipped') + + +class TestFSLinkStorageGetDataSanitization(TestCase): + """ + Unit tests for FSLinkStorage.get_data() output sanitization: + plugin-produced .chrislink files and symlinks must be removed, + and any failure to remove them must propagate (treated as fatal, + matching CUBE's _register_output_files() behavior). + """ + + def setUp(self): + logging.disable(logging.WARNING) + self.tmpdir = tempfile.mkdtemp() + self.job_output_rel = 'job-out' + self.outgoing_dir = os.path.join(self.tmpdir, self.job_output_rel) + os.makedirs(self.outgoing_dir) + self.storage = FSLinkStorage({'STOREBASE_MOUNT': self.tmpdir}) + + def tearDown(self): + shutil.rmtree(self.tmpdir, ignore_errors=True) + logging.disable(logging.NOTSET) + + def _get_data(self): + content = self.storage.get_data('job-1', self.outgoing_dir, + job_output_path=self.job_output_rel) + return json.loads(content.getvalue().decode()) + + def test_removes_chrislink_files(self): + regular_path = os.path.join(self.outgoing_dir, 'out.txt') + link_path = os.path.join(self.outgoing_dir, 'evil.chrislink') + with open(regular_path, 'w') as f: + f.write('legit output') + with open(link_path, 'w') as f: + f.write('home/victim') + + data = self._get_data() + + self.assertFalse(os.path.exists(link_path)) + self.assertTrue(os.path.exists(regular_path)) + self.assertIn('out.txt', data['rel_file_paths']) + self.assertNotIn('evil.chrislink', data['rel_file_paths']) + + def test_removes_symlinks(self): + target_path = os.path.join(self.tmpdir, 'secret.txt') + with open(target_path, 'w') as f: + f.write('secret data') + regular_path = os.path.join(self.outgoing_dir, 'out.txt') + with open(regular_path, 'w') as f: + f.write('legit output') + symlink_path = os.path.join(self.outgoing_dir, 'leak') + os.symlink(target_path, symlink_path) + + data = self._get_data() + + self.assertFalse(os.path.lexists(symlink_path)) + self.assertTrue(os.path.exists(target_path)) # target untouched + self.assertTrue(os.path.exists(regular_path)) + self.assertIn('out.txt', data['rel_file_paths']) + self.assertNotIn('leak', data['rel_file_paths']) + + def test_chrislink_symlink_takes_chrislink_path(self): + # a *.chrislink symlink must be removed via os.remove (which unlinks + # the symlink itself, not its target) and logged through the + # .chrislink branch + target_path = os.path.join(self.tmpdir, 'target.txt') + with open(target_path, 'w') as f: + f.write('linked content') + link_path = os.path.join(self.outgoing_dir, 'evil.chrislink') + os.symlink(target_path, link_path) + + data = self._get_data() + + self.assertFalse(os.path.lexists(link_path)) + self.assertTrue(os.path.exists(target_path)) + self.assertNotIn('evil.chrislink', data['rel_file_paths']) + + def test_raises_on_unremovable_chrislink(self): + link_path = os.path.join(self.outgoing_dir, 'evil.chrislink') + with open(link_path, 'w') as f: + f.write('home/victim') + + with mock.patch('pfcon.storage.fslink_storage.os.remove', + side_effect=OSError('permission denied')): + with self.assertRaises(OSError): + self.storage.get_data('job-1', self.outgoing_dir, + job_output_path=self.job_output_rel) + # link must still exist on disk: removal failed and the exception + # propagated, so the job is fatally failed by the caller + self.assertTrue(os.path.exists(link_path)) + + def test_raises_on_unremovable_symlink(self): + target_path = os.path.join(self.tmpdir, 'secret.txt') + with open(target_path, 'w') as f: + f.write('secret') + symlink_path = os.path.join(self.outgoing_dir, 'leak') + os.symlink(target_path, symlink_path) + + with mock.patch('pfcon.storage.fslink_storage.os.remove', + side_effect=OSError('permission denied')): + with self.assertRaises(OSError): + self.storage.get_data('job-1', self.outgoing_dir, + job_output_path=self.job_output_rel) + self.assertTrue(os.path.lexists(symlink_path)) From 7ec73ddab24ebacbe1a4071b762b23d86c0949fc Mon Sep 17 00:00:00 2001 From: Jorge Date: Thu, 28 May 2026 20:03:02 -0400 Subject: [PATCH 2/3] Delete symlinks pointing to directories and increse test coverage --- pfcon/copy_worker.py | 5 +- pfcon/resources.py | 24 ++-- pfcon/storage/fslink_storage.py | 74 +++++++---- tests/test_resources_fslink.py | 225 ++++++++++++++++++++++++++++++++ tests/test_resources_mocked.py | 94 +++++++++++++ 5 files changed, 384 insertions(+), 38 deletions(-) diff --git a/pfcon/copy_worker.py b/pfcon/copy_worker.py index c372b08..8ce53d2 100755 --- a/pfcon/copy_worker.py +++ b/pfcon/copy_worker.py @@ -166,9 +166,8 @@ def main(): if subcommand == 'copy': try: do_copy(key_dir) - except Exception as e: - logger.error(f'Copy worker failed for {key_dir}, ' - f'detail: {str(e)}') + except Exception: + logger.exception(f'Copy worker failed for {key_dir}') sys.exit(1) elif subcommand == 'upload': do_upload(key_dir) diff --git a/pfcon/resources.py b/pfcon/resources.py index 1a4b7e8..cb9778e 100755 --- a/pfcon/resources.py +++ b/pfcon/resources.py @@ -9,6 +9,7 @@ from flask import request, send_file, current_app as app from flask_restful import reqparse, abort, Resource +from werkzeug.exceptions import HTTPException from .storage.zip_file_storage import ZipFileStorage from .storage.swift_storage import SwiftStorage @@ -477,9 +478,10 @@ def get(self, job_id): try: content = storage.get_data(job_id, outgoing_dir, job_output_path=job_output_path) + except HTTPException: + raise except Exception as e: - logger.error(f'Error fetching job {job_id} output data, ' - f'detail: {str(e)}') + logger.exception(f'Error fetching job {job_id} output data') abort(500, message=str(e)) download_name = f'{job_id}.json' mimetype = 'application/json' @@ -503,9 +505,11 @@ def get(self, job_id): content = storage.get_output_metadata( job_id, outgoing_dir, job_output_path=job_output_path) + except HTTPException: + raise except Exception as e: - logger.error(f'Error fetching job {job_id} output ' - f'metadata, detail: {str(e)}') + logger.exception(f'Error fetching job {job_id} output ' + f'metadata') abort(500, message=str(e)) download_name = f'{job_id}.json' @@ -522,9 +526,11 @@ def get(self, job_id): storage = ZipFileStorage(app.config) try: content = storage.get_data(job_id, outgoing_dir) + except HTTPException: + raise except Exception as e: - logger.error(f'Error fetching job {job_id} output data, ' - f'detail: {str(e)}') + logger.exception(f'Error fetching job {job_id} output ' + f'data') abort(500, message=str(e)) else: job_dir = os.path.join(self.storebase_mount, 'key-' + job_id) @@ -539,9 +545,11 @@ def get(self, job_id): storage = ZipFileStorage(app.config) try: content = storage.get_data(job_id, outgoing_dir) + except HTTPException: + raise except Exception as e: - logger.error(f'Error fetching job {job_id} output data, ' - f'detail: {str(e)}') + logger.exception(f'Error fetching job {job_id} output ' + f'data') abort(500, message=str(e)) logger.info(f'Successfully retrieved job {job_id} output data') diff --git a/pfcon/storage/fslink_storage.py b/pfcon/storage/fslink_storage.py index 382b552..865ac1a 100755 --- a/pfcon/storage/fslink_storage.py +++ b/pfcon/storage/fslink_storage.py @@ -81,8 +81,8 @@ def get_data(self, job_id, job_outgoing_dir, **kwargs): list of relative file paths. Any .chrislink files found in the outgoing directory are removed: ChRIS links - may only be authored by upstream CUBE, never by plugin output. In addition, any - symlinks found in the outgoing directory are also removed. + may only be authored by upstream CUBE, never by plugin output. In addition, any + symlink found in the outgoing directory is also removed. """ fs_rel_file_paths = [] job_output_path = kwargs['job_output_path'] @@ -93,38 +93,34 @@ def get_data(self, job_id, job_outgoing_dir, **kwargs): if rel_path == '.': rel_path = '' + # symlinks to directories land in `dirs` (os.walk classifies via + # is_dir which follows symlinks), so the files-pass alone misses + # them. Sanitize dirs first and mutate the list in place so + # os.walk does not descend into anything we removed. + kept_dirs = [] + for dirname in dirs: + dir_path = os.path.join(root, dirname) + if os.path.islink(dir_path): + self._unlink_or_fail(dir_path, job_id, + entity='symlink', + policy_plural='symlinks') + continue + kept_dirs.append(dirname) + dirs[:] = kept_dirs + for filename in files: local_file_path = os.path.join(root, filename) if filename.endswith('.chrislink'): - # a non-deletable attacker-controlled link left in an output - # dir is a security-relevant state: fail the job - logger.warning(f'Removing unauthorized .chrislink file ' - f'{local_file_path} from job {job_id} output; ' - f'plugins are not allowed to create ChRIS links') - try: - os.remove(local_file_path) - except OSError as e: - logger.error(f'Failed to remove unauthorized .chrislink file ' - f'{local_file_path} for job {job_id}, ' - f'detail: {str(e)}') - raise + self._unlink_or_fail(local_file_path, job_id, + entity='.chrislink file', + policy_plural='ChRIS links') continue if os.path.islink(local_file_path): - # symlinks can point anywhere on the mounted filesystem; - # same blast radius as .chrislink, so treat as fatal on - # removal failure - logger.warning(f'Removing unauthorized symlink ' - f'{local_file_path} from job {job_id} output; ' - f'plugins are not allowed to create symlinks') - try: - os.remove(local_file_path) - except OSError as e: - logger.error(f'Failed to remove unauthorized symlink ' - f'{local_file_path} for job {job_id}, ' - f'detail: {str(e)}') - raise + self._unlink_or_fail(local_file_path, job_id, + entity='symlink', + policy_plural='symlinks') continue fs_rel_file_paths.append(os.path.join(rel_path, filename)) @@ -133,6 +129,30 @@ def get_data(self, job_id, job_outgoing_dir, **kwargs): 'rel_file_paths': fs_rel_file_paths} return io.BytesIO(json.dumps(data).encode()) + @staticmethod + def _unlink_or_fail(path, job_id, *, entity, policy_plural): + """ + Unlink an unauthorized filesystem entry produced by a plugin and + re-raise OSError on failure. A non-deletable attacker-controlled + entry left in an output dir is a security-relevant state, so this + helper treats removal failure as fatal — the caller must let the + exception propagate so the job fails rather than reporting success + with a tainted output dir. + + `entity` is the singular noun used in the log messages (e.g. + '.chrislink file', 'symlink'); `policy_plural` is the noun used + in the policy statement (e.g. 'ChRIS links', 'symlinks'). + """ + logger.warning(f'Removing unauthorized {entity} {path} from job ' + f'{job_id} output; plugins are not allowed to ' + f'create {policy_plural}') + try: + os.remove(path) + except OSError: + logger.exception(f'Failed to remove unauthorized {entity} ' + f'{path} for job {job_id}') + raise + def delete_data(self, job_dir): """ Delete job data from the local storage. diff --git a/tests/test_resources_fslink.py b/tests/test_resources_fslink.py index 8e66112..bd2506f 100755 --- a/tests/test_resources_fslink.py +++ b/tests/test_resources_fslink.py @@ -411,3 +411,228 @@ def test_raises_on_unremovable_symlink(self): self.storage.get_data('job-1', self.outgoing_dir, job_output_path=self.job_output_rel) self.assertTrue(os.path.lexists(symlink_path)) + + def test_removes_symlink_to_directory(self): + # os.walk classifies symlink-to-dir as a directory (entry.is_dir() + # follows symlinks), so it lands in `dirs`, not `files`. The + # sanitizer must check dirs too. + target_dir = os.path.join(self.tmpdir, 'secret_dir') + os.makedirs(target_dir) + with open(os.path.join(target_dir, 'inside.txt'), 'w') as f: + f.write('private') + regular_path = os.path.join(self.outgoing_dir, 'out.txt') + with open(regular_path, 'w') as f: + f.write('legit output') + symlink_path = os.path.join(self.outgoing_dir, 'leak_dir') + os.symlink(target_dir, symlink_path) + + data = self._get_data() + + self.assertFalse(os.path.lexists(symlink_path)) + # target directory and its contents are untouched + self.assertTrue(os.path.isdir(target_dir)) + self.assertTrue(os.path.isfile( + os.path.join(target_dir, 'inside.txt'))) + self.assertIn('out.txt', data['rel_file_paths']) + # nothing from the symlink target should leak into the metadata + self.assertFalse(any('leak_dir' in p or 'inside.txt' in p + for p in data['rel_file_paths'])) + + def test_raises_on_unremovable_symlink_to_directory(self): + target_dir = os.path.join(self.tmpdir, 'secret_dir') + os.makedirs(target_dir) + symlink_path = os.path.join(self.outgoing_dir, 'leak_dir') + os.symlink(target_dir, symlink_path) + + with mock.patch('pfcon.storage.fslink_storage.os.remove', + side_effect=OSError('permission denied')): + with self.assertRaises(OSError): + self.storage.get_data('job-1', self.outgoing_dir, + job_output_path=self.job_output_rel) + self.assertTrue(os.path.lexists(symlink_path)) + + def test_dirs_mutation_blocks_descent_when_followlinks_true(self): + # The dirs[:] mutation is the second line of defense: even with + # followlinks=True (a future-proofing concern), os.walk must not + # descend into a removed symlink. Make os.remove a no-op so the + # symlink stays on disk and force followlinks=True; if dirs[:] + # mutation were removed, os.walk would descend into the symlinked + # dir and `inside.txt` would leak into rel_file_paths. + target_dir = os.path.join(self.tmpdir, 'secret_dir') + os.makedirs(target_dir) + with open(os.path.join(target_dir, 'inside.txt'), 'w') as f: + f.write('private') + os.symlink(target_dir, + os.path.join(self.outgoing_dir, 'leak_dir')) + + original_walk = os.walk + + def walk_with_followlinks(*args, **kwargs): + kwargs['followlinks'] = True + return original_walk(*args, **kwargs) + + with mock.patch('pfcon.storage.fslink_storage.os.remove'), \ + mock.patch('pfcon.storage.fslink_storage.os.walk', + side_effect=walk_with_followlinks): + data = self._get_data() + + self.assertFalse(any('inside.txt' in p + for p in data['rel_file_paths']), + f'symlink target leaked: {data["rel_file_paths"]}') + + def test_sanitizes_nested_directories(self): + # Sanitization applies through subdirectories — a .chrislink or + # symlink several levels deep must still be removed and excluded + # from rel_file_paths. + subdir = os.path.join(self.outgoing_dir, 'sub1', 'sub2') + os.makedirs(subdir) + with open(os.path.join(subdir, 'evil.chrislink'), 'w') as f: + f.write('home/x') + with open(os.path.join(subdir, 'real.txt'), 'w') as f: + f.write('ok') + target_path = os.path.join(self.tmpdir, 'secret.txt') + with open(target_path, 'w') as f: + f.write('s') + os.symlink(target_path, os.path.join(subdir, 'leak')) + + data = self._get_data() + + self.assertFalse(os.path.exists( + os.path.join(subdir, 'evil.chrislink'))) + self.assertFalse(os.path.lexists(os.path.join(subdir, 'leak'))) + rel_real = os.path.join('sub1', 'sub2', 'real.txt') + self.assertIn(rel_real, data['rel_file_paths']) + self.assertFalse(any(p.endswith('.chrislink') or p.endswith('leak') + for p in data['rel_file_paths'])) + + def test_removes_broken_symlink(self): + # A dangling symlink (target does not exist) lands in `files` + # because os.walk's is_dir(follow=True) returns False. The + # sanitizer must still remove it — both as defense-in-depth and + # because a downstream consumer could resolve the target. + symlink_path = os.path.join(self.outgoing_dir, 'broken') + os.symlink(os.path.join(self.tmpdir, 'does_not_exist'), + symlink_path) + with open(os.path.join(self.outgoing_dir, 'real.txt'), 'w') as f: + f.write('ok') + + data = self._get_data() + + self.assertFalse(os.path.lexists(symlink_path)) + self.assertIn('real.txt', data['rel_file_paths']) + self.assertNotIn('broken', data['rel_file_paths']) + + +class TestPluginJobFileFsLinkSanitizationFailure(NewResourcesFsLinkTests): + """ + Lock in the resources.py outer wrapper: when FSLinkStorage.get_data + raises during output sanitization, PluginJobFile must convert the + exception into an HTTP 500 rather than letting it become a 200 with + incomplete or tainted metadata. + """ + + def test_returns_500_when_get_data_raises(self): + job_id = 'fslink-sanitization-fail-1' + output_rel = os.path.relpath(self.fs_output_path, + self.storebase_mount) + + # Drop a .chrislink file in the outgoing dir so the sanitizer has + # a removal call to make. + with open(os.path.join(self.fs_output_path, 'evil.chrislink'), + 'w') as f: + f.write('home/x') + + with self.app.test_request_context(): + file_url = url_for('api.pluginjobfile', job_id=job_id) + + # Force the .chrislink removal to fail; this exercises the + # OSError re-raise in get_data and the abort(500) wrapper in + # resources.PluginJobFile.get(). + with mock.patch('pfcon.storage.fslink_storage.os.remove', + side_effect=OSError('permission denied')): + response = self.client.get( + file_url, + query_string={'job_output_path': output_rel}, + headers=self.headers) + + self.assertEqual(response.status_code, 500) + + +class TestPluginJobFileFsLinkHTTPExceptionPassthrough(NewResourcesFsLinkTests): + """ + The abort-500 wrappers in PluginJobFile.get() must let + werkzeug HTTPExceptions propagate unchanged. Without an explicit + `except HTTPException: raise` ahead of the broad `except Exception`, + a future storage method that calls flask_restful.abort(404) (or + similar) would have its intended status silently downgraded to 500. + """ + + def test_http_exception_from_storage_propagates_unchanged(self): + from werkzeug.exceptions import NotFound + + job_id = 'fslink-httpexc-1' + output_rel = os.path.relpath(self.fs_output_path, + self.storebase_mount) + + with self.app.test_request_context(): + file_url = url_for('api.pluginjobfile', job_id=job_id) + + # Storage method raises NotFound (a 404 HTTPException). The + # wrapper must let it pass through, not catch and rewrite as 500. + with mock.patch( + 'pfcon.storage.fslink_storage.FSLinkStorage.get_data', + side_effect=NotFound('not found')): + response = self.client.get( + file_url, + query_string={'job_output_path': output_rel}, + headers=self.headers) + + self.assertEqual(response.status_code, 404) + + +class TestCopyWorkerExitOnFailure(TestCase): + """ + Lock in the copy_worker.main() outer wrapper: when do_copy raises, + the worker must exit with status 1 so the compute manager records + finishedWithError and CUBE refuses to schedule the plugin job. + Also confirm the upload/delete subcommands were intentionally not + wrapped, so anyone who later 'fixes' them by adding the same wrapper + has to update this test and consciously change the contract. + """ + + def test_copy_subcommand_exits_1_on_exception(self): + import pfcon.copy_worker as cw + + with mock.patch.object(cw, 'do_copy', + side_effect=RuntimeError('boom')): + with mock.patch('sys.argv', + ['copy_worker', 'copy', '/tmp/nonexistent']): + with self.assertRaises(SystemExit) as cm: + cw.main() + + self.assertEqual(cm.exception.code, 1) + + def test_upload_subcommand_propagates_exception(self): + # No try/except around upload; an unhandled exception bubbles up + # as a plain Python error and produces a non-zero exit via the + # interpreter's default behavior. If anyone wraps it later, + # this test will fail and force the contract change to be + # explicit. + import pfcon.copy_worker as cw + + with mock.patch.object(cw, 'do_upload', + side_effect=RuntimeError('boom')): + with mock.patch('sys.argv', + ['copy_worker', 'upload', '/tmp/nonexistent']): + with self.assertRaises(RuntimeError): + cw.main() + + def test_delete_subcommand_propagates_exception(self): + import pfcon.copy_worker as cw + + with mock.patch.object(cw, 'do_delete', + side_effect=RuntimeError('boom')): + with mock.patch('sys.argv', + ['copy_worker', 'delete', '/tmp/nonexistent']): + with self.assertRaises(RuntimeError): + cw.main() diff --git a/tests/test_resources_mocked.py b/tests/test_resources_mocked.py index fdbdbd5..c4ffb50 100755 --- a/tests/test_resources_mocked.py +++ b/tests/test_resources_mocked.py @@ -1958,3 +1958,97 @@ def test_docker_with_host_ok(self): 'STOREBASE': self.tmpdir, }) self.assertEqual(app.config['COMPUTE_VOLUME_TYPE'], 'host') + + +# --------------------------------------------------------------------------- +# PluginJobFile abort-500 wrappers for non-fslink storage backends. +# The fslink wrapper is covered in tests/test_resources_fslink.py +# (TestPluginJobFileFsLinkSanitizationFailure). +# --------------------------------------------------------------------------- + +class TestPluginJobFileWrappersNonFslink(NewResourcesTestBase): + """ + PluginJobFile.get() wraps its storage call in + try/except HTTPException: raise / except Exception -> abort(500) for + every storage backend. Verify the swift, s3, and zipfile + (out-of-network) wrappers fire by mocking the storage class to + raise a non-HTTP exception, and asserting the client sees 500. + """ + + def _set_config(self, **overrides): + saved = {k: self.app.config.get(k) for k in overrides} + + def restore(): + for k, v in saved.items(): + self.app.config[k] = v + + for k, v in overrides.items(): + self.app.config[k] = v + return restore + + def test_swift_get_output_metadata_failure_returns_500(self): + job_id = 'wrapper-swift-1' + os.makedirs(os.path.join(self.tmpdir, 'key-' + job_id, 'outgoing')) + + restore = self._set_config(STORAGE_ENV='swift') + try: + with self.app.test_request_context(): + url = url_for('api.pluginjobfile', job_id=job_id) + + mock_storage = mock.MagicMock() + mock_storage.get_output_metadata.side_effect = OSError('boom') + with mock.patch('pfcon.resources.SwiftStorage', + return_value=mock_storage): + response = self.client.get( + url, + query_string={'job_output_path': 'some/path'}, + headers=self.headers) + + self.assertEqual(response.status_code, 500) + finally: + restore() + + def test_s3_get_output_metadata_failure_returns_500(self): + job_id = 'wrapper-s3-1' + os.makedirs(os.path.join(self.tmpdir, 'key-' + job_id, 'outgoing')) + + restore = self._set_config(STORAGE_ENV='s3') + try: + with self.app.test_request_context(): + url = url_for('api.pluginjobfile', job_id=job_id) + + mock_storage = mock.MagicMock() + mock_storage.get_output_metadata.side_effect = OSError('boom') + with mock.patch('pfcon.resources.S3Storage', + return_value=mock_storage): + response = self.client.get( + url, + query_string={'job_output_path': 'some/path'}, + headers=self.headers) + + self.assertEqual(response.status_code, 500) + finally: + restore() + + def test_zipfile_get_data_failure_returns_500(self): + # Out-of-network zipfile path: PFCON_INNETWORK=False, + # STORAGE_ENV='zipfile'. The job key dir must exist or the + # handler short-circuits with 404 before reaching the wrapper. + job_id = 'wrapper-zipfile-1' + os.makedirs(os.path.join(self.tmpdir, 'key-' + job_id, 'outgoing')) + + restore = self._set_config(PFCON_INNETWORK=False, + STORAGE_ENV='zipfile') + try: + with self.app.test_request_context(): + url = url_for('api.pluginjobfile', job_id=job_id) + + mock_storage = mock.MagicMock() + mock_storage.get_data.side_effect = OSError('boom') + with mock.patch('pfcon.resources.ZipFileStorage', + return_value=mock_storage): + response = self.client.get(url, headers=self.headers) + + self.assertEqual(response.status_code, 500) + finally: + restore() From fde37b23be07a3f4fbd418bd5af189d3a8ef131c Mon Sep 17 00:00:00 2001 From: Jorge Date: Fri, 29 May 2026 10:52:39 -0400 Subject: [PATCH 3/3] Use flattened with statements with the parenthesized form --- tests/test_resources_fslink.py | 97 ++++++++++++++++++---------------- 1 file changed, 52 insertions(+), 45 deletions(-) diff --git a/tests/test_resources_fslink.py b/tests/test_resources_fslink.py index bd2506f..e876544 100755 --- a/tests/test_resources_fslink.py +++ b/tests/test_resources_fslink.py @@ -14,7 +14,6 @@ """ import logging -from pathlib import Path import shutil import os import tempfile @@ -23,7 +22,9 @@ from unittest import TestCase, mock from flask import url_for +from werkzeug.exceptions import NotFound +import pfcon.copy_worker as cw from pfcon.app import create_app from pfcon.compute.container_user import ContainerUser from pfcon.compute.abstractmgr import ManagerException @@ -389,11 +390,13 @@ def test_raises_on_unremovable_chrislink(self): with open(link_path, 'w') as f: f.write('home/victim') - with mock.patch('pfcon.storage.fslink_storage.os.remove', - side_effect=OSError('permission denied')): - with self.assertRaises(OSError): - self.storage.get_data('job-1', self.outgoing_dir, - job_output_path=self.job_output_rel) + with ( + mock.patch('pfcon.storage.fslink_storage.os.remove', + side_effect=OSError('permission denied')), + self.assertRaises(OSError), + ): + self.storage.get_data('job-1', self.outgoing_dir, + job_output_path=self.job_output_rel) # link must still exist on disk: removal failed and the exception # propagated, so the job is fatally failed by the caller self.assertTrue(os.path.exists(link_path)) @@ -405,11 +408,13 @@ def test_raises_on_unremovable_symlink(self): symlink_path = os.path.join(self.outgoing_dir, 'leak') os.symlink(target_path, symlink_path) - with mock.patch('pfcon.storage.fslink_storage.os.remove', - side_effect=OSError('permission denied')): - with self.assertRaises(OSError): - self.storage.get_data('job-1', self.outgoing_dir, - job_output_path=self.job_output_rel) + with ( + mock.patch('pfcon.storage.fslink_storage.os.remove', + side_effect=OSError('permission denied')), + self.assertRaises(OSError), + ): + self.storage.get_data('job-1', self.outgoing_dir, + job_output_path=self.job_output_rel) self.assertTrue(os.path.lexists(symlink_path)) def test_removes_symlink_to_directory(self): @@ -444,11 +449,13 @@ def test_raises_on_unremovable_symlink_to_directory(self): symlink_path = os.path.join(self.outgoing_dir, 'leak_dir') os.symlink(target_dir, symlink_path) - with mock.patch('pfcon.storage.fslink_storage.os.remove', - side_effect=OSError('permission denied')): - with self.assertRaises(OSError): - self.storage.get_data('job-1', self.outgoing_dir, - job_output_path=self.job_output_rel) + with ( + mock.patch('pfcon.storage.fslink_storage.os.remove', + side_effect=OSError('permission denied')), + self.assertRaises(OSError), + ): + self.storage.get_data('job-1', self.outgoing_dir, + job_output_path=self.job_output_rel) self.assertTrue(os.path.lexists(symlink_path)) def test_dirs_mutation_blocks_descent_when_followlinks_true(self): @@ -471,9 +478,11 @@ def walk_with_followlinks(*args, **kwargs): kwargs['followlinks'] = True return original_walk(*args, **kwargs) - with mock.patch('pfcon.storage.fslink_storage.os.remove'), \ - mock.patch('pfcon.storage.fslink_storage.os.walk', - side_effect=walk_with_followlinks): + with ( + mock.patch('pfcon.storage.fslink_storage.os.remove'), + mock.patch('pfcon.storage.fslink_storage.os.walk', + side_effect=walk_with_followlinks), + ): data = self._get_data() self.assertFalse(any('inside.txt' in p @@ -568,8 +577,6 @@ class TestPluginJobFileFsLinkHTTPExceptionPassthrough(NewResourcesFsLinkTests): """ def test_http_exception_from_storage_propagates_unchanged(self): - from werkzeug.exceptions import NotFound - job_id = 'fslink-httpexc-1' output_rel = os.path.relpath(self.fs_output_path, self.storebase_mount) @@ -601,14 +608,14 @@ class TestCopyWorkerExitOnFailure(TestCase): """ def test_copy_subcommand_exits_1_on_exception(self): - import pfcon.copy_worker as cw - - with mock.patch.object(cw, 'do_copy', - side_effect=RuntimeError('boom')): - with mock.patch('sys.argv', - ['copy_worker', 'copy', '/tmp/nonexistent']): - with self.assertRaises(SystemExit) as cm: - cw.main() + with ( + mock.patch.object(cw, 'do_copy', + side_effect=RuntimeError('boom')), + mock.patch('sys.argv', + ['copy_worker', 'copy', '/tmp/nonexistent']), + self.assertRaises(SystemExit) as cm, + ): + cw.main() self.assertEqual(cm.exception.code, 1) @@ -618,21 +625,21 @@ def test_upload_subcommand_propagates_exception(self): # interpreter's default behavior. If anyone wraps it later, # this test will fail and force the contract change to be # explicit. - import pfcon.copy_worker as cw - - with mock.patch.object(cw, 'do_upload', - side_effect=RuntimeError('boom')): - with mock.patch('sys.argv', - ['copy_worker', 'upload', '/tmp/nonexistent']): - with self.assertRaises(RuntimeError): - cw.main() + with ( + mock.patch.object(cw, 'do_upload', + side_effect=RuntimeError('boom')), + mock.patch('sys.argv', + ['copy_worker', 'upload', '/tmp/nonexistent']), + self.assertRaises(RuntimeError), + ): + cw.main() def test_delete_subcommand_propagates_exception(self): - import pfcon.copy_worker as cw - - with mock.patch.object(cw, 'do_delete', - side_effect=RuntimeError('boom')): - with mock.patch('sys.argv', - ['copy_worker', 'delete', '/tmp/nonexistent']): - with self.assertRaises(RuntimeError): - cw.main() + with ( + mock.patch.object(cw, 'do_delete', + side_effect=RuntimeError('boom')), + mock.patch('sys.argv', + ['copy_worker', 'delete', '/tmp/nonexistent']), + self.assertRaises(RuntimeError), + ): + cw.main()