# Add Input Validation to Firebase Cloud Functions

Yes. An agent validates the query and document data your HTTP and Firestore functions read, answers 400 instead of crashing, tests it offline, and opens a PR.

[Run this on Rush](https://cloud.getrush.ai/run/add-input-validation/firebase-functions/). Opens the console with this prompt ready to send, in a Project that has your repository.

## What the agent does

The agent reads each function to see what it trusts. In a codebase like `Node/quickstarts/uppercase-firestore` in firebase/functions-samples, `functions/index.js` exports two 2nd-gen functions: `addmessage`, an `onRequest` handler that reads `req.query.text`, writes `{original}` to the `messages` collection with the Admin SDK and answers `{result: "Message with ID: ... added."}`, and `makeuppercase`, an `onDocumentCreated("/messages/{documentId}")` trigger that reads `event.data.data().original`, logs with `logger.log`, and writes `uppercase` back with `set({uppercase}, {merge: true})`. Neither checks anything: a request with no `text` stores `original: undefined` and the trigger then throws on `.toUpperCase()`, a repeated `?text=` query arrives as an array, and a request of any method is accepted. `functions/package.json` depends on `firebase-functions` `^7.4.0` and `firebase-admin` `^14.5.0` on Node `24`, with `eslint` and `eslint-config-google` and a `lint` script at `--max-warnings=0`, and no test script; `firebase.json` names the `uppercase-firestore` codebase, the Firestore rules and indexes files, and emulator ports for Functions and Firestore, with no `predeploy` step. The sibling `Node/test-functions-mocha` sample shows the repository's own way to test functions offline with `mocha` and `firebase-functions-test`.

For `addmessage` the agent adds a small `validate.js` next to `index.js` that exports `parseText(query)`: it rejects a missing value, an array, a non-string, an empty string after trimming, and anything longer than a limit set in one constant, returning either `{text}` or `{error}` with a plain reason. The handler answers `405` for any method other than `GET` and `POST` (the same shape `https-time-server` uses to forbid `PUT`), `400` with `{error}` when validation fails, and otherwise stores the trimmed text. Every rejection goes through `logger.warn` with the reason and never with the raw text, so logs do not fill with user input.

For `makeuppercase` the agent guards the trigger rather than trusting the writer: if `event.data` is missing or `original` is not a string, it logs with `logger.warn` including `event.params.documentId` and returns without writing, so a bad document does not throw, does not retry, and does not leave a half-written `uppercase` field. A document that is valid is handled exactly as before.

Tests use the repository's own pattern. The agent adds `mocha` and `firebase-functions-test` as dev dependencies, a `test` script of `mocha *.test.js`, and `index.test.js` that initialises `firebase-functions-test` offline, wraps `makeuppercase` with `test.wrap` and `test.firestore.makeDocumentSnapshot` for a valid document, a document with a number in `original` and an empty document, and calls `addmessage` directly with stubbed `req` and `res` objects for a missing `text`, an array, an overlong string, a `PUT`, and a good `POST`, asserting the status and JSON each time. Firestore writes are stubbed so nothing needs an emulator. It runs `npm install`, `npm run lint` (warnings fail it) and `npm test` in the function's directory and includes the output; `test_node.yml`, which runs the workspace-wide lint and compile on Node 22.x, picks the new files up unchanged.

## Start it with one API call

`POST https://api.phoenix.so/o/{org}/sessions`

```json
{
  "agent": "claude",
  "input": "Add input validation to the Cloud Functions in this directory. Read functions/index.js, functions/package.json, firebase.json and the repository's test-functions-mocha sample first. For the onRequest function, validate the text query parameter in a separate module: reject missing, array, non-string, empty-after-trim and overlong values with a 400 JSON error, answer 405 for methods other than GET and POST, log rejections with logger.warn without the raw input, and store the trimmed text. For the Firestore onDocumentCreated trigger, return without writing and log a warning when the event has no data or the original field is not a string, keeping the valid path unchanged. Add mocha and firebase-functions-test as dev dependencies and a test script, and write offline tests for each case with stubbed Firestore writes. Run npm install, npm run lint and npm test in the functions directory, include the output, and open a pull request.",
  "resources": [
    {
      "url": "https://github.com/your-org/your-app"
    }
  ]
}
```

1. **Get an API key.** In the console, open Settings, then API keys, and create a key for your org. Send it in the Authorization header as a Bearer token.
2. **Send the request.** POST the body in request.json to https://api.phoenix.so/o/{org}/sessions, with your repository as the resources URL. The run starts in its own cloud sandbox.
3. **Read what came back.** Follow the run on its live stream or wait for the run.completed webhook, then read the result and its trajectory.

## What comes back

What comes back is a pull request that changes `functions/index.js` (the method check, the validation call and the trigger guard) and `functions/package.json` (two dev dependencies and a `test` script), and adds `functions/validate.js` and `functions/index.test.js`. `firebase.json`, the ESLint config and every other sample directory are untouched.

The description lists each rejected input and the status it now gets, quotes the Mocha summary and the ESLint result, and states that the valid path of both functions produces the same writes as before. The commands and their full output are in the transcript at `GET /o/{org}/sessions/{id}/messages`.

Before merging, a reviewer sets the length limit to what the product needs, decides whether an invalid document should also be marked in Firestore rather than only logged, and confirms the 405 does not break a client that posts with another method. A follow-up message to the same session can add the same guards to another function.

## Run it on every Linear issue labelled functions

Set up an automation with a Linear trigger on the `functions` label and this prompt, scoped to the Project that holds the Firebase code. The trigger appends the issue to the prompt, so an issue that names a function and the bad input a user sent starts a run that guards that function, tests it offline, and opens its own pull request.

From your own server, send `POST /o/{org}/sessions` with the repository in `resources` and the issue URL as a second resource, with a `request_id` that is a UUID v5 of the issue identifier so a retry returns the run already started. The key's `webhook_url` reports when each run the key starts finishes.

## Why run it on Rush?

Functions that trust their input fail in production, where a crash in a Firestore trigger becomes a retry loop and a log full of stack traces. The agent reads what each function assumes, adds the checks at the boundary, and proves them with offline tests in a sandbox of its own, no emulator and no project credentials.

The pull request carries the test list and the passing summary, so a reviewer checks the limits and the status codes rather than deploying to find out. A codebase with many functions can be done in parallel, one run per directory, each with its own pull request.

## Frequently asked questions

### Do the tests need the Firebase emulator or a project?

No. `firebase-functions-test` runs in offline mode, `makeDocumentSnapshot` builds the Firestore event, and the Admin SDK write is stubbed, so `npm test` runs anywhere Node runs. The emulator remains the way to try the deployed shape end to end.

### Why return without writing instead of throwing in the trigger?

A thrown error in an event-driven function is reported as a failure and can be retried, which for a document that will never become valid means the same warning over and over. Logging the document id and returning keeps the bad document visible without the retries.

### Will the valid path change?

No. A string `text` is trimmed and stored under `original` as before, and a document whose `original` is a string gets the same `uppercase` write with `merge: true`. The tests include the valid case for both functions to show that.

### Does the lint step still pass?

Yes. The function's `lint` script runs ESLint with `eslint-config-google` and zero warnings allowed, and the repository's `test_node.yml` workflow runs lint and compile across the Node samples on every pull request. The agent runs `npm run lint` on the changed and new files and includes the result.

## More Firebase Cloud Functions jobs

- [Add Rate Limiting to Firebase Callable Functions](https://getrush.ai/run/add-rate-limiting/firebase-functions/)
- [Turn On Safe Retries for Event-Driven Firebase Cloud Functions](https://getrush.ai/run/add-retry-policies/firebase-functions/)
- [Convert Firebase Cloud Functions From JavaScript to TypeScript](https://getrush.ai/run/convert-javascript-to-typescript/firebase-functions/)

## The same job on other stacks

- [Add Input Validation to a Hono API](https://getrush.ai/run/add-input-validation/hono/)
- [Add Input Validation to a Koa App](https://getrush.ai/run/add-input-validation/koa/)
- [Add Input Validation to a Ktor API](https://getrush.ai/run/add-input-validation/ktor/)

## Keep reading

- [How a Rush run works on your repository, from request to pull request](https://getrush.ai/cloud/)
- [Compare cloud agents, agent sandboxes and AI code review](https://getrush.ai/compare/)
- [Rush pricing: Free, Pro and Max](https://getrush.ai/pricing/)
