Skip to content

🛡️ Sentinel: [improvement] Pre-canonicalize base path in FileSystemContext to avoid symlink escapes#245

Open
bashandbone wants to merge 1 commit into
mainfrom
sentinel/canonicalize-base-path-17483386213109417647
Open

🛡️ Sentinel: [improvement] Pre-canonicalize base path in FileSystemContext to avoid symlink escapes#245
bashandbone wants to merge 1 commit into
mainfrom
sentinel/canonicalize-base-path-17483386213109417647

Conversation

@bashandbone
Copy link
Copy Markdown
Contributor

@bashandbone bashandbone commented May 19, 2026

🚨 Severity: MEDIUM
💡 Vulnerability: FileSystemContext::new previously accepted an uncanonicalized base path. When validating paths against a sandbox, an uncanonicalized base path can lead to symlink traversal bypasses if the base path itself contains symlinks that resolve unexpectedly compared to the target path.
🎯 Impact: Potential path traversal or symlink escapes during file system sandbox validation in the service layer, although practically limited by whether the base path is user-controlled.
🔧 Fix: Changed FileSystemContext::new to return a ServiceResult<Self> and explicitly canonicalize() the base path at creation time, guaranteeing an absolute, symlink-free sandbox root for all subsequent secure_path checks. Updated usage in tests to handle the Result.
Verification: Verified by running the existing test_file_system_context_security suite and unit tests (cargo test -p thread-services), ensuring all security checks and standard usages still operate as intended.


PR created automatically by Jules for task 17483386213109417647 started by @bashandbone

Summary by Sourcery

Canonicalize the base path used by FileSystemContext at construction time to harden sandboxed path validation against symlink-based escapes.

Bug Fixes:

  • Ensure FileSystemContext always uses a canonicalized, absolute base path to prevent potential symlink traversal escapes during secure_path checks.

Enhancements:

  • Update FileSystemContext::new to return a ServiceResult and adjust call sites to handle potential construction failures.

Documentation:

  • Add a Sentinel security note documenting the FileSystemContext base path canonicalization change and its rationale.

The `FileSystemContext` accepted an uncanonicalized `base_path` in its
constructor. This could potentially allow symlink escapes during path
validation inside `secure_path`. By changing the constructor to return
a `ServiceResult<Self>` and canonicalizing the base path on creation, we
ensure the base sandbox path is absolute and free of symlinks before any
further validation takes place. Downstream consumers such as tests have
been updated to handle the `Result`.

Co-authored-by: bashandbone <89049923+bashandbone@users.noreply.github.com>
Copilot AI review requested due to automatic review settings May 19, 2026 17:43
@google-labs-jules
Copy link
Copy Markdown
Contributor

👋 Jules, reporting for duty! I'm here to lend a hand with this pull request.

When you start a review, I'll add a 👀 emoji to each comment to let you know I've read it. I'll focus on feedback directed at me and will do my best to stay out of conversations between you and other bots or reviewers to keep the noise down.

I'll push a commit with your requested changes shortly after. Please note there might be a delay between these steps, but rest assured I'm on the job!

For more direct control, you can switch me to Reactive Mode. When this mode is on, I will only act on comments where you specifically mention me with @jules. You can find this option in the Pull Request section of your global Jules UI settings. You can always switch back!

New to Jules? Learn more at jules.google/docs.


For security, I will only act on instructions from the user who triggered this task.

@sourcery-ai
Copy link
Copy Markdown
Contributor

sourcery-ai Bot commented May 19, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Canonicalizes the FileSystemContext base path at construction time, changing its constructor to return a ServiceResult and updating tests and sentinel documentation accordingly to harden against symlink-based path traversal.

File-Level Changes

Change Details Files
Make FileSystemContext::new canonicalize the base path and return a ServiceResult to prevent symlink escape issues.
  • Change FileSystemContext::new signature to return ServiceResult instead of Self.
  • Canonicalize the provided base path inside FileSystemContext::new using Path::canonicalize, storing the resolved absolute path as base_path.
  • Propagate canonicalization errors via the ServiceResult error path rather than constructing a context with an invalid base path.
crates/services/src/lib.rs
Adjust tests and integration usage to handle the new fallible FileSystemContext::new constructor.
  • Update test_file_system_context_security to unwrap the Result from FileSystemContext::new when constructing the context.
  • Update the thread integration test that checks service re-exports to unwrap the Result from FileSystemContext::new so the test still compiles and runs.
crates/services/src/lib.rs
crates/thread/tests/integration.rs
Document the security fix and lessons learned in the Sentinel journal.
  • Add a sentinel entry describing the symlink escape vulnerability due to uncanonicalized base paths.
  • Record the mitigation of canonicalizing the base path during FileSystemContext construction and the general prevention guideline.
