The permission model and hardening
Restricting what a Node process can touch with --permission, plus hardening basics for services: prototype pollution, ReDoS, helmet and non-root users.
The process objectHandling uncaught errors and rejectionsSecuring Node dependencies and the supply chain
The permission model and hardening
The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.
Not started
What you'll learn
- Node trusts the code it runs. The permission model (`--permission`) is a seat belt: it denies file system, child process, worker, addon and network access unless you grant it, so a mistake or a compromised dependency can do less.
- Grant what you need explicitly: `--allow-fs-read=<path>`, `--allow-fs-write=<path>`, `--allow-child-process`, `--allow-worker`, `--allow-addons`. A blocked operation throws `ERR_ACCESS_DENIED` with the permission name.
- The permission model is stable (since Node 22.13 and 23.5) and the flag is `--permission`. Network control, `--allow-net`, is still experimental in Node 26. Tutorials that say `--experimental-permission` are out of date.
- It is not a sandbox. The docs say it does not protect against malicious code, because code that can run can try to escape, so combine it with containers, least-privilege users and review.
- `--permission-audit` logs violations without blocking, which is a way to discover what a real application needs before enforcing.
- Prototype pollution happens when merging untrusted JSON into objects without filtering `__proto__`, `constructor` and `prototype`. ReDoS happens when a regex with nested quantifiers meets crafted input. Both turn small requests into big failures.
- Basic hardening for a service: `helmet` for response headers, input validation at the edge, no secrets in code or logs, and a process that runs as a non-root user.
Node trusts everything it runs
A Node process can read any file its user can read, write anywhere that user can write, spawn any program, open any socket, and load native code. That is convenient, and it means any code in the process, including that of every dependency from the previous lesson, inherits all of it. A bug that lets a user choose a file path becomes arbitrary file read. A compromised package becomes everything your user can do.
Other runtimes, notably Deno, ship permissions as a core design. Node added its own, which lets you start a process with less power than the user who launched it.
The permission model
node --permission app.js
With --permission, Node denies access to the file system, child processes, worker threads, native addons and the network, unless you grant each one. I ran this on Node 26 against a script that tried several things:
fs.readFileSync('data.txt'); // allowed: I granted this path
fs.readFileSync('secret.txt'); // denied
fs.writeFileSync('out.txt', 'x'); // denied
spawnSync('ls'); // denied
Run as node --permission --allow-fs-read=$PWD/p.mjs --allow-fs-read=$PWD/data.txt p.mjs, the first read worked, and the others threw ERR_ACCESS_DENIED, with the permission property naming FileSystemRead, FileSystemWrite and ChildProcess. Those are ordinary exceptions you can handle. Note the script itself had to be readable, since it is a file too.
The grants:
| Flag | Allows |
|---|---|
--allow-fs-read=<path> |
reading that path (repeatable, * wildcards allowed at the end) |
--allow-fs-write=<path> |
writing to that path |
--allow-child-process |
spawning processes |
--allow-worker |
worker threads |
--allow-addons |
native addons |
--allow-net |
network access (experimental) |
Your code can ask what it holds, with process.permission.has('fs.read', path). When I enabled --allow-child-process, Node printed SecurityWarning: The flag --allow-child-process must be used with extreme caution. It could invalidate the permission model. A child process is not bound by the parent’s permissions, so granting it undoes the rest.
Three details that outdate older tutorials:
- The flag is
--permission. Videos and blog posts from 2023 use--experimental-permission. The feature stopped being experimental in Node 22.13 and 23.5, and the Node 26 docs mark it stable. --allow-netis new and still experimental. I tested it against a local server:fetchfailed withERR_ACCESS_DENIEDwithout the flag, and worked with it, after printing anExperimentalWarning.- Audit mode exists.
node --permission-audit app.jsruns with no enforcement and reports what would have been denied through a diagnostics channel, which is how you work out the minimum grant list for a real application before turning enforcement on.
What it is not
Node’s documentation is blunt. The model is a “seat belt” that stops trusted code from accidentally touching things, and it “does not provide security guarantees in the presence of malicious code.” Code that is already running can look for ways around it, for example through allowed child processes or native addons. Use it to shrink the damage of bugs and path-traversal mistakes, and to make a script that should only read one folder unable to read anything else. Do not use it as a replacement for a container or a separate low-privilege user. The conference talk covers the design reasoning and trade-offs behind this, from the engineer who led it.
Prototype pollution
Hardening is more than flags. A classic Node-specific vulnerability starts with a helpful-looking function:
function merge(target, source) {
for (const key in source) {
if (typeof source[key] === 'object' && source[key] !== null) {
target[key] = merge(target[key] ?? {}, source[key]);
} else {
target[key] = source[key];
}
}
return target;
}
merge({}, JSON.parse('{"__proto__": {"isAdmin": true}}'));
console.log(({}).isAdmin); // true. Every object now has it.
JSON.parse creates an own property named __proto__. The merge then follows target['__proto__'], which is Object.prototype, and writes isAdmin onto it. Any later if (user.isAdmin) check on any object passes. I ran this and printed true. The fixes:
- Skip
__proto__,constructorandprototypekeys when copying, and copy only own keys (Object.keys,Object.hasOwn). My filtered version printedundefinedafterwards. - Use
Object.create(null)for dictionaries built from user keys, or aMap. - Validate input against a schema that rejects unexpected keys, as in input validation and injection attacks and validating untrusted data at runtime.
- Keep dependencies that merge objects up to date, since this has been a recurring bug in utility libraries.
ReDoS
A regular expression with nested quantifiers can take exponential time on input that almost matches. Because Node runs your JavaScript on one thread, one slow match blocks every request:
const re = /^(a+)+$/;
re.test('a'.repeat(28) + 'b'); // over a second on my machine
I timed it: 22 a characters took about 190 ms, 26 took about 300 ms, and 28 took about 1.2 seconds, climbing roughly fourfold per two characters. A pattern without nested repetition, /^a+$/, handled 100,000 characters in under a millisecond. Defenses: avoid nested quantifiers and overlapping alternations, cap the length of any string you test, and do not build regexes from user input. Regular expressions covers the language side, and blocking vs non-blocking I/O explains why a slow match stalls the whole server.
Headers, secrets and users
A few cheap measures complete the baseline for an HTTP service:
helmet. One line in Express,app.use(helmet()), sets a group of security headers. With Helmet in a test app, the response carriedcontent-security-policy,strict-transport-security,x-content-type-options: nosniff,x-frame-optionsandreferrer-policy. Also remove theX-Powered-Byheader withapp.disable('x-powered-by'). The default Content-Security-Policy is strict and will break pages that load outside resources, so tune it rather than disabling it. What those headers do is in web security fundamentals for frontend.- No secrets in code or logs. See secrets and sensitive data handling.
- Run as a non-root user. In a container, add a user and switch to it before starting Node, for example
USER nodein the Dockerfile, since the official Node images include anodeuser. If an attacker gets code execution, they hold a low-privilege account instead of root. Containers are covered in deploying Node applications. - Do not leave the inspector open. See debugging with the inspector.
- Keep Node patched. Run a supported LTS release, as in installing Node and managing versions.
What the video covers
The embedded talk is Rafael Gonzaga’s “The Journey of the Node.js Permission Model”, from October 2023, in a 15-minute cut hosted on OpenSSF’s channel. Gonzaga is a Node.js TSC member and chair of its Security Working Group. His abstract says he covers the motivations behind the model, the challenges and plans, and what the then-experimental feature does. It is a design talk rather than a tutorial. It predates the stable --permission flag and the network permission, and it does not cover prototype pollution, ReDoS, Helmet or non-root users. Those sections, and every flag and result above, come from this lesson and my local runs on Node 26. A longer 21-minute cut of the same talk is on Nearform’s channel. The channel’s view counts are tiny, and a transcript was not available, so the talk is described from its abstract. The “go deeper” Snyk video has a four-minute permission demo, using the old flag name.
Where this fits
Permissions limit what a process can do once it is running. Deploying Node applications is about how it gets started, kept alive and stopped.
Check yourself
Does `node --permission app.js` stop a malicious dependency from stealing your data?
It reduces the damage a mistake or a limited exploit can do, because file reads, writes, child processes and so on are denied unless granted. But Node's own docs say it provides no guarantee against malicious code, since code that is already running can look for ways around it. Treat it as one layer next to containers, least privilege and dependency controls.
You run `node --permission server.js` and it crashes reading its own source file. What did you forget?
Under `--permission`, file reads are denied by default, including your application's files and its dependencies. Grant them, for example `--allow-fs-read=$PWD`, and add `--allow-fs-write` only for directories that must be writable, such as a temp or upload folder.
What is prototype pollution, and what in a JSON merge function enables it?
It is writing to `Object.prototype` through a crafted key such as `__proto__`, so that every object gains an attacker-chosen property, such as `isAdmin: true`. A naive recursive merge that copies every key from user JSON will follow `__proto__` into the shared prototype. Skip those keys, use `Object.hasOwn` checks, build objects with `Object.create(null)`, or validate input against a schema.
Why is the regex `/^(a+)+$/` dangerous on user input?
The nested quantifiers let the engine try exponentially many ways to split a failing input, so a short crafted string can take seconds or minutes while the event loop is blocked. I measured it growing roughly fourfold for every two extra characters, reaching over a second at 28. Avoid nested quantifiers, bound input length, and prefer linear patterns.
Go deeper
Notes
Notes are saved to your account.
Everything else on this page works without one — progress and bookmarks keep themselves in this browser and come with you when you sign in. Notes are the one thing worth not trusting to a browser you might clear.
Your notes could not be loaded.