All jobs

Add Security Headers to a chi API

Yes. An agent adds a chi middleware that sets nosniff, frame, referrer and content security headers, turns on HSTS only behind TLS, and tests it with httptest.

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 reads the router before writing a header. In a service laid out like dhax/go-base, api/api.go builds the mux in New(enableCORS bool) with middleware.Recoverer, middleware.RequestID, a commented-out middleware.RealIP, middleware.Timeout(15 * time.Second), the structured logrus logger from logging/ and render.SetContentType(render.ContentTypeJSON), adds the go-chi/cors handler from corsConfig() when enable_cors is set, mounts /auth, then /admin and /api behind jwt.Authenticator, answers /healthz with ok, and ends with r.Get("/*", SPAHandler("public")), which serves public/index.html and a service-worker.js for a single-page app that the placeholder page says to replace. api/server.go starts it with ListenAndServe on the viper port, so TLS terminates somewhere in front of the process, and .env.example and cmd/root.go show every setting is a viper key read from the environment.

The new middleware lives in api/headers.go as one func securityHeaders(next http.Handler) http.Handler. On every response it sets X-Content-Type-Options: nosniff, X-Frame-Options: DENY, Referrer-Policy: strict-origin-when-cross-origin, Permissions-Policy denying camera, microphone and geolocation, and Cross-Origin-Opener-Policy: same-origin. Strict-Transport-Security is set only when the request arrived over TLS, which the handler reads from r.TLS or from X-Forwarded-Proto: https, and only when a new viper key enable_hsts is true, because a header with max-age and includeSubDomains sent from a staging host on plain HTTP is remembered by browsers for the whole domain. The middleware is registered right after Recoverer so a panic's 500 carries the headers too.

Content-Security-Policy is two policies, not one. The JSON routes get default-src 'none'; frame-ancestors 'none', which is correct for an API that serves no HTML, set by the middleware. The /* route that serves the single-page app gets its own r.Group with a second middleware that reads csp_spa from viper and sets it only when non-empty, because the placeholder in public/index.html gives no way to know which scripts and styles the real app will load, and a guessed policy would break it on the first deploy. .env.example gains ENABLE_HSTS=false and an empty CSP_SPA with a comment showing a starting value.

The test follows auth/pwdless/api_test.go, which builds a chi.NewRouter, mounts a resource and serves it with httptest.NewServer. api/headers_test.go mounts a handler that writes ok behind securityHeaders, asserts each header on a plain request, asserts Strict-Transport-Security is absent on plain HTTP and present with X-Forwarded-Proto: https once enable_hsts is set through viper.Set, and asserts a request to the SPA group carries the SPA policy and not the API one. go vet ./... and go test -v ./..., the command .github/workflows/test.yml runs, pass, and cmd/gendoc.go regenerates routes.md, since docgen lists each router's middlewares there.

Start it with one API call

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

{
  "agent": "claude",
  "input": "Add security headers to this chi service. Read api/api.go, api/server.go, cmd/root.go, cmd/serve.go, .env.example, auth/pwdless/api_test.go, routes.md and .github/workflows/test.yml first. Write api/headers.go with a securityHeaders middleware that sets X-Content-Type-Options nosniff, X-Frame-Options DENY, Referrer-Policy strict-origin-when-cross-origin, a Permissions-Policy that denies camera, microphone and geolocation, Cross-Origin-Opener-Policy same-origin, and Content-Security-Policy default-src 'none'; frame-ancestors 'none' for the JSON routes. Set Strict-Transport-Security only when the request came over TLS (r.TLS or X-Forwarded-Proto https) and a new viper key enable_hsts is true. Register it right after Recoverer. Put the /* SPA route in its own group whose policy comes from a csp_spa viper key and is set only when non-empty. Add ENABLE_HSTS and CSP_SPA to .env.example. Write api/headers_test.go with httptest covering every header, HSTS absent on plain HTTP and present behind X-Forwarded-Proto with enable_hsts set, and the SPA group's separate policy. Regenerate routes.md with the gendoc command, run go vet ./... and go test -v ./..., and open a pull request with the output.",
  "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

The pull request adds api/headers.go and api/headers_test.go, changes api/api.go, .env.example and routes.md, and touches nothing under auth/, database/ or email/. Its description pastes the go test -v ./... output with the new test names and the header set from one curl -i against the sandbox's server, once over plain HTTP and once with the forwarded-proto header, so a reviewer sees the exact bytes a browser will receive.

Every JSON answer, including a 401 from jwt.Authenticator and a 500 from Recoverer, now carries the same headers, and a browser that lands on an API URL cannot sniff a response into HTML or frame it. The single-page app is unchanged until someone sets CSP_SPA, and HSTS stays off until someone who knows the domain is fully on TLS turns it on.

Before merging, a reviewer confirms the proxy in front of the service sets X-Forwarded-Proto and strips a client-supplied one, since the HSTS decision trusts that header, and decides the max-age to start with, because a long value cannot be taken back once browsers have seen it.

Run it on every Go service that answers a browser

A platform team with several chi services sends this body once per repository to POST /o/{org}/sessions from a script, each with its own 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. Each run reads its own router: a service that already uses a headers package gets only the missing headers and the test, one that terminates TLS itself reads r.TLS alone and ignores the forwarded header, and one that serves no HTML at all gets a single policy and no SPA group.

Each run opens its own pull request on its own branch. GET /o/{org}/sessions lists them newest first and the key's webhook_url receives a run.completed per run with the pull request in result, so the person who started the batch reads every header set from one place.

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

Why run it on Rush?

Security headers are cheap to add and easy to add wrong: an HSTS header sent from a plain-HTTP staging host, a content policy that blanks the single-page app, a frame header missing from error responses. The agent reads where TLS ends, where the HTML is served and which middleware runs first, and its test asserts the headers on the real net/http response rather than on a mocked writer.

The run keeps every command and its output, so the reviewer reads the test run and the curl -i output without a Go toolchain or a database. Several services can be covered at once, each in its own sandbox, and one that already sets the headers correctly gets only the test that proves it.

Frequently asked questions

Why not turn HSTS on by default?

Because ListenAndServe in api/server.go serves plain HTTP and the process cannot know whether the host in front of it has a certificate. A browser that once receives the header refuses plain HTTP for max-age seconds, so the agent makes it an explicit setting and documents it in .env.example.

Will the content policy break the single-page app?

No, because the /* route gets no policy until CSP_SPA is set. The JSON policy of default-src 'none' applies only to responses that are never rendered as a page, which is what render.SetContentType(render.ContentTypeJSON) makes every API answer.

Does this change CORS?

No. The go-chi/cors handler from corsConfig() keeps answering preflights when enable_cors is set, and the new headers are added beside its Access-Control-* ones. Cross-Origin-Opener-Policy does not affect XHR or fetch from another origin.

Why a hand-written middleware instead of a package?

Six static headers and one condition are fewer lines than a dependency's option struct, and chi/v5 already ships middleware.SetHeader for the simplest case. The agent uses the standard library only, so go.mod is unchanged and the pull request has no new module to audit.

More chi jobs

The same job on other stacks

Keep reading