---
title: Untrusted input
description: "A request can send any fields, so take only the ones you want, and reject values you can’t use."
seo:
  description: "Handle untrusted input with Active Record: permit only the fields you want, return a 400 for values that can’t be cast, and check values before querying."
---

## At a glance

| To                                     | Write                                                     |
| -------------------------------------- | --------------------------------------------------------- |
| take only the fields you want          | `Account.permit(await request.json(), "email", "handle")` |
| return a 400 for a value you can’t use | catch `TypeError` and `SyntaxError`                       |
| query with a value from a request      | check `typeof token === "string"` first                   |
| widen a query                          | `rewhere` and `unscope`, with names you chose             |

## The Models

The examples use these Models, whose attributes come from their tables through the schema `active-record schema` generates:

```ts account.ts
import { ApplicationRecord } from "./application-record";

export class Account extends ApplicationRecord {}
```

```ts invitation.ts
import { ApplicationRecord } from "./application-record";

// Its token is NULL once the invitation is accepted.
export class Invitation extends ApplicationRecord {}
```

```ts schema.ts
// Generated by `active-record schema` from migrations/ — don't edit.
// schema: a77f61266d3a

import { defineSchema, type TableAttributes } from "@forestfuture/active-record";
import { d1 } from "@forestfuture/active-record/d1";

/** accounts — last changed by 0001_create_tables.sql */
export const accounts = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
  handle: { type: "string", null: false },
  plan: "string",
  seats: "integer",
} as const;

/** invitations — last changed by 0001_create_tables.sql */
export const invitations = {
  id: { type: "string", null: false, generateId: true },
  email: { type: "string", null: false },
  token: "string",
  acceptedAt: "datetime",
} as const;

/** The database's adapter and binding, its tables (with their primary keys), and the Models built on them. */
export const schema = defineSchema({
  adapter: d1({ binding: "DB" }),
  tables: {
    accounts: { attributes: accounts, primaryKey: "id" },
    invitations: { attributes: invitations, primaryKey: "id" },
  },
  models: { Account: "accounts", Invitation: "invitations" },
});

declare module "../models/account" {
  interface Account extends TableAttributes<typeof accounts, (typeof Account)["attributes"]> {}
}

declare module "../models/invitation" {
  interface Invitation
    extends TableAttributes<typeof invitations, (typeof Invitation)["attributes"]> {}
}
```

```sql D1
CREATE TABLE accounts (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL,
  handle TEXT NOT NULL,
  plan TEXT,
  seats INTEGER
);
CREATE TABLE invitations (
  id TEXT PRIMARY KEY NOT NULL,
  email TEXT NOT NULL,
  token TEXT,
  accepted_at DATETIME
);
```

```sql Postgres
CREATE TABLE accounts (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL,
  handle TEXT NOT NULL,
  plan TEXT,
  seats INTEGER
);
CREATE TABLE invitations (
  id UUID PRIMARY KEY,
  email TEXT NOT NULL,
  token TEXT,
  accepted_at TIMESTAMPTZ
);
```

## Permitting fields

Only permit the fields you want from a request:

```ts
import { Account } from "./models/account";

export async function signUp(request: Request) {
  const permitted = Account.permit(await request.json(), "email", "handle"); // drops plan and seats
  return Account.create(permitted);
}
```

:::note
`permit` can also read `FormData` or `URLSearchParams`.
:::

Permitted values are cast to their attribute’s types, so `"42"` becomes `42` for an integer. [Attribute types](/attribute-types#casting-assigned-values) lists what each type accepts. A page number from a query string can go straight to [`paginate`](/ordering-and-pagination#paginating), which casts it too.

> **Beyond Rails**
>
> Rails’ `params.permit` only filters keys. Active Record’s also casts each value, and checks that each name is an attribute.

## Using a schema library

If you validate requests with a schema library such as [Zod](https://zod.dev) or [Valibot](https://valibot.dev), pass the parsed result to the Model:

```ts
import { z } from "zod";

const SignUp = z.object({ email: z.string(), handle: z.string().min(3) });

const fields = SignUp.parse(await request.json());
const account = await Account.create(fields);
```

## Returning a 400

A value that can’t be cast throws a `TypeError`, and a body that isn’t JSON throws a `SyntaxError`. Return a 400 for either:

```ts
import { Account } from "./models/account";

export async function updateAccount(request: Request): Promise<Response> {
  const account = await Account.find(new URL(request.url).searchParams.get("id") ?? "");
  let permitted;
  try {
    permitted = Account.permit(await request.json(), "handle", "seats");
  } catch (error) {
    if (error instanceof SyntaxError || error instanceof TypeError) {
      return new Response("Bad request", { status: 400 });
    }
    throw error;
  }

  await account.update(permitted);
  return Response.json(account);
}
```

## Querying with request values

Check that a value is a string before you query with it. An accepted invitation’s token is NULL, so an unchecked `null` would find one:

```ts
import { Invitation } from "./models/invitation";

export async function accept(request: Request): Promise<Response> {
  const { token } = await request.json<{ token: string }>();
  if (typeof token !== "string" || token === "") {
    return new Response("Send the invitation's token", { status: 400 });
  }

  const invitation = await Invitation.findBy({ token });
  if (invitation === null) return new Response("No such invitation", { status: 404 });

  await invitation.update({ token: null, acceptedAt: new Date() });
  return new Response(`Welcome, ${invitation.email}`);
}
```

JSON can send `null` or a list. `findBy({ token: null })` matches rows whose token is NULL, and `findBy({ token: [first, second] })` matches a row with either token.

`findOrCreateBy`, `findOrInitializeBy`, and `createOrFindBy` refuse a list. They throw a `TypeError` before they query, since their attributes become the new record’s values.

:::note
A value that can’t be cast matches nothing, so `whereNot({ id: "abc" })` excludes nothing.
:::

> **Beyond Rails**
>
> Rails’ `find_or_create_by` reads a list as `IN`, as `find_by` does. Rails doesn’t need to refuse one. A request’s params must be permitted before a model takes them, and `permit(:email)` keeps only single values.
>
> Here, `await request.json()` is a plain object, and `permit` is up to you. So `findOrCreateBy(await request.json())` could find another user’s row. The find-or-create methods refuse a list instead. `findBy` and `where` still read a list as `IN`.

### Rewriting queries

Pass `rewhere` and `unscope` the attribute names and values you chose, never a request’s. They widen a query, where `where` only narrows one, so `Post.where({ published: true }).rewhere(await request.json())` would find any post the body names.

An association’s link to its owner always stays. `user.posts().rewhere({ userId: 2 })` finds nothing, since no post belongs to both users.

[Security](/security) lists what Active Record protects against, and what it leaves to your app.
