6.9 KiB
title
| title |
|---|
| experimental_taintUniqueValue |
This API is experimental and is not available in a stable version of React yet.
You can try it by upgrading React packages to the most recent experimental version:
react@experimentalreact-dom@experimentaleslint-plugin-react-hooks@experimental
Experimental versions of React may contain bugs. Don't use them in production.
This API is only available inside React Server Components.
taintUniqueValue lets you prevent unique values from being passed to Client Components like passwords, keys, or tokens.
taintUniqueValue(errMessage, lifetime, value)
To prevent passing an object containing sensitive data, see taintObjectReference.
Reference {/reference/}
taintUniqueValue(message, lifetime, value) {/taintuniquevalue/}
Call taintUniqueValue with a password, token, key or hash to register it with React as something that should not be allowed to be passed to the Client as is:
import {experimental_taintUniqueValue} from 'react';
experimental_taintUniqueValue(
'Do not pass secret keys to the client.',
process,
process.env.SECRET_KEY
);
Parameters {/parameters/}
-
errMessage: The message you want to display if the object gets passed to a Client Component. Ifvalueis passed to a Client Component an Error will be thrown.errMessagelet's you define the message displayed by this Error. -
lifetime: Any object that indicates how longvalueshould be tainted.valuewill be blocked from being sent to any Client Component while this object still exists. For example, passingglobalThisblocks the value for the lifetime of an app.lifetimeis typically an object whose properties containsvalue. -
value: A string, bigint or TypedArray.valuemust be a unique sequence of characters or bytes with high entropy such as a cryptographic token, private key, hash, or a long password.valuewill be blocked from being sent to any Client Component.
Returns {/returns/}
experimental_taintUniqueValue returns undefined.
Caveats {/caveats/}
- Modifying tainted values can invalidate tainting protection. Converting tainted values to upper case, concatenating tainted string values into a larger string, converting tainted values to base64, returning a substring, and similar transformations will lose tainting protection.
Do not rely solely on tainting for security. Tainting a value doesn't block every possible derived value. For example, converting it to upper case, concatenating it into a larger string, converting it to base64, returning a substring etc, will still be allowed. It only protects against simple mistakes like explictly passing secret values to the client. Mistakes in calling the taintUniqueValue like using a global store outside of React, without the corresponding lifetime object, can cause the tainted value to become untainted. Tainting is a layer of protection, a secure app will have multiple layers of protection, well designed APIs, and isolation patterns.
Usage {/usage/}
Prevent a token from being passed to Client Components {/prevent-a-token-from-being-passed-to-client-components/}
To ensure that sensitive information such as passwords, session tokens, or other unique values do not inadvertently get passed to Client Components, the taintUniqueValue function provides a layer of protection. When a value is tainted, any attempt to pass it to a Client Component will result in an error.
The lifetime argument defines the duration for which the value remains tainted. For values that should remain tainted indefinitely, objects like globalThis or process can serve as the lifetime argument. These objects have a lifespan that spans the entire duration of your app's execution.
import {experimental_taintUniqueValue} from 'react';
experimental_taintUniqueValue(
'Do not pass a user password to the client.',
globalThis,
process.env.SECRET_KEY
);
If the tainted value's lifespan is tied to a object, the lifetime should be the object that encapsulates the value. This ensures the tainted value remains protected for the lifetime of the encapsulating object.
import {experimental_taintUniqueValue} from 'react';
export async function getUser(id) {
const user = await db`SELECT * FROM users WHERE id = ${id}`;
experimental_taintUniqueValue(
'Do not pass a user session token to the client.',
user,
user.session.token
);
return user;
}
In this example, the user object serves as the lifetime argument. If this object gets stored in a global cache or is accessible by another request, the session token remains tainted.
Using server-only and taintUniqueValue to prevent leaking secrets {/using-server-only-and-taintuniquevalue-to-prevent-leaking-secrets/}
If you're running a Server Components environment that has access to private keys or passwords such as database passwords, you have to be careful not to pass that to a Client Component.
export async function Dashboard(props) {
// DO NOT DO THIS
return <Overview password={process.env.API_PASSWORD} />;
}
"use client";
import {useEffect} from '...'
export async function Overview({ password }) {
useEffect(() => {
const headers = { Authorization: password };
fetch(url, { headers }).then(...);
}, [password]);
...
}
This example would leak the secret API token to the client. If this API token can be used to access data this particular user shouldn't have access to, it could lead to a data breach.
Ideally, secrets like this are abstracted into a single helper file that can only be imported by trusted data utilities on the server. The helper can even be tagged with server-only to ensure that this file isn't imported on the client.
import "server-only";
export function fetchAPI(url) {
const headers = { Authorization: process.env.API_PASSWORD };
return fetch(url, { headers });
}
Sometimes mistakes happen during refactoring and not all of your colleagues might know about this. To protect against this mistakes happening down the line we can "taint" the actual password:
import "server-only";
import {experimental_taintUniqueValue} from 'react';
experimental_taintUniqueValue(
'Do not pass the API token password to the client. ' +
'Instead do all fetches on the server.'
process,
process.env.API_PASSWORD
);
Now whenever anyone tries to pass this password to a Client Component, or send the password to a Client Component with a Server Action, a error will be thrown with message you defined when you called taintUniqueValue.