Elixir/Phoenix Security Reference
Ash projects: AshAuthentication has its own strategy/token patterns — use the ash-framework skill. CSRF, XSS, and secret management patterns below still apply.
Quick reference for security patterns in Elixir/Phoenix.
Iron Laws — Never Violate These
- VALIDATE AT BOUNDARIES — Never trust client input. All data through changesets
- NEVER INTERPOLATE USER INPUT — Use Ecto's
^ operator, never string interpolation
- NO String.to_atom WITH USER INPUT — Atom exhaustion DoS. Use
to_existing_atom/1
- AUTHORIZE EVERYWHERE — Check in contexts AND re-validate in LiveView events
- ESCAPE BY DEFAULT — Never use
raw/1 with untrusted content
- SECRETS NEVER IN CODE — All secrets in
runtime.exs from env vars
- LIVEVIEW EVENT PARAMS ARE UNTRUSTED — Users can alter forms, hooks, and every
phx-value-* in DevTools. Validate and authorize against server-side state before acting
Quick Patterns
Timing-Safe Authentication
def authenticate(email, password) do
user = Repo.get_by(User, email: email)
cond do
user && Argon2.verify_pass(password, user.hashed_password) ->
{:ok, user}
user ->
{:error, :invalid_credentials}
true ->
Argon2.no_user_verify() # Timing attack prevention
{:error, :invalid_credentials}
end
end
LiveView Authorization (CRITICAL)
# `id` is client input even when it came from phx-value-id.
# RE-AUTHORIZE IN EVERY EVENT HANDLER
def handle_event("delete", %{"id" => id}, socket) do
post = Blog.get_post!(id)
# Don't trust that mount authorized this action!
with :ok <- Bodyguard.permit(Blog, :delete_post, socket.assigns.current_user, post) do
Blog.delete_post(post)
{:noreply, stream_delete(socket, :posts, post)}
else
_ -> {:noreply, put_flash(socket, :error, "Unauthorized")}
end
end
Rendered LiveView events can expose IDs in HTML and websocket payloads. That is
not automatically a vulnerability: treat IDs as public identifiers, never as
proof of access. Use opaque references only when the identifier itself must not
be disclosed, and still perform server-side authorization.
SQL Injection Prevention
# ✅ SAFE: Parameterized queries
from(u in User, where: u.name == ^user_input)
# ❌ VULNERABLE: String interpolation
from(u in User, where: fragment("name = '#{user_input}'"))
Quick Decisions
What to validate?
- All user input → Ecto changesets
- File uploads → Extension + magic bytes + size
- Paths →
Path.safe_relative/2 for traversal
- Atoms →
String.to_existing_atom/1 only
What to escape?
- HTML output → Auto-escaped by default (
<%= %>)
- User HTML → HtmlSanitizeEx with scrubber
- Never →
raw/1 with untrusted content
Anti-patterns
| Wrong |
Right |
"SELECT * FROM users WHERE name = '#{name}'" |
from(u in User, where: u.name == ^name) |
String.to_atom(user_input) |
String.to_existing_atom(user_input) |
<%= raw @user_comment %> |
<%= @user_comment %> |
| Hardcoded secrets in config |
runtime.exs from env vars |
| Auth only in mount |
Re-auth in every handle_event |
Trusting phx-value-* or hidden IDs |
Load server-side state and authorize it |
References
For detailed patterns, see:
references/authentication.md - phx.gen.auth, MFA, sessions
references/authorization.md - Bodyguard, scopes, LiveView auth
references/input-validation.md - Changesets, file uploads, paths
references/security-headers.md - CSP, CSRF, rate limiting, headers
references/oauth-linking.md - OAuth account linking, token management
references/rate-limiting.md - Composite key strategies, Hammer patterns
references/advanced-patterns.md - SSRF prevention, secrets management, supply chain
1---2name: security3description: Enforce Elixir/Phoenix security — auth, OAuth, sessions, CSRF, XSS; Use4 when editing auth files, login flows, RBAC…5---67# Elixir/Phoenix Security Reference89> **Ash projects**: `AshAuthentication` has its own strategy/token patterns — use the `ash-framework` skill. CSRF, XSS, and secret management patterns below still apply.1011Quick reference for security patterns in Elixir/Phoenix.1213## Iron Laws — Never Violate These14151. **VALIDATE AT BOUNDARIES** — Never trust client input. All data through changesets162. **NEVER INTERPOLATE USER INPUT** — Use Ecto's `^` operator, never string interpolation173. **NO String.to_atom WITH USER INPUT** — Atom exhaustion DoS. Use `to_existing_atom/1`184. **AUTHORIZE EVERYWHERE** — Check in contexts AND re-validate in LiveView events195. **ESCAPE BY DEFAULT** — Never use `raw/1` with untrusted content206. **SECRETS NEVER IN CODE** — All secrets in `runtime.exs` from env vars217. **LIVEVIEW EVENT PARAMS ARE UNTRUSTED** — Users can alter forms, hooks, and every `phx-value-*` in DevTools. Validate and authorize against server-side state before acting2223## Quick Patterns2425### Timing-Safe Authentication2627```elixir28def authenticate(email, password) do29 user = Repo.get_by(User, email: email)3031 cond do32 user && Argon2.verify_pass(password, user.hashed_password) ->33 {:ok, user}34 user ->35 {:error, :invalid_credentials}36 true ->37 Argon2.no_user_verify() # Timing attack prevention38 {:error, :invalid_credentials}39 end40end41```4243### LiveView Authorization (CRITICAL)4445```elixir46# `id` is client input even when it came from phx-value-id.47# RE-AUTHORIZE IN EVERY EVENT HANDLER48def handle_event("delete", %{"id" => id}, socket) do49 post = Blog.get_post!(id)5051 # Don't trust that mount authorized this action!52 with :ok <- Bodyguard.permit(Blog, :delete_post, socket.assigns.current_user, post) do53 Blog.delete_post(post)54 {:noreply, stream_delete(socket, :posts, post)}55 else56 _ -> {:noreply, put_flash(socket, :error, "Unauthorized")}57 end58end59```6061Rendered LiveView events can expose IDs in HTML and websocket payloads. That is62not automatically a vulnerability: treat IDs as public identifiers, never as63proof of access. Use opaque references only when the identifier itself must not64be disclosed, and still perform server-side authorization.6566### SQL Injection Prevention6768```elixir69# ✅ SAFE: Parameterized queries70from(u in User, where: u.name == ^user_input)7172# ❌ VULNERABLE: String interpolation73from(u in User, where: fragment("name = '#{user_input}'"))74```7576## Quick Decisions7778### What to validate?7980- **All user input** → Ecto changesets81- **File uploads** → Extension + magic bytes + size82- **Paths** → `Path.safe_relative/2` for traversal83- **Atoms** → `String.to_existing_atom/1` only8485### What to escape?8687- **HTML output** → Auto-escaped by default (`<%= %>`)88- **User HTML** → HtmlSanitizeEx with scrubber89- **Never** → `raw/1` with untrusted content9091## Anti-patterns9293| Wrong | Right |94|-------|-------|95| `"SELECT * FROM users WHERE name = '#{name}'"` | `from(u in User, where: u.name == ^name)` |96| `String.to_atom(user_input)` | `String.to_existing_atom(user_input)` |97| `<%= raw @user_comment %>` | `<%= @user_comment %>` |98| Hardcoded secrets in config | `runtime.exs` from env vars |99| Auth only in mount | Re-auth in every `handle_event` |100| Trusting `phx-value-*` or hidden IDs | Load server-side state and authorize it |101102## References103104For detailed patterns, see:105106- `references/authentication.md` - phx.gen.auth, MFA, sessions107- `references/authorization.md` - Bodyguard, scopes, LiveView auth108- `references/input-validation.md` - Changesets, file uploads, paths109- `references/security-headers.md` - CSP, CSRF, rate limiting, headers110- `references/oauth-linking.md` - OAuth account linking, token management111- `references/rate-limiting.md` - Composite key strategies, Hammer patterns112- `references/advanced-patterns.md` - SSRF prevention, secrets management, supply chain