Skip to content
Tutorials Center
My learning

Topics

Lesson 33 of 133 ยท File System

Paths, Permissions and Safe File Handling

Handle files safely in Node.js - file modes and chmod, symlinks, path traversal attacks and how to block them, os.tmpdir and mkdtemp, cleanup with finally, sanitizing filenames and the permission model.

Reading and writing files is easy. Doing it safely is the part that separates a toy from a service people can trust. As soon as a file name, a folder or a path comes from outside your program (an upload, a URL, a form field, a command-line argument, an archive), attackers and accidents can use it to reach files you never meant to expose. A server that returns /uploads/ + name can be tricked into returning /etc/passwd. A temporary file with a predictable name can be replaced by someone else. A file created with permissive access can leak secrets.

This lesson covers the file-system safety toolkit: Unix-style permission bits and chmod, symbolic links, path traversal attacks and a correct defence, temporary files and directories, guaranteed cleanup with finally, sanitizing user-supplied filenames, and Node.js's built-in permission model. You will want to know the path functions from The os and path Modules and the file operations from the previous lessons in this chapter.

File modes and chmod

On Linux and macOS every file has a mode: three groups of permission bits (owner, group, everyone else), each allowing read (4), write (2) and execute (1). They are normally written in octal. 0o644 means owner read+write (6), group read (4), others read (4). 0o600 means only the owner can read and write, which is right for private keys and tokens. 0o755 is typical for programs and directories.

You can set the mode when creating a file (mode option) and change it later with chmod. The effective mode at creation is reduced by the process's umask, which usually removes group and other write bits.

Node.js Reading and changing file modes

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notes on modes:

  • mode & 0o777 keeps only the permission bits; the higher bits of stat().mode describe the file type.
  • On Windows most of this does not exist. chmod can only toggle the read-only flag, and the mode reported by stat is an approximation. Never rely on mode bits for security on Windows. Our sandbox runs on Linux; your results on a Windows machine will differ.
  • For a directory, "read" means listing the names, "write" means creating and deleting entries, and "execute" means entering it and accessing the entries inside.
  • Create sensitive files with the restrictive mode from the very start ({ mode: 0o600 }). Writing first and calling chmod later leaves a window where the data is readable by others.
  • If a process is not allowed to do something, it fails with EACCES or EPERM. Test for it by trying, not by calling access first (that is a TOCTOU race, see Sync, Callback and Promise APIs).

A symbolic link (symlink) is a tiny file that contains a path to another file. Opening the link opens the target. Links are useful (versioned release folders, shared config), but they are a security risk for any code that checks a path and then uses it, because the path you checked may not be where you end up.

Node.js What symlinks do to your checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The path looks like it lives in public, and a naive check says yes. fs.realpath resolves every link and returns the true location, which is outside. Whenever a security decision depends on where a path really points, compare real paths.

Path traversal

Path traversal (also called directory traversal) is one of the most common web vulnerabilities. A program builds a path from user input:

NODE
// DANGEROUS
const file = join('/srv/uploads', request.query.name);

If the user sends name=../../etc/passwd, join happily normalises the .. segments and the result is /etc/passwd. Variants include absolute paths (/etc/passwd, which resolve accepts and uses as is), URL-encoded dots (%2e%2e%2f, check after decoding), Windows backslashes and drive letters, and null bytes. Let us see the problem and the standard fix.

Node.js A vulnerable file server and the fix

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

(The example imports node:path/posix so that the output is the same on every operating system; in your code import plain node:path.)

Look at the last attempt carefully: ../uploads-evil/x resolves to /srv/uploads-evil/x, which starts with the text /srv/uploads. A check with full.startsWith(ROOT) alone would wrongly allow it. That is why the correct check compares against ROOT + sep, with the separator, or uses path.relative:

NODE
const rel = relative(ROOT, full);
const inside = rel !== '' && !rel.startsWith('..') && !isAbsolute(rel);

Rules for path-safe code:

  1. Resolve first, check second. Always resolve(root, input) and then verify the result.
  2. Decode before you check. If your framework decodes URLs, check after decoding, never before.
  3. Check real paths if symlinks could exist inside the root (realpath both root and target).
  4. Reject, don't repair. Stripping ../ from input is error-prone (....// becomes ../ after one pass). Throw an error instead.
  5. Prefer ids to names. Store uploads under generated ids (<uuid>.png) and keep the original name in a database. Then user input never touches a path.
  6. Least privilege. Run the process as a user that can only write the folders it needs.

Temporary files and directories

Programs need scratch space: partial downloads, test fixtures, extracted archives. Two mistakes are common: choosing a predictable name such as /tmp/output.txt (another user can create it first, or plant a symlink named that, so you overwrite a different file), and forgetting to delete the files.

  • os.tmpdir() returns the system temporary directory (/tmp on Linux).
  • fs.mkdtemp(prefix) creates a new, unique directory by appending six random characters to the prefix, with mode 0o700 on POSIX systems. Nobody else can guess it or write into it.
  • Inside that directory you can use simple file names.
Node.js mkdtemp for private scratch space

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The exact path and random suffix differ on every run and every machine, so the example prints only properties that are stable. The mode check prints 700 on Linux and macOS.

Cleanup with finally

