← Back to Pull requests

fix(compilers): jail Fe source writes to the compilation temp dir #2933

Merged
SashaMIT merged 3 files (89 lines) on Aug 19, 2026 09:58 UTC
View on GitHub
SashaMIT SashaMIT commented on Aug 19, 2026 08:02 UTC
Author

Summary

useFeCompiler wrote path.join(tmpDir, sourcePath). A Fe verify body whose source keys start with src/ (the API prefix check) can still be src/../../../tmp/..., which path.join treats as a write outside the temp ingot.

The attacker already controls stdJsonInput.sources keys on the public verify API. The src/ prefix does not dominate ...

Jail is resolve-under-dir fail-closed in @ethereum-sourcify/compilers (covers library callers) and the same class is rejected in validateAndNormalizeFeInput.

Test plan

  • mocha --grep 'escape|resolve Fe source' in packages/compilers (2/2)

  • Revert-tested: without the prefix check, Should resolve Fe source paths under the compilation directory fails (expected [Function] to throw)
  • Made with Cursor

    Diff: 89 lines (+88 / -1) across 3 files Reviewer: manuelwedler Review duration: 115m
    All Vouch review confidence checks passed
    Residual risk 0.02 = Change Risk (0.38) × (1 − Review Confidence (0.94)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.38 · 89 lines diff across 3 files
    0.38
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.97 · 5 substantive comment(s)
    0.97
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 50%
    93%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.269
    Ai Authored ai_authored
    0.050
    Real PR Conversation Timeline
    12 items
    manuelwedler manuelwedler commented on code on Aug 19, 2026 09:10 UTC
    Code Review
    packages/compilers/src/lib/feCompiler.ts:1
    @@ -139,6 +172,13 @@ export async function useFeCompiler(
         throw new Error('Fe compiler is not supported on this machine.');
       }
     
    +  // Fail closed before downloading the binary. Public verify accepts Fe
    +  // source keys; the API src/ prefix check does not stop src/../...
    +  assertFeSourcesStayInside(
    +    path.resolve(os.tmpdir(), 'sourcify-fe-jail-root'),
    +    feJsonInput.sources,
    +  );

    Remove this pre-check and the helper assertFeSourcesStayInside. The reasons:

    1. The check in the write loop is sufficient. It stops the compilation before the code writes one byte.
    2. Escape detection for a relative key does not change with the root directory. Thus this call cannot find a problem that the loop does not find.
    3. The root sourcify-fe-jail-root does not exist. It is not the real tmpDir. This can confuse the reader.

    The pre-check only moves the error before getFeExecutable. But the binary is in the cache after the first download. If an early error is important: create the temp directory first, then do the check on the real tmpDir.

    ---
    _Generated by Claude Code_

    manuelwedler manuelwedler commented on code on Aug 19, 2026 09:10 UTC
    Code Review
    packages/compilers/src/lib/feCompiler.ts:1
    @@ -16,6 +16,39 @@ import type { JsonFragment } from 'ethers';
     const HOST_FE_REPO = 'https://github.com/argotorg/fe/releases/download/';
     const MINIMUM_FE_VERSION = '26.0.0-alpha.12';
     
    +/**
    + * Resolve a Fe source key under `root`. `path.join` treats an absolute
    + * segment as a new root, and `src/../..` walks out of the temp ingot.
    + */
    +export function resolveFeSourcePath(root: string, sourcePath: string): string {
    +  if (sourcePath.includes('\0')) {
    +    throw new Error(`Fe source path contains a null byte: ${sourcePath}`);
    +  }
    +  if (path.isAbsolute(sourcePath)) {
    +    throw new Error(`Fe source path must be relative: ${sourcePath}`);
    +  }
    +  const resolved = path.resolve(root, sourcePath);
    +  const rootResolved = path.resolve(root);
    +  const prefix = rootResolved.endsWith(path.sep)
    +    ? rootResolved
    +    : rootResolved + path.sep;
    +  if (resolved !== rootResolved && !resolved.startsWith(prefix)) {

    The condition resolved !== rootResolved permits a key that resolves to the root itself. Example: src/...

    The middleware also permits this key. There, the key normalizes to .. That value is not absolute and does not start with ...

    The result: fs.writeFile(tmpDir) fails with a raw EISDIR error, not with a clear validation error.

    A source key must point to a file inside the root. Reject the equal path also:

    if (!resolved.startsWith(prefix)) {
    

    ---
    _Generated by Claude Code_

    manuelwedler manuelwedler commented on code on Aug 19, 2026 09:10 UTC
    Code Review
    services/server/src/server/apiv2/middlewares.ts:1
    @@ -250,6 +251,30 @@ export function validateAndNormalizeFeInput(
         req.body.stdJsonInput = { ...stdJsonInput, sources: normalized };
       }
     
    +  // Prefix check alone does not stop src/../... path.join on the compiler
    +  // treats that as a write outside the temp ingot.
    +  const jailedSources = req.body.stdJsonInput.sources as Record<
    +    string,
    +    { content: string }
    +  >;
    +  for (const sourcePath of Object.keys(jailedSources)) {
    +    if (sourcePath.includes("\0")) {
    +      throw new InvalidParametersError(
    +        "Fe source paths must not contain a null byte.",
    +      );
    +    }
    +    const normalized = path.posix.normalize(sourcePath.replace(/\\/g, "/"));
    +    if (
    +      path.posix.isAbsolute(normalized) ||
    +      normalized === ".." ||
    +      normalized.startsWith("../")
    +    ) {
    +      throw new InvalidParametersError(
    +        "Fe source paths must stay under the compilation directory.",
    +      );
    +    }
    +  }

    This block is not necessary for the fix. The jail in useFeCompiler stops the write in all cases. But this block gives a clean 400 error at request time, not a failed verification job. Keep it for that behavior. Remove it for the smallest diff.

    If the block stays, two points:

    1. The rules here are different from resolveFeSourcePath. This check changes \ to / and normalizes the path. The compiler jail does not. Thus the two layers accept different key sets. Example: src/.. passes here, but causes an fs error in the compiler (see the comment there). The server has @ethereum-sourcify/compilers as a direct dependency, and the PR exports resolveFeSourcePath. Use the same rules in the two places, or add a comment that says the middleware is more strict.
    2. The comment text is not clear: "does not stop src/../... path.join on the compiler treats that as". Add the missing sentence break. Also, this loop uses the name normalized again. The block above uses the same name for the sources record. The two scopes are separate, but one name with two meanings in one function decreases readability.

    ---
    _Generated by Claude Code_

    manuelwedler manuelwedler commented on code on Aug 19, 2026 09:11 UTC
    Code Review
    packages/compilers/test/feCompiler.spec.ts:1
    @@ -41,6 +44,50 @@ describe('Verify Fe Compiler', () => {
         }
       });
     
    +  it('Should reject source paths that escape the temp compilation directory', async () => {
    +    const marker = path.join(os.tmpdir(), 'sourcify-fe-escape-probe');
    +    try {
    +      fs.unlinkSync(marker);
    +    } catch {
    +      undefined;
    +    }
    +
    +    let thrown: unknown;
    +    try {
    +      await useFeCompiler(feRepoPath, version, {
    +        language: 'Fe',
    +        settings: {},
    +        sources: {
    +          'src/../../../tmp/sourcify-fe-escape-probe': {
    +            content: 'pwned',
    +          },
    +        },
    +      });
    +    } catch (error) {
    +      thrown = error;
    +    }
    +
    +    expect(thrown, 'expected the compilation to reject').to.be.instanceOf(
    +      Error,
    +    );
    +    expect((thrown as Error).message).to.include(
    +      'escapes the compilation directory',
    +    );
    +    expect(fs.existsSync(marker)).to.equal(false);

    The marker path and the injected key can point to different files. The key contains the fixed string /tmp/sourcify-fe-escape-probe. The marker value comes from os.tmpdir(). On macOS, os.tmpdir() is /var/folders/.... There, existsSync(marker) examines a different path, and the assertion passes without value.

    Also, the jail throws before the code writes a file. Thus the marker assertion shows intent more than it guards the write.

    Two possible corrections:

  • Make the traversal key from os.tmpdir(). Then the marker is the true write target.

  • Or remove the marker steps. Keep the assertion for the message "escapes the compilation directory". That assertion does the work, and the unit test below covers the same case again.
  • ---
    _Generated by Claude Code_

    SashaMIT SashaMIT commented on Aug 19, 2026 09:28 UTC
    Author

    Thanks for the review. You were right on all four.

    Dropped the fake-root pre-check. The write loop is the jail. resolveFeSourcePath now rejects keys that resolve to the root (src/..), so that is a validation error instead of EISDIR. Middleware keeps the 400-before-job behavior and now calls the same resolver. Removed the marker file from the compiler test.

    Pushed on a3c37c2.

    SashaMIT SashaMIT commented on code on Aug 19, 2026 09:29 UTC
    Code Review
    packages/compilers/src/lib/feCompiler.ts:1
    @@ -139,6 +172,13 @@ export async function useFeCompiler(
         throw new Error('Fe compiler is not supported on this machine.');
       }
     
    +  // Fail closed before downloading the binary. Public verify accepts Fe
    +  // source keys; the API src/ prefix check does not stop src/../...
    +  assertFeSourcesStayInside(
    +    path.resolve(os.tmpdir(), 'sourcify-fe-jail-root'),
    +    feJsonInput.sources,
    +  );

    Dropped. The write loop is the jail. No fake root.

    SashaMIT SashaMIT commented on code on Aug 19, 2026 09:29 UTC
    Code Review
    packages/compilers/src/lib/feCompiler.ts:1
    @@ -16,6 +16,39 @@ import type { JsonFragment } from 'ethers';
     const HOST_FE_REPO = 'https://github.com/argotorg/fe/releases/download/';
     const MINIMUM_FE_VERSION = '26.0.0-alpha.12';
     
    +/**
    + * Resolve a Fe source key under `root`. `path.join` treats an absolute
    + * segment as a new root, and `src/../..` walks out of the temp ingot.
    + */
    +export function resolveFeSourcePath(root: string, sourcePath: string): string {
    +  if (sourcePath.includes('\0')) {
    +    throw new Error(`Fe source path contains a null byte: ${sourcePath}`);
    +  }
    +  if (path.isAbsolute(sourcePath)) {
    +    throw new Error(`Fe source path must be relative: ${sourcePath}`);
    +  }
    +  const resolved = path.resolve(root, sourcePath);
    +  const rootResolved = path.resolve(root);
    +  const prefix = rootResolved.endsWith(path.sep)
    +    ? rootResolved
    +    : rootResolved + path.sep;
    +  if (resolved !== rootResolved && !resolved.startsWith(prefix)) {

    Agreed. src/.. now fails the prefix check, so it is a validation error instead of EISDIR.

    SashaMIT SashaMIT commented on code on Aug 19, 2026 09:29 UTC
    Code Review
    services/server/src/server/apiv2/middlewares.ts:1
    @@ -250,6 +251,30 @@ export function validateAndNormalizeFeInput(
         req.body.stdJsonInput = { ...stdJsonInput, sources: normalized };
       }
     
    +  // Prefix check alone does not stop src/../... path.join on the compiler
    +  // treats that as a write outside the temp ingot.
    +  const jailedSources = req.body.stdJsonInput.sources as Record<
    +    string,
    +    { content: string }
    +  >;
    +  for (const sourcePath of Object.keys(jailedSources)) {
    +    if (sourcePath.includes("\0")) {
    +      throw new InvalidParametersError(
    +        "Fe source paths must not contain a null byte.",
    +      );
    +    }
    +    const normalized = path.posix.normalize(sourcePath.replace(/\\/g, "/"));
    +    if (
    +      path.posix.isAbsolute(normalized) ||
    +      normalized === ".." ||
    +      normalized.startsWith("../")
    +    ) {
    +      throw new InvalidParametersError(
    +        "Fe source paths must stay under the compilation directory.",
    +      );
    +    }
    +  }

    Kept the 400 so a bad key never starts a job. It now calls resolveFeSourcePath, same rules as the write loop.

    SashaMIT SashaMIT commented on code on Aug 19, 2026 09:29 UTC
    Code Review
    packages/compilers/test/feCompiler.spec.ts:1
    @@ -41,6 +44,50 @@ describe('Verify Fe Compiler', () => {
         }
       });
     
    +  it('Should reject source paths that escape the temp compilation directory', async () => {
    +    const marker = path.join(os.tmpdir(), 'sourcify-fe-escape-probe');
    +    try {
    +      fs.unlinkSync(marker);
    +    } catch {
    +      undefined;
    +    }
    +
    +    let thrown: unknown;
    +    try {
    +      await useFeCompiler(feRepoPath, version, {
    +        language: 'Fe',
    +        settings: {},
    +        sources: {
    +          'src/../../../tmp/sourcify-fe-escape-probe': {
    +            content: 'pwned',
    +          },
    +        },
    +      });
    +    } catch (error) {
    +      thrown = error;
    +    }
    +
    +    expect(thrown, 'expected the compilation to reject').to.be.instanceOf(
    +      Error,
    +    );
    +    expect((thrown as Error).message).to.include(
    +      'escapes the compilation directory',
    +    );
    +    expect(fs.existsSync(marker)).to.equal(false);

    Removed the marker. The unit test now covers src/.. and the escape key, and those assertions do the work.

    manuelwedler manuelwedler approved these changes on Aug 19, 2026 09:58 UTC
    Approved Reviewer

    Looks good. Thanks for this finding!

    SashaMIT SashaMIT commented on Aug 19, 2026 10:27 UTC
    Author

    Thanks for the review and the merge. Glad the follow-up landed cleanly.

    Reviewers
    Assignees
    SashaMIT SashaMIT
    Labels
    risk: low confidence: 93.6% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 37.8% (MEDIUM) · Higher = larger blast radius
    37.8%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 93.6% · Lower = rushed or shallow review
    93.6%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 2.4% · Safe to merge
    2.4%