Elixir/Phoenix Security Reference
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
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)
# 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
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 |
References
For detailed patterns, see:
${CLAUDE_SKILL_DIR}/references/authentication.md - phx.gen.auth, MFA, sessions
${CLAUDE_SKILL_DIR}/references/authorization.md - Bodyguard, scopes, LiveView auth
${CLAUDE_SKILL_DIR}/references/input-validation.md - Changesets, file uploads, paths
${CLAUDE_SKILL_DIR}/references/security-headers.md - CSP, CSRF, rate limiting, headers
${CLAUDE_SKILL_DIR}/references/oauth-linking.md - OAuth account linking, token management
${CLAUDE_SKILL_DIR}/references/rate-limiting.md - Composite key strategies, Hammer patterns
${CLAUDE_SKILL_DIR}/references/advanced-patterns.md - SSRF prevention, secrets management, supply chain
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: security-243description: Enforce Elixir/Phoenix security — auth, OAuth, sessions, CSRF, XSS, SQL injection, input validation, secrets. Use when editing auth files, login flows, RBAC, or API keys. Use when this capability is needed.4---56# Elixir/Phoenix Security Reference78Quick reference for security patterns in Elixir/Phoenix.910## Iron Laws — Never Violate These11121. **VALIDATE AT BOUNDARIES** — Never trust client input. All data through changesets132. **NEVER INTERPOLATE USER INPUT** — Use Ecto's `^` operator, never string interpolation143. **NO String.to_atom WITH USER INPUT** — Atom exhaustion DoS. Use `to_existing_atom/1`154. **AUTHORIZE EVERYWHERE** — Check in contexts AND re-validate in LiveView events165. **ESCAPE BY DEFAULT** — Never use `raw/1` with untrusted content176. **SECRETS NEVER IN CODE** — All secrets in `runtime.exs` from env vars1819## Quick Patterns2021### Timing-Safe Authentication2223```elixir24def authenticate(email, password) do25 user = Repo.get_by(User, email: email)2627 cond do28 user && Argon2.verify_pass(password, user.hashed_password) ->29 {:ok, user}30 user ->31 {:error, :invalid_credentials}32 true ->33 Argon2.no_user_verify() # Timing attack prevention34 {:error, :invalid_credentials}35 end36end37```3839### LiveView Authorization (CRITICAL)4041```elixir42# RE-AUTHORIZE IN EVERY EVENT HANDLER43def handle_event("delete", %{"id" => id}, socket) do44 post = Blog.get_post!(id)4546 # Don't trust that mount authorized this action!47 with :ok <- Bodyguard.permit(Blog, :delete_post, socket.assigns.current_user, post) do48 Blog.delete_post(post)49 {:noreply, stream_delete(socket, :posts, post)}50 else51 _ -> {:noreply, put_flash(socket, :error, "Unauthorized")}52 end53end54```5556### SQL Injection Prevention5758```elixir59# ✅ SAFE: Parameterized queries60from(u in User, where: u.name == ^user_input)6162# ❌ VULNERABLE: String interpolation63from(u in User, where: fragment("name = '#{user_input}'"))64```6566## Quick Decisions6768### What to validate?6970- **All user input** → Ecto changesets71- **File uploads** → Extension + magic bytes + size72- **Paths** → `Path.safe_relative/2` for traversal73- **Atoms** → `String.to_existing_atom/1` only7475### What to escape?7677- **HTML output** → Auto-escaped by default (`<%= %>`)78- **User HTML** → HtmlSanitizeEx with scrubber79- **Never** → `raw/1` with untrusted content8081## Anti-patterns8283| Wrong | Right |84|-------|-------|85| `"SELECT * FROM users WHERE name = '#{name}'"` | `from(u in User, where: u.name == ^name)` |86| `String.to_atom(user_input)` | `String.to_existing_atom(user_input)` |87| `<%= raw @user_comment %>` | `<%= @user_comment %>` |88| Hardcoded secrets in config | `runtime.exs` from env vars |89| Auth only in mount | Re-auth in every `handle_event` |9091## References9293For detailed patterns, see:9495- `${CLAUDE_SKILL_DIR}/references/authentication.md` - phx.gen.auth, MFA, sessions96- `${CLAUDE_SKILL_DIR}/references/authorization.md` - Bodyguard, scopes, LiveView auth97- `${CLAUDE_SKILL_DIR}/references/input-validation.md` - Changesets, file uploads, paths98- `${CLAUDE_SKILL_DIR}/references/security-headers.md` - CSP, CSRF, rate limiting, headers99- `${CLAUDE_SKILL_DIR}/references/oauth-linking.md` - OAuth account linking, token management100- `${CLAUDE_SKILL_DIR}/references/rate-limiting.md` - Composite key strategies, Hammer patterns101- `${CLAUDE_SKILL_DIR}/references/advanced-patterns.md` - SSRF prevention, secrets management, supply chain102103---104> Converted and distributed by [TomeVault](https://tomevault.io/claim/oliver-kriska) — claim your Tome and manage your conversions.105<!-- tomevault:4.0:skill_md:2026-04-11 -->