# Add Security Headers to a Gin API

Yes. An agent adds a Gin middleware setting nosniff, frame, referrer, CSP and cache headers on every response, with HSTS behind a flag, tests it, and opens a PR.

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

## What the agent does

The agent reads how the router is built before it adds a middleware. In an API shaped like gothinkster/golang-gin-realworld-example-app, `go.mod` declares `go 1.21` with `gin-gonic/gin` v1.10.0, `golang-jwt/jwt/v5` v5.2.1, `gorm.io/gorm` v1.25.12 on the SQLite driver and `stretchr/testify` v1.10.0. `hello.go` creates `gin.Default()`, turns `RedirectTrailingSlash` off, mounts the `/api` group with the `users`, `articles`, `profiles` and `tags` routers behind `users.AuthMiddleware`, adds `/api/ping`, and listens on `PORT` or `8080`. `users/middlewares.go` reads the token from an `Authorization: Token` header or an `access_token` query parameter, which means a token can end up in a URL. `common/utils.go` holds shared helpers and `common/unit_test.go` shows the test style: `httptest.NewRecorder`, a request against a `gin` engine, `assert.New(t)`. `.env.example` lists `PORT`, `GIN_MODE` and `DB_PATH`.

It writes `common/security.go` with a `SecurityHeaders()` function returning a `gin.HandlerFunc` that sets `X-Content-Type-Options: nosniff`, `X-Frame-Options: DENY`, `Referrer-Policy: no-referrer`, a `Content-Security-Policy` of `default-src 'none'; frame-ancestors 'none'`, which fits an API that returns JSON only, and `Cache-Control: no-store`, because every `/api` response is either per-user or carries a token. Each header is set only when the handler has not already set it, so a route that wants a different value keeps it. `Strict-Transport-Security` is handled apart: the binary listens on plain HTTP and TLS ends at a proxy, so the middleware reads `HSTS_MAX_AGE` from the environment the way `hello.go` reads `PORT`, and sends the header only when the variable is set and the request arrived over TLS or with `X-Forwarded-Proto: https`. `.env.example` documents the new variable, commented out.

`hello.go` registers `r.Use(common.SecurityHeaders())` right after `gin.Default()`, before any group, so `/api/ping`, every `/api` route and the `401` that `AuthMiddleware` aborts with all pass through it. The `no-referrer` policy also means a URL that carries `access_token` is not sent on to another origin by a browser, which the pull request points out without changing the token extraction.

Tests go in `common/security_test.go` in the repository's own style: a `gin.New()` engine with the middleware and one route, `httptest` requests, and `testify` assertions for each header, for the absence of `Strict-Transport-Security` by default, for its presence with `HSTS_MAX_AGE` set and `X-Forwarded-Proto: https`, and for a handler's own `Cache-Control` being kept. Before pushing, the agent runs what `ci.yml` runs: `bash ./scripts/gofmt.sh`, `bash ./scripts/coverage.sh`, which runs `go test` with coverage for every package including `common`, `golangci-lint run` with the `staticcheck`, `unused` and `misspell` linters from `.golangci.yml`, and `gosec ./...`. It starts the server and pastes a `curl -i http://localhost:8080/api/ping` response into the pull request.

## Start it with one API call

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

