Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
6 changes: 5 additions & 1 deletion pfcon/copy_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,11 @@ def main():
key_dir = args[0]

if subcommand == 'copy':
do_copy(key_dir)
try:
do_copy(key_dir)
except Exception:
logger.exception(f'Copy worker failed for {key_dir}')
sys.exit(1)
elif subcommand == 'upload':
do_upload(key_dir)
elif subcommand == 'delete':
Expand Down
43 changes: 36 additions & 7 deletions pfcon/resources.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -474,8 +475,14 @@ 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 HTTPException:
raise
except Exception as 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'

Expand All @@ -486,16 +493,24 @@ 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 HTTPException:
raise
except Exception as e:
logger.exception(f'Error fetching job {job_id} output '
f'metadata')
abort(500, message=str(e))

download_name = f'{job_id}.json'
mimetype = 'application/json'
Expand All @@ -509,7 +524,14 @@ 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 HTTPException:
raise
except Exception as 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)
if not os.path.isdir(job_dir):
Expand All @@ -521,7 +543,14 @@ 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 HTTPException:
raise
except Exception as 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')

Expand Down
63 changes: 51 additions & 12 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
symlink found in the outgoing directory is also removed.
"""
fs_rel_file_paths = []
job_output_path = kwargs['job_output_path']
Expand All @@ -92,28 +93,66 @@ 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'):
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)}')
self._unlink_or_fail(local_file_path, job_id,
entity='.chrislink file',
policy_plural='ChRIS links')
continue

if os.path.islink(local_file_path):
self._unlink_or_fail(local_file_path, job_id,
entity='symlink',
policy_plural='symlinks')
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}
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.
Expand Down
Loading
Loading