.jules/sentinel.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 2 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="crates/services/src/lib.rs" line_range="145-146" />
<code_context>
-        Self {
-            base_path: base_path.as_ref().to_path_buf(),
-        }
+    pub fn new<P: AsRef<Path>>(base_path: P) -> ServiceResult<Self> {
+        let canonical_base = base_path.as_ref().canonicalize()?;
+        Ok(Self {
+            base_path: canonical_base,
</code_context>
<issue_to_address>
**issue:** Canonicalizing the base path in `new` may reject otherwise valid configurations where the directory is created later.

This constructor now requires the directory to pre-exist, so callers can’t create a context for a path that will be created later. If that scenario should remain supported, consider either delaying canonicalization until first use, or eagerly creating the directory (e.g., via `create_dir_all`) before canonicalizing, depending on the intended invariants.
</issue_to_address>

### Comment 2
<location path="crates/services/src/lib.rs" line_range="146" />
<code_context>
-            base_path: base_path.as_ref().to_path_buf(),
-        }
+    pub fn new<P: AsRef<Path>>(base_path: P) -> ServiceResult<Self> {
+        let canonical_base = base_path.as_ref().canonicalize()?;
+        Ok(Self {
+            base_path: canonical_base,
</code_context>
<issue_to_address>
**suggestion:** Consider enriching the error from `canonicalize()` with path context for easier debugging and observability.

Using `?` here returns the bare `canonicalize` error, which can be hard to trace. Consider wrapping it (e.g. via a custom error variant or `map_err` that includes the `base_path`) so callers can see which base path failed when constructing different `FileSystemContext` roots.

Suggested implementation:

```rust
    pub fn new<P: AsRef<Path>>(base_path: P) -> ServiceResult<Self> {
        let canonical_base = base_path
            .as_ref()
            .canonicalize()
            .map_err(|e| {
                std::io::Error::new(
                    e.kind(),
                    format!(
                        "failed to canonicalize base path '{}': {}",
                        base_path.as_ref().display(),
                        e
                    ),
                )
            })?;
        Ok(Self {
            base_path: canonical_base,
        })
    }

```

If `ServiceResult` does not currently accept `std::io::Error` via `From<std::io::Error>`, you will need to:
1. Ensure the error type used by `ServiceResult` implements `From<std::io::Error>` (or adjust the `map_err` to construct the appropriate service-specific error variant instead of `std::io::Error::new`).
2. Optionally, if you already use a custom error type with richer context (e.g. via `thiserror` or `anyhow::Context`), replace the `std::io::Error::new(...)` construction with your existing pattern while keeping the `base_path.as_ref().display()` information in the message.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines +145 to +146
pub fn new<P: AsRef<Path>>(base_path: P) -> ServiceResult<Self> {
let canonical_base = base_path.as_ref().canonicalize()?;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

issue: Canonicalizing the base path in new may reject otherwise valid configurations where the directory is created later.

This constructor now requires the directory to pre-exist, so callers can’t create a context for a path that will be created later. If that scenario should remain supported, consider either delaying canonicalization until first use, or eagerly creating the directory (e.g., via create_dir_all) before canonicalizing, depending on the intended invariants.

base_path: base_path.as_ref().to_path_buf(),
}
pub fn new<P: AsRef<Path>>(base_path: P) -> ServiceResult<Self> {
let canonical_base = base_path.as_ref().canonicalize()?;
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

suggestion: Consider enriching the error from canonicalize() with path context for easier debugging and observability.

Using ? here returns the bare canonicalize error, which can be hard to trace. Consider wrapping it (e.g. via a custom error variant or map_err that includes the base_path) so callers can see which base path failed when constructing different FileSystemContext roots.

Suggested implementation:

    pub fn new<P: AsRef<Path>>(base_path: P) -> ServiceResult<Self> {
        let canonical_base = base_path
            .as_ref()
            .canonicalize()
            .map_err(|e| {
                std::io::Error::new(
                    e.kind(),
                    format!(
                        "failed to canonicalize base path '{}': {}",
                        base_path.as_ref().display(),
                        e
                    ),
                )
            })?;
        Ok(Self {
            base_path: canonical_base,
        })
    }

If ServiceResult does not currently accept std::io::Error via From<std::io::Error>, you will need to:

  1. Ensure the error type used by ServiceResult implements From<std::io::Error> (or adjust the map_err to construct the appropriate service-specific error variant instead of std::io::Error::new).
  2. Optionally, if you already use a custom error type with richer context (e.g. via thiserror or anyhow::Context), replace the std::io::Error::new(...) construction with your existing pattern while keeping the base_path.as_ref().display() information in the message.

Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

This PR hardens the services-layer filesystem sandboxing by ensuring FileSystemContext is constructed with a canonicalized (absolute, symlink-resolved) base path, reducing the risk of symlink-based sandbox escapes during subsequent path validation.

Changes:

  • Make FileSystemContext::new fallible (ServiceResult<Self>) and canonicalize base_path at construction time.
  • Update affected tests to handle the new Result-returning constructor.
  • Add a Sentinel learning note describing the vulnerability and prevention guidance.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 2 comments.

File Description
crates/services/src/lib.rs Canonicalizes filesystem sandbox base path during FileSystemContext construction and updates the related unit test call site.
crates/thread/tests/integration.rs Updates integration test to unwrap the new fallible FileSystemContext::new API.
.jules/sentinel.md Adds a short security learning note documenting the change and rationale.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

base_path: base_path.as_ref().to_path_buf(),
}
pub fn new<P: AsRef<Path>>(base_path: P) -> ServiceResult<Self> {
let canonical_base = base_path.as_ref().canonicalize()?;
Comment thread .jules/sentinel.md
Comment on lines +1 to +4
## 2024-05-20 - Pre-canonicalize base path in FileSystemContext to avoid symlink escapes
**Vulnerability:** The `FileSystemContext::new` accepted an uncanonicalized base path, which could potentially lead to symlink escapes during path validation.
**Learning:** By canonicalizing the base path during construction, the check inside `secure_path` accurately determines if the target escapes the expected path, which wasn't fully guaranteed with an uncanonicalized base path.
**Prevention:** Always construct secure contexts with canonicalized paths when implementing file path validation checks, especially to prevent symlink traversal.
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.

2 participants