```json
{
  "agent": "codex",
  "input": "Add security response headers to this Gin API and open a pull request. Read go.mod, hello.go, users/middlewares.go, common/utils.go, common/unit_test.go, .env.example, .golangci.yml, scripts/gofmt.sh, scripts/coverage.sh and .github/workflows/ci.yml first. Write common/security.go with SecurityHeaders() returning a gin.HandlerFunc that sets X-Content-Type-Options nosniff, X-Frame-Options DENY, Referrer-Policy no-referrer, Content-Security-Policy default-src 'none'; frame-ancestors 'none', and Cache-Control no-store, each only when the handler has not set it. Read HSTS_MAX_AGE from the environment and send Strict-Transport-Security only when it is set and the request is TLS or carries X-Forwarded-Proto https. Register the middleware in hello.go right after gin.Default() before any group. Document HSTS_MAX_AGE in .env.example. Add common/security_test.go with httptest and testify covering every header, HSTS off by default and on with the variable and header, and a handler's own Cache-Control being kept. Run scripts/gofmt.sh, scripts/coverage.sh, golangci-lint run and gosec ./..., start the server and paste a curl -i response for /api/ping and the test output in the pull request. Do not change AuthMiddleware or any route.",
  "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 adds `common/security.go` and `common/security_test.go`, adds one `r.Use` line to `hello.go` and one commented variable to `.env.example`. The description shows a `curl -i` response for `/api/ping` with the five headers and no `Strict-Transport-Security`, a second with `HSTS_MAX_AGE` set behind a forwarded-proto header, and the `go test` coverage lines for `common`.

On a repository with this `CI` workflow, the pull request runs the gofmt check, the coverage script across Go 1.21, 1.22 and 1.23, golangci-lint, the gosec scan, and the Realworld Postman collection through Newman against the running server; the collection checks bodies and status codes, so it passes unchanged.

A reviewer checks that the `Content-Security-Policy` is right for an API with no HTML, that `Cache-Control: no-store` suits the clients that call `GET /api/tags`, that HSTS stays off for the plain `:8080` listener, and that a `401` from `AuthMiddleware` carries the headers. Then they set `HSTS_MAX_AGE` in the deployment that has TLS in front of it.

## Run it on every new Gin service

A team that runs several Gin services sends one `POST /o/{org}/sessions` per repository with this prompt and that repository in `resources`. Each run reads its own `main` package and middleware, so a service already using `gin-contrib/secure` gets its options reviewed instead of a second middleware, and each run opens its own pull request with its own tests.

Give the API key a `webhook_url` and Rush POSTs `run.completed` when each turn ends, with the `session_url` to read the pull request from, so a handler on your server can post the link where that service's owners review.

## Why run it on Rush?

Headers are cheap to add and easy to add wrongly: HSTS from a plain-HTTP binary breaks local development, and a web-page CSP on a JSON API protects nothing. In a Rush sandbox the agent starts the real server, fetches a route with `curl -i`, and keeps that output in the run's record, so the pull request shows the exact header block the proxy will pass through.

The repository already has a four-job CI with lint, coverage, a security scan and an API suite, and the agent runs the same scripts before pushing, so the pull request arrives green rather than waiting a round trip for a gofmt failure. The same request body works on every Gin service a team owns.

## Frequently asked questions

### Why not use gin-contrib/secure?

It would work, and the agent uses it if the prompt asks. The default is a small middleware in `common` with no new dependency, because the five headers and the HSTS rule fit in one function and the repository's tests can cover every line of it.

### Will HSTS break local development?

No. The header is sent only when `HSTS_MAX_AGE` is set and the request arrived over TLS or with `X-Forwarded-Proto: https`. A plain `curl http://localhost:8080` never receives it, and the test suite asserts that.

### Does this affect the Postman API tests?

No. The Realworld collection run by Newman in the `api-test` job asserts status codes and JSON bodies, which do not change. The agent runs the Go tests and lint locally; the workflow runs the collection on the pull request.

### What about the token in the access_token query parameter?

`Referrer-Policy: no-referrer` stops a browser from leaking such a URL to another site, which is the part a header can fix. Removing query-string tokens from `AuthMiddleware` is an API change for its clients and is left out of this pull request, with a note in the description.

## More Gin jobs

- [Add Structured Logging to a Gin API from a Linear Issue](https://getrush.ai/run/add-structured-logging/gin/)
- [Inventory the API Endpoints of a Gin Service](https://getrush.ai/run/api-endpoint-inventory/gin/)
- [Dockerize a Gin API](https://getrush.ai/run/dockerize-app/gin/)

## The same job on other stacks

- [Add Security Headers to a Hono App](https://getrush.ai/run/add-security-headers/hono/)
- [Add Security Headers to a Koa App](https://getrush.ai/run/add-security-headers/koa/)
- [Add Security Headers to a Leptos Axum App](https://getrush.ai/run/add-security-headers/leptos/)

## 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/)
