Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion pfcon/copy_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}, '

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ LOW RISK

Suggestion: Consider using logger.exception to ensure the full stack trace is captured in the logs before the worker exits, facilitating easier debugging of copy failures.

f'detail: {str(e)}')
sys.exit(1)
elif subcommand == 'upload':
do_upload(key_dir)
elif subcommand == 'delete':
Expand Down
35 changes: 28 additions & 7 deletions pfcon/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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, '

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Avoid exposing internal error details to the client to prevent information disclosure (e.g., internal paths). Additionally, use logger.exception instead of logger.error to ensure the full stack trace is captured in logs. This pattern should be corrected here and in subsequent error handlers (lines 509, 528, 545).

Suggested change
logger.error(f'Error fetching job {job_id} output data, '
logger.exception('Failed to retrieve storage data')
abort(500, message='An internal error occurred while retrieving job output.')

f'detail: {str(e)}')
abort(500, message=str(e))
download_name = f'{job_id}.json'
mimetype = 'application/json'

Expand All @@ -486,16 +491,22 @@ 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)

if self.storage_env == 'swift':
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'
Expand All @@ -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):
Expand All @@ -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')

Expand Down
25 changes: 22 additions & 3 deletions pfcon/storage/fslink_storage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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']
Expand All @@ -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')
Expand All @@ -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}
Expand Down
107 changes: 106 additions & 1 deletion tests/test_resources_fslink.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,18 @@
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

from pfcon.app import create_app
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):
Expand Down Expand Up @@ -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))
Loading