All jobs

Add CSRF Protection to a Slim 4 App

Yes. An agent adds slim/csrf's Guard to a Slim 4 app, starts the session it needs, serves token pairs, proves a POST without them is refused, and opens a PR.

Run this on RushOpens the console with this prompt ready to send, in a Project that has your repository.

What the agent does

The agent starts by finding out where state lives, because the Guard middleware stores its tokens in the PHP session and throws Invalid CSRF storage the moment it is built without one. In an app laid out like slimphp/Slim-Skeleton, composer.json requires slim/slim ^4.12, slim/psr7 ^1.6, php-di/php-di ^6.4 and monolog/monolog ^2.9 on PHP ^7.4 || ^8.0, with phpunit/phpunit ^9.6.17, phpstan/phpstan ^1.10 and squizlabs/php_codesniffer ^3.9 for development. public/index.php builds the PHP-DI container from app/settings.php, app/dependencies.php and app/repositories.php, loads app/middleware.php and app/routes.php, then adds the routing, body-parsing and error middleware itself. app/middleware.php registers exactly one class, SessionMiddleware, and that class calls session_start() only when $_SERVER['HTTP_AUTHORIZATION'] is set. app/routes.php has a catch-all OPTIONS route for CORS preflights, GET / and a /users group with two GET actions, so today nothing in the app changes state and nothing starts a session for an anonymous browser.

The agent runs composer require slim/csrf, which resolves to the 1.5.x line, and reads the package's Guard before wiring it. Its constructor takes the app's ResponseFactoryInterface, a prefix that defaults to csrf, a storage array passed by reference or the session, an optional failure handler, a storageLimit of 200 token pairs and a minimum strength of 16. process() reads csrf_name and csrf_value from the parsed body, falls back to request headers of the same names for a bodiless DELETE, validates the pair on POST, PUT, DELETE and PATCH, removes a used token unless persistentTokenMode is on, and refuses a GET that carries a token in its body. The default failure handler answers 400 with the plain text Failed CSRF check!, which does not match the JSON that HttpErrorHandler::respond writes for every other error in this app.

So the agent writes three things. In app/dependencies.php it adds a container definition for Slim\Csrf\Guard built from $app->getResponseFactory() with a failure handler that returns an ActionPayload carrying an ActionError of type BAD_REQUEST and the message Invalid or missing CSRF token, so a refused request looks like every other 4xx from this app. In app/middleware.php it adds $app->add(Guard::class) on the line before SessionMiddleware: Slim runs the middleware added last first, so the session middleware stays outside the guard and the session exists before the container builds the Guard. The guard is also inside the body-parsing middleware that public/index.php adds afterwards, so getParsedBody() already holds the form or JSON fields when the guard reads them. SessionMiddleware changes from starting a session only behind an Authorization header to starting one for every request that is not a CORS preflight, with session_set_cookie_params setting httponly and samesite=Lax first; the session request attribute it already sets stays. In app/routes.php a GET /csrf route returns the key names from getTokenNameKey() and getTokenValueKey() and the pair from the request attributes, so a front end can fetch a token before it posts.

The test is the part that needs the most care, because tests/TestCase.php builds the app through getAppInstance() without the body-parsing middleware and PHPUnit runs with beStrictAboutOutputDuringTests, where session_start() fails on headers already sent. The agent therefore has the test container override the Guard definition with an array storage passed by reference, which the constructor accepts in place of $_SESSION, and uses withParsedBody() on the Slim\Psr7\Request that createRequest() returns. tests/Application/Middleware/CsrfGuardTest.php adds a throwaway POST /echo route to the app instance, posts to it with no tokens and asserts the 400 JSON payload, reads a pair from GET /csrf, posts again with csrf_name and csrf_value and asserts 200, and posts the same pair a third time to show a token is single-use. The agent runs vendor/bin/phpcs, vendor/bin/phpstan and composer test as .github/workflows/tests.yml does on its PHP 7.4 to 8.2 matrix, then composer start and two curl calls against localhost:8080 to capture a refused and an accepted POST.

Start it with one API call

POST https://api.phoenix.so/o/{org}/sessions with this body:

{
  "agent": "claude",
  "input": "Add CSRF protection to this Slim 4 app with the slim/csrf package. Read composer.json, public/index.php, app/middleware.php, app/dependencies.php, app/routes.php, src/Application/Middleware/SessionMiddleware.php, src/Application/Handlers/HttpErrorHandler.php, tests/TestCase.php and .github/workflows/tests.yml first. Register Slim\\Csrf\\Guard in the container with a failure handler that answers the same JSON ActionPayload shape the app's error handler uses, add it to the app so it runs inside the session middleware and inside body parsing, make the session start for every non-preflight request with httponly and SameSite cookie flags, and add a GET route that returns the token key names and a fresh pair. Write a PHPUnit test that gives the Guard array storage, posts without tokens and expects 400, posts with a pair from the token route and expects 200, and shows a used pair is refused. Run phpcs, phpstan and phpunit, start the server and curl one refused and one accepted POST, then open a pull request that explains the middleware order.",
  "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 composer.json and composer.lock for slim/csrf, app/dependencies.php for the Guard definition and its JSON failure handler, app/middleware.php for the one added line and its ordering comment, app/routes.php for GET /csrf, and src/Application/Middleware/SessionMiddleware.php for the unconditional session, and adds tests/Application/Middleware/CsrfGuardTest.php. The description shows the two curl exchanges, one 400 with the BAD_REQUEST payload and one 200, and the phpunit output with the new test's name beside the existing ListUserActionTest and ViewUserActionTest.

The Tests workflow runs on the pull request across the PHP matrix, with phpcs and phpstan on the 8.1 job, so a reviewer sees the coding standard and the static analysis pass on the same commit. The run's record keeps the composer require output with the version it resolved and every command after it, so a reviewer can tell which step produced which line.

Before merging, a reviewer decides whether API clients will send the pair as headers or whether an /api group should be exempt, whether persistentTokenMode should be on for a single-page front end that keeps several tabs open, and whether the OPTIONS catch-all should keep skipping the session. The agent changes no action class and no repository.

Run it on every Slim repository with form posts

A team with several Slim services starts one run per repository from its own server: one POST /o/{org}/sessions each, with the repository in resources and a request_id that is a UUID v5 of the repository's full name, so a retried call returns the run already started rather than a second pull request. Each run reads its own app/middleware.php and app/routes.php, so a service that already starts sessions in public/index.php gets the guard placed accordingly, and one with only an API and bearer tokens gets a pull request that says CSRF protection does not apply to it.

After that, an automation in the Project with a github trigger on pull_request.opened and pull_request.synchronize and the prompt "if this pull request adds a POST, PUT, PATCH or DELETE route or a form template, check that the route runs inside the CSRF guard and the template includes the two hidden fields, and say so in a comment" keeps new routes covered. The trigger adds the pull request after the prompt and fires only for work by owners, members and collaborators.

The use case this job follows, with its automation and trigger: Hand off a long task.

Why run it on Rush?

CSRF middleware fails quietly in ways a diff hides: a Guard built before session_start() throws on the first anonymous request, a guard added after the session middleware in app/middleware.php runs outside it and never sees the session, and a test that starts a real session under PHPUnit's output rules fails on headers already sent. The agent runs the real app in its sandbox, posts to it with and without tokens, and reads the real 400 body before it opens the pull request.

Every command stays with the run, from composer require to the two curl calls, and the pull request quotes them. The same job over a dozen Slim services at once costs no more attention than one, because each run has its own machine, its own record and its own pull request to review.

Frequently asked questions

Does this break JSON API clients that never render a form?

Not if they send the pair. Guard::process reads csrf_name and csrf_value from the parsed body first and from request headers of the same names when the body has neither, so a client fetches GET /csrf once and sends the two headers on its POST. A service whose clients authenticate with bearer tokens only can instead add the guard to a route group rather than the whole app, and the pull request names where that line would go.

Why does the test give the Guard an array instead of the session?

The constructor's storage parameter accepts an array by reference and uses it in place of $_SESSION, which is what the package's own tests do. PHPUnit in this app runs with beStrictAboutOutputDuringTests, and session_start() under the test runner fails on headers already sent, so array storage lets the test prove the guard's behaviour without a PHP session. The production path through $_SESSION is covered by the two curl calls in the pull request.

A user with two tabs open gets refused on the second one. Is that expected?

Yes, with the default settings: each token is removed once it validates, so a form rendered in one tab uses up the pair the other tab also holds. Setting persistentTokenMode to true on the Guard keeps one pair for the whole session, which a single-page front end usually wants. The default storageLimit of 200 pairs bounds the session either way.

Why does the session now start for every request?

Because the guard has to read its storage on every unsafe request and write a fresh pair on every safe one, and a session that only exists behind an Authorization header leaves anonymous form posts with nowhere to keep a token. The OPTIONS preflight route is excluded so CORS checks stay cookie-free. A team that wants a different store can pass any ArrayAccess that is also Countable and Iterator to the constructor instead.

More Slim jobs

The same job on other stacks

Keep reading