Skip to content

Fail fast on unsanitized plugin output in FSLinkStorage - #177

Merged
jbernal0019 merged 3 commits into
masterfrom
bug/deleting-link-files
May 29, 2026
Merged

jbernal0019 merged 3 commits into
masterfrom
bug/deleting-link-files

Conversation

@jbernal0019

Copy link
Copy Markdown
Contributor

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:

  1. Remove any .chrislink file the plugin produced — ChRIS links may only be authored by upstream CUBE.
  2. Skip symlinks when building the file list.

Both steps had a security gap. The .chrislink removal swallowed OSError, 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_obj failure 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

  • .chrislink removal now re-raises OSError after logging. The job fails rather than reporting success with a tainted output dir.
  • New branch deletes symlinks with the same fatal-on-failure policy. os.remove() unlinks the symlink itself, never the target.
  • Docstring updated to reflect the new symlink behavior.

2.2 pfcon/resources.py

Wrapped all three previously-unguarded output-fetch callsites in PluginJobFile.get():

Storage Method Action on failure
fslink / filesystem storage.get_data(...) logger.error + abort(500)
swift / s3 storage.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 pfconclient raises PfconRequestException on 5xx, which pluginjobs.py already handles by assigning CODE03 and cancelling the plugin instance — exactly the outcome we want for an unsanitizable output dir.

2.3 pfcon/copy_worker.py

Wrapped the copy subcommand in main() with try / except Exception → logger.error(...) + sys.exit(1). Previously any exception became an unhandled traceback; the downstream behavior was correct (non-zero exit → compute manager reports finishedWithError → CUBE refuses to schedule the plugin job), but now it's explicit and produces a clean single-line error.

Added TestFSLinkStorageGetDataSanitization — a TestCase that exercises FSLinkStorage.get_data() directly against a tempfile.mkdtemp() outgoing dir. No containers required; runs in well under a second.

3. Reviewer notes

  • No behavior change in the success path. A job that produces no .chrislink files and no symlinks sees exactly the same response as before.
  • copy_worker.py was strictly speaking unaffected by the bug (the new exception surface is only in get_data), but the new explicit try / sys.exit(1) improves worker-container observability and was added at the same time.
  • S3 and Swift storage do not have the reported issue because the plugin's execution output directory is tottaly isolated from ChRIS storage. which provides additional security guarantees.

@codacy-production

codacy-production Bot commented May 28, 2026 •

Copy link
Copy Markdown

Not up to standards ⛔

🔴 Issues 3 medium

Alerts:
⚠ 3 issues (≤ 0 issues of at least minor severity)

Results:
3 new issues

Category Results
Security 3 medium

View in Codacy

🟢 Metrics 38 complexity · 5 duplication

Metric Results
Complexity 38
Duplication 5

View in Codacy

AI Reviewer: first review requested successfully. AI can make mistakes. Always validate suggestions.

Run reviewer

TIP This summary will be updated as you push new changes.

@codacy-production codacy-production Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

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 checks files, which bypasses symbolic links that resolve to directories as these appear in dirs during an os.walk. To ensure the 'fail fast' and sanitization goals are met, both dirs and files must be checked. For any entry that is a symbolic link or ends with .chrislink, remove it. If a symlink is found in dirs, it should also be removed from the list to prevent os.walk from 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

Comment thread pfcon/resources.py Outdated
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.')

Comment thread pfcon/copy_worker.py Outdated
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.

@jbernal0019

Copy link
Copy Markdown
Contributor Author
  • Implemented dirs-pass before the files-pass. Closes the reported symlink-to-directory hole: iterates dirs, removes any os.path.islink(...) entry with os.remove() (POSIX unlink() on a symlink-to-dir removes the symlink, not the target), and mutates dirs[:] in place so os.walk cannot descend into anything removed.

  • Improved exception handling and increased tests' code coverage.

@jbernal0019

Copy link
Copy Markdown
Contributor Author

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

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
TIP Improve review quality by adding custom instructions TIP How was this review? Give us feedback

  • Implemented dirs-pass before the files-pass. Closes the reported symlink-to-directory hole: iterates dirs, removes any os.path.islink(...) entry with os.remove() (POSIX unlink() on a symlink-to-dir removes the symlink, not the target), and mutates dirs[:] in place so os.walk cannot descend into anything removed.

  • Improved exception handling and increased tests' code coverage.

@milesbeyond milesbeyond left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

syntax question

Comment thread tests/test_resources_fslink.py Outdated
Comment on lines +606 to +611
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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

could this be grouped into a single with statement using parenthesis?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@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.

Comment thread tests/test_resources_fslink.py Outdated
Comment on lines +633 to +638
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()

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

same question

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

@milesbeyond See my previous answer.

@jbernal0019
jbernal0019 merged commit b374613 into master May 29, 2026
4 of 5 checks passed
@jbernal0019
jbernal0019 deleted the bug/deleting-link-files branch May 29, 2026 21:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants