---
url: /runcobo/guide/security.md
description: >-
  What Runcobo protects against by default, and what your application must do —
  input, SQL, HTML escaping, authentication, CSRF, proxies, secrets and headers.
---

# Security

Runcobo closes the common holes by default and leaves the rest visible in your code. This page lists both: what you get for free, and what each application must decide.

## What Runcobo does for you

| Risk | Default |
| --- | --- |
| Malformed or unexpected input | [Contracts](/guide/contracts) check types and constraints; JSON is never coerced; undeclared fields are dropped |
| Huge request bodies | Bodies over **1 MiB** are rejected with `413` before they're buffered ([limits](/guide/uploads#body-size-limit)) |
| SQL injection | Generated queries always send values as bind parameters ([database](/guide/database)) |
| HTML injection in templates | Water escapes text inside tags; Jbuilder encodes JSON |
| Leaking errors | Unhandled exceptions become a bare `500`; messages and stack traces stay in the log ([errors](/guide/errors#unhandled-exceptions)) |
| Spoofed client IPs | `X-Forwarded-*` headers are ignored until you list trusted proxies ([proxies](/guide/proxies)) |
| Path traversal | Static files resolve strictly inside their directory; `..`, encoded `..` and outside symlinks are "not found" ([static files](/guide/static-files)) |
| Leftover uploads | Temporary upload files are deleted at the end of every request |

## Validate every input

Read input only through `validate`. It checks the path, query and body together and gives you typed values:

```crystal
call do
  input = validate(UpdatePostContract)   # anything below this line has valid input
  # ...
end
```

* Constrain sizes and ranges in the contract — `max_size:`, `gteq:`, `lteq:`, `allowed_values:` — so a client can't send a 10 MB title or `per_page=1000000`.
* Fields the contract doesn't declare are ignored. Pass `strict: true` to reject them instead, which catches typos and mass-assignment attempts early.
* Avoid reading `request.query_params` or `request.route_params` directly: those values are unchecked strings.

## Write SQL with parameters

Every value in a generated query is a bind parameter — `sqlc.arg(title)` becomes `$1`, never pasted into the SQL text:

```sql
-- name: GetPost :one
SELECT id, title FROM posts WHERE id = sqlc.arg(id);
```

Keep it that way: don't build SQL strings with interpolation in hand-written code. For optional filters, use a fixed query with `sqlc.narg` ([recipe](/guide/query-recipes#optional-filters)) instead of concatenating `WHERE` clauses. An `ORDER BY` column chosen by the client must come from a fixed list, for example with `allowed_values:` in the contract and a `CASE` in the query.

## Authenticate before reading the body

Put authentication in a `before` [filter](/guide/filters), usually on a base class, and fail closed:

```crystal [src/actions/admin_action.cr]
require "crypto/subtle"

abstract class Blog::AdminAction < Blog::BaseAction
  before authenticate

  private def authenticate
    expected = ENV["BLOG_ADMIN_TOKEN"]?
    given = request.headers["Authorization"]?.try(&.lchop?("Bearer "))
    unless expected && !expected.empty? && given && Crypto::Subtle.constant_time_compare(given, expected)
      render_json({error: "unauthorized"}, status_code: 401)
      return byebye
    end
  end
end
```

* A `before` filter runs before the body is read, so an unauthenticated client can't make the server parse a large upload.
* **Fail closed:** a missing configuration value must deny, not allow.
* Compare secrets with `Crypto::Subtle.constant_time_compare`, not `==`, so response timing doesn't reveal how much of a token was right.
* Prefer one protected base class over remembering a filter on every action. Opt specific actions out with [`skip`](/guide/filters#skipping-an-inherited-filter), so the exceptions are explicit.
* **Authorization is separate:** after authenticating, check that *this* user may touch *this* record, typically by including the owner in the query (`WHERE id = $1 AND author_id = $2`).

## Escaping HTML

[Water](/guide/views#water) escapes text passed to a tag, so this is safe with any title:

```crystal
h1 post.title        # <h1>&lt;script&gt;...</h1>
```

Two places are **not** escaped:

* **Attributes** — the `%|...|` string is written as is. Interpolate only values you control, such as numeric IDs, or escape them with `HTML.escape`:

  ```crystal
  a %|href="/posts/#{post.id}"|, post.title                         # an Int64: safe
  a %|href="#{HTML.escape(user.website)}" rel="nofollow"|, user.name  # escaped
  ```

* **`text`** — writes raw HTML. Use it for markup you wrote, never for user input.

A URL from a user can still be `javascript:...` after escaping; accept only `http://` and `https://` URLs in the contract (for example with a rule) before rendering them as links.

JSON from [Jbuilder](/guide/views#jbuilder) or `render_json` is always properly encoded.

## CSRF and cookies

Runcobo has no built-in sessions, so there's nothing to forge by default. An API authenticated with a header (`Authorization: Bearer ...`) isn't exposed to cross-site request forgery, because browsers don't attach that header automatically.

If you authenticate HTML forms with a cookie, protect state-changing requests yourself:

* set the cookie with `http_only: true`, `secure: true` and `samesite: :lax` (or `:strict`),
* accept changes only through `POST`, `PATCH`, `PUT` and `DELETE`, never `GET`,
* and check a CSRF token, or the `Origin` header, in a `before` filter.

```crystal
context.response.cookies << HTTP::Cookie.new("session", token,
  http_only: true, secure: true, samesite: HTTP::Cookie::SameSite::Lax)
```

## CORS

Runcobo sends no CORS headers, so browsers block cross-origin calls to your API by default. If a front end on another origin needs access, allow exactly that origin — not `*` with credentials — in a [handler](/guide/server#custom-handlers) that also answers `OPTIONS` preflight requests.

## Behind a proxy

Configure [trusted proxies](/guide/proxies) only for the load balancers actually in front of the app. Trusting a range that clients can reach lets them choose their own `remote_ip`, which breaks rate limits and audit logs.

Terminate TLS at the proxy or with Runcobo's [TLS options](/guide/server#tls), and serve the app only over HTTPS in production.

## Secrets

* Read secrets from environment variables, as the [deployment guide](/guide/deployment#_2-configure-with-environment-variables) does. Don't commit them.
* `cobo dev` can generate a development secret for you ([`secret_environment`](/cli/configuration)); production needs its own.
* Don't log tokens, passwords or full request bodies. Runcobo's request log has the method, path, status and duration — not headers or bodies.

## Security headers

Set the headers your application needs in a `before` filter on the base action — before anything is written, so they're always sent — or in a [handler](/guide/server#custom-handlers) for every response:

```crystal
abstract class Blog::BaseAction < ::BaseAction
  before security_headers

  private def security_headers
    headers = context.response.headers
    headers["X-Content-Type-Options"] = "nosniff"
    headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
    headers["X-Frame-Options"] = "DENY"
  end
end
```

HTML applications should also set a `Content-Security-Policy`.

## Rate limiting

Runcobo doesn't limit request rates. Do it at the proxy or load balancer, or in a `before` filter keyed by `request.remote_ip` (with [trusted proxies](/guide/proxies) configured) or by the authenticated user.

## Checklist

* \[ ] Every action reads input with `validate`, and contracts bound sizes and ranges.
* \[ ] No SQL is built by string interpolation.
* \[ ] Authentication is a `before` filter on a base class, and fails closed.
* \[ ] Records are scoped to the user who may access them.
* \[ ] Untrusted values never go into Water attributes or `text` unescaped.
* \[ ] Cookie-authenticated forms check a CSRF token or `Origin`.
* \[ ] Only real proxies are trusted; production is HTTPS only.
* \[ ] Secrets come from the environment and never reach the log.
