--- name: security-essentials description: "Use when Elixir/Phoenix code handles params or other user input, String.to_atom on external strings, tokens, redirects, raw SQL, deserialization, outbound HTTP or security headers, or when asked to review code for security — injection, XSS, atom exhaustion, SSRF, open redirects, CSP, timing attacks, Sobelow. Not for permission rules (use phoenix-authorization-patterns)." --- # Security Essentials > Verified against Elixir 1.20, Phoenix 1.8, LiveView 1.2, Ecto 3.14 — October 2026 ## RULES — Follow these with no exceptions 1. **Never use `String.to_atom/1` on user input** — atoms are never garbage collected; `String.to_existing_atom/1` raises on unknown input (a 500). Map known strings with a `case` 2. **Never build SQL or identifiers from user input** — `fragment` already rejects interpolated strings at compile time; the real holes are `Repo.query`/`SQL.query` with string interpolation and user-chosen columns (`field(p, ^name)`, `identifier(^name)`, `order_by: ^...`). Use `$1` parameters and allowlist columns with a `case` 3. **Never pass user input to `redirect(external: ...)`** — check the host against an allowlist first. `redirect(to: ...)` already raises on anything but a local path, so keep return paths server-side (session) like phx.gen.auth 4. **Avoid `raw/1`** — HEEx escapes `{@x}`; if HTML is required, sanitize with HtmlSanitizeEx first 5. **Keep secrets out of logs** — `redact: true` on sensitive schema fields, extend `:filter_parameters`, and never pass tokens or credentials as Logger metadata or message text 6. **Compare secrets with `Plug.Crypto.secure_compare/2`** — never `==` or a pattern match 7. **Never `:erlang.binary_to_term/1` untrusted bytes** — it can build functions and atoms; use JSON, or `Plug.Crypto.non_executable_binary_to_term(bin, [:safe])` 8. **Give every signed token a purpose and an explicit `max_age`** — `Phoenix.Token.verify(endpoint, "purpose", token, max_age: ...)`; `Phoenix.Token` can't be revoked, so use database tokens (phx.gen.auth `UserToken`) for login sessions and API keys 9. **Validate outbound URLs (SSRF)** — allowlist scheme and host before `Req.get(url)`, and disable redirects 10. **Production transport and headers** — keep the generated `force_ssl` (HSTS), and replace the default CSP, which only sets `base-uri` and `frame-ancestors` 11. **Run audits after dependency changes** — `mix hex.audit`, `mix deps.audit`, `mix sobelow` --- ## Atom Table Exhaustion The atom table has a fixed limit (default 1,048,576) and is never garbage collected. Filling it crashes the whole VM. ```elixir role = String.to_atom(params["role"]) # unbounded atom creation status = String.to_existing_atom(params["status"]) # ArgumentError (500) on unknown input ``` ```elixir def parse_role("admin"), do: {:ok, :admin} def parse_role("member"), do: {:ok, :member} def parse_role(_), do: {:error, :invalid_role} ``` For schema fields, `Ecto.Enum` does this mapping for you when you `cast`. --- ## SQL Injection The query DSL parameterizes `^values`, and `fragment("lower(#{x})")` is a compile error ("to prevent SQL injection attacks, fragment(...) does not allow strings to be interpolated"). The risks that remain: ```elixir # Raw SQL built with interpolation — injection Repo.query("SELECT * FROM users WHERE email = '#{email}'") # User picks the column: ?sort=hashed_password orders (and leaks) by the password hash order_by(query, [u], asc: field(u, ^String.to_existing_atom(params["sort"]))) # identifier/1 is quoted, but the user still chooses which column or table is read fragment("SELECT ? FROM users", identifier(^params["column"])) ``` ```elixir # Parameters for raw SQL Repo.query("SELECT * FROM users WHERE email = $1", [email]) # Allowlist user-chosen columns defp sort_field("name"), do: :name defp sort_field("inserted_at"), do: :inserted_at defp sort_field(_), do: :inserted_at def list_users(params) do from(u in User, order_by: [asc: field(u, ^sort_field(params["sort"])), asc: u.id]) |> Repo.all() end ``` `splice(^list)` sends each element as a parameter and is safe. `constant(^value)` inlines the value into the SQL (escaped), so each distinct value creates a new prepared query: don't feed it user input. --- ## Open Redirects `redirect(conn, to: path)` raises `ArgumentError` unless `path` starts with a single `/` and contains no `\`, tab or newline. So `to: params["return_to"]` is a crash, not an open redirect. The risk is `external:`, in controllers and in LiveView (`redirect(socket, external: url)`). ```elixir def callback(conn, %{"next" => next}) do redirect(conn, external: next) # https://evil.example/login looks like it came from you end ``` ```elixir @allowed_hosts ["docs.example.com", "billing.example.com"] def callback(conn, %{"next" => next}) do case URI.new(next) do {:ok, %URI{scheme: "https", host: host}} when host in @allowed_hosts -> redirect(conn, external: next) _ -> redirect(conn, to: ~p"/") end end ``` For "return to where you were", copy phx.gen.auth: `maybe_store_return_to/1` saves `current_path(conn)` in the session on GET requests and `log_in_user/3` redirects to it with `to:`. The path never comes from a query param. --- ## Cross-Site Scripting (XSS) HEEx escapes every `{@value}` in text and attributes. `raw/1` turns that off. ```heex
{raw(@user_bio)}
website ``` ```heex
{@user_bio}
{raw(HtmlSanitizeEx.basic_html(@user_bio))}

{@comment_body}

``` - `Phoenix.HTML.Format` was removed in phoenix_html 4. To keep line breaks in plain text, use CSS (`whitespace-pre-line`) rather than generating `
` tags. - Escaping doesn't make a URL safe: `href={@user_url}` with `javascript:alert(1)` still runs. Validate that the scheme is `http`/`https` before storing user URLs. - Uploaded files are another XSS route: see the `phoenix-uploads` skill. Never derive the stored extension or the served content type from the client. ### Content Security Policy The `:browser` pipeline's `put_secure_browser_headers` sets only `content-security-policy: base-uri 'self'; frame-ancestors 'self';`. That's clickjacking protection, not XSS protection. Pass a real policy: ```elixir # router.ex @csp "default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; " <> "img-src 'self' data: blob:; connect-src 'self'; frame-ancestors 'self'; " <> "base-uri 'self'; form-action 'self'; object-src 'none'" pipeline :browser do plug :accepts, ["html"] plug :fetch_session plug :fetch_live_flash plug :put_root_layout, html: {MyAppWeb.Layouts, :root} plug :protect_from_forgery plug :put_secure_browser_headers, %{"content-security-policy" => @csp} plug :fetch_current_scope_for_user end ``` The Phoenix 1.8 root layout includes an inline theme `