Cleanup code must run on the failure path too, otherwise every error leaves another temporary directory behind. The tool for that is try / finally: the finally block runs whether the try block succeeds, throws, or returns early.

Node.js Guaranteed cleanup with finally

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The helper withTempDir is a small, reusable pattern: acquire a resource, give it to a function, release it in finally. Modern Node.js (24 and later) also supports await using with disposable objects for the same purpose, introduced in Modern JavaScript You Need.

A few more points:

  • finally does not run if the process is killed (SIGKILL) or crashes hard. Temporary directories in os.tmpdir() are eventually cleaned by the operating system, which is one more reason to keep them there rather than in your project folder.
  • If the cleanup itself may fail, make it harmless (force: true) so it does not hide the original error.
  • To remove files on shutdown signals, see The process Object and Graceful Shutdown and Health Checks.

Sanitizing user-supplied filenames

Sometimes you must keep part of a name given by a user, for example a download called report.pdf. A filename is data, not a path, so reduce it to a safe form. A conservative sanitiser:

  1. Takes only the last path segment (basename), so no directory part survives, for both / and \.
  2. Normalises Unicode and removes control characters and null bytes.
  3. Replaces everything outside a small allowed set (letters, digits, dot, dash, underscore) with _.
  4. Rejects names that are empty, only dots, or reserved on Windows (CON, NUL, COM1...).
  5. Limits the length (255 bytes is the usual file system limit).
  6. Optionally adds a unique prefix, so two uploads called report.pdf do not collide.
Node.js A filename sanitiser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Notice that rรฉsumรฉ.docx becomes r_sum_.docx: an allow-list is blunt. If your users write in many languages, you can allow Unicode letters (\p{L}\p{N}) in the stored name, or better, store the file under a generated id and keep the original name only as metadata to show to users and send in a Content-Disposition header (which has its own encoding rules). Never use the sanitised name for deciding the file type; check the content instead.

The Node.js permission model

Everything so far protects you from mistakes in your code. What about a dependency or a script you did not write? Node.js has a permission model (the --permission flag, called --experimental-permission in older releases; check the documentation of your version for its stability status). When enabled, a process can access nothing by default and must be granted access explicitly:

Terminal
# Read-only example: command line on your machine, not runnable in our editor
node --permission --allow-fs-read=/app --allow-fs-write=/app/tmp server.js

Under this model, readFile('/etc/passwd') throws an error with code ERR_ACCESS_DENIED, even if the operating system user could read the file. Other flags control --allow-child-process, --allow-worker, --allow-addons and --allow-wasi. You can query the current state at runtime with process.permission.has('fs.read', '/some/path') when the model is on.

NODE
// Read-only: only meaningful when started with --permission
if (process.permission && !process.permission.has('fs.write', './out')) {
  console.error('This process may not write to ./out');
  process.exit(1);
}

What it is and what it is not:

  • It is a defence in depth layer for running less-trusted code, for example your build scripts or a CLI with many dependencies. It limits damage when something is compromised.
  • It is not a sandbox against malicious native code or a vulnerable Node.js itself; use containers and operating-system users for that.
  • It does not replace path traversal checks: inside the allowed folder, a traversal bug can still expose other files in it.
  • It cannot be shown in our editor, because the run command is fixed, so check the documentation of your Node.js version for the current list of flags.

Putting it together: a safe upload store

A final example ties the pieces together. It stores "uploads" under generated ids with restrictive modes, resolves names defensively, and cleans up.

Node.js A small safe file store

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

The user's name never reaches the file system: files are named by random ids that match a strict pattern, so traversal is impossible by construction. The extra resolve check is a second layer, because defence in depth means a single mistake does not become a vulnerability.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the mode 0o600 mean for a file on Linux?

    6 is read (4) plus write (2) for the owner; the two zeros remove all access for group and others. It is the right mode for secrets.
  2. 2. A server does join('/srv/uploads', name) with name = '../../etc/passwd'. What is the result?

    path.join collapses '..' segments, so the path escapes the folder. You must verify that the resolved path is still inside the root.
  3. 3. Why is full.startsWith('/srv/uploads') alone a flawed check?

    Compare against the root plus a separator, or use path.relative, so that sibling folders with a common prefix are rejected.
  4. 4. Which function creates a unique, private temporary directory?

    mkdtemp appends random characters and creates the directory with restrictive permissions, so names cannot be guessed or pre-created by others.
  5. 5. Why put cleanup code in a finally block?

    finally runs on both the success and the failure path, so resources are released even when an error occurs.

Summary

  • Permission bits (0o600, 0o644, 0o755) control access on POSIX systems; create sensitive files with the right mode from the start. Windows largely ignores them.
  • Symlinks can make a path point elsewhere; use lstat to detect them and realpath before security decisions.
  • Path traversal: never join user input to a path without resolve plus a check that the result is inside the root, using root + sep or path.relative. Reject bad input instead of trying to repair it.
  • Prefer generated ids over user-supplied names; when you must keep a name, sanitise it with an allow-list.
  • Use mkdtemp under os.tmpdir() for private scratch space, and release it with try/finally.
  • The --permission model limits what a Node.js process may touch; it is defence in depth, not a complete sandbox.

Next: Streams Fundamentals