Repository navigation
Fail fast on unsanitized plugin output in FSLinkStorage - #177
Conversation
Not up to standards ⛔🔴 Issues
|
| Category | Results |
|---|---|
| Security | 3 medium |
🟢 Metrics 38 complexity · 5 duplication
Metric Results Complexity 38 Duplication 5
AI Reviewer: first review requested successfully. AI can make mistakes. Always validate suggestions.
TIP This summary will be updated as you push new changes.
There was a problem hiding this comment.
Pull Request Overview
While the pull request is generally up to standards according to Codacy, there is a significant logic gap in the sanitization routine within FSLinkStorage.get_data(). The current implementation only inspects the 'files' list provided by os.walk, allowing directory-level symlinks to bypass security checks and persist in the output.
Additionally, several acceptance criteria related to fail-fast behavior in the API resources and the copy worker appear unaddressed or unverified, specifically regarding the HTTP 500 status codes on cleanup failure and the worker's exit status. There is also a recurring pattern of returning raw exception strings to API clients, which poses an information disclosure risk.
About this PR
- The sanitization logic in FSLinkStorage is incomplete. By only iterating over the 'files' list from os.walk, the system will fail to detect or remove symlinks that point to directories. These symlinks are categorized in the 'dirs' list and must be explicitly handled to prevent directory traversal or unauthorized data access.
1 comment outside of the diff
pfcon/storage/fslink_storage.py
line 91🔴 HIGH RISK
The current sanitization only checksfiles, which bypasses symbolic links that resolve to directories as these appear indirsduring anos.walk. To ensure the 'fail fast' and sanitization goals are met, bothdirsandfilesmust be checked. For any entry that is a symbolic link or ends with.chrislink, remove it. If a symlink is found indirs, it should also be removed from the list to preventos.walkfrom descending into it.
Test suggestions
- FSLinkStorage correctly removes unauthorized .chrislink files during output walk.
- FSLinkStorage correctly identifies and deletes symlinks pointing to external locations.
- FSLinkStorage propagates OSError when file/link removal fails (fast-fail).
- PluginJobFile resource returns 500 status when FSLinkStorage raises an exception during cleanup.
- Copy worker exits with status 1 when an exception is caught during the copy subcommand.
Prompt proposal for missing tests
Consider implementing these tests if applicable:
1. PluginJobFile resource returns 500 status when FSLinkStorage raises an exception during cleanup.
2. Copy worker exits with status 1 when an exception is caught during the copy subcommand.
TIP Improve review quality by adding custom instructions
TIP How was this review? Give us feedback
| 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, ' |
There was a problem hiding this comment.
🟡 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).
| 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.') |
| try: | ||
| do_copy(key_dir) | ||
| except Exception as e: | ||
| logger.error(f'Copy worker failed for {key_dir}, ' |
There was a problem hiding this comment.
⚪ 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.
|
|
| 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() |
There was a problem hiding this comment.
could this be grouped into a single with statement using parenthesis?
There was a problem hiding this comment.
@milesbeyond I prefer the nested syntax since it makes it easier (at least to me) to determine which one enters first and exits first. But since it's not a big deal (I'm just probably used to the nested one and just need to get used to the flattened one) I've just pushed a change flattening the with statements.
| 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() |
1. Background
FSLinkStorage.get_data()runs after a plugin container finishes and walks the job's output directory to build the metadata payload returned to CUBE. Two cleanup steps live in that walk:.chrislinkfile the plugin produced — ChRIS links may only be authored by upstream CUBE.Both steps had a security gap. The
.chrislinkremoval swallowedOSError, logging and continuing; that could leave an attacker-controlled link physically present in shared storage while pfcon still returned successful output metadata to CUBE. Also symlinks were silently ignored rather than deleted, so a plugin could leave a symlink to anywhere on the mounted filesystem in its output directory.CUBE's
plugininstances/services/pluginjobs.py::_register_output_files()already treats this as fatal —delete_objfailure on an unauthorized link file raises and cancels the job. This change brings pfcon into line with that contract.2. Changes
2.1
pfcon/storage/fslink_storage.py.chrislinkremoval now re-raisesOSErrorafter logging. The job fails rather than reporting success with a tainted output dir.os.remove()unlinks the symlink itself, never the target.2.2
pfcon/resources.pyWrapped all three previously-unguarded output-fetch callsites in
PluginJobFile.get():fslink/filesystemstorage.get_data(...)logger.error+abort(500)swift/s3storage.get_output_metadata(...)logger.error+abort(500)zipfile(out-of-network)storage.get_data(...)logger.error+abort(500)500 status code is used because the failure is server-side integrity, not a client error. CUBE's
pfconclientraisesPfconRequestExceptionon 5xx, whichpluginjobs.pyalready handles by assigningCODE03and cancelling the plugin instance — exactly the outcome we want for an unsanitizable output dir.2.3
pfcon/copy_worker.pyWrapped the
copysubcommand inmain()withtry / except Exception→logger.error(...)+sys.exit(1). Previously any exception became an unhandled traceback; the downstream behavior was correct (non-zero exit → compute manager reportsfinishedWithError→ CUBE refuses to schedule the plugin job), but now it's explicit and produces a clean single-line error.Added
TestFSLinkStorageGetDataSanitization— aTestCasethat exercisesFSLinkStorage.get_data()directly against atempfile.mkdtemp()outgoing dir. No containers required; runs in well under a second.3. Reviewer notes
.chrislinkfiles and no symlinks sees exactly the same response as before.copy_worker.pywas strictly speaking unaffected by the bug (the new exception surface is only inget_data), but the new explicittry / sys.exit(1)improves worker-container observability and was added at the same time.