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
1---2name: security-213description: 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.4---5
6# Elixir/Phoenix Security Reference
7
8Quick reference for security patterns in Elixir/Phoenix.
9
10## Iron Laws — Never Violate These
11
121. **VALIDATE AT BOUNDARIES** — Never trust client input. All data through changesets
132. **NEVER INTERPOLATE USER INPUT** — Use Ecto's `^` operator, never string interpolation
143. **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 events
165. **ESCAPE BY DEFAULT** — Never use `raw/1` with untrusted content
176. **SECRETS NEVER IN CODE** — All secrets in `runtime.exs` from env vars
18
19## Quick Patterns
20
21### Timing-Safe Authentication
22
23```elixir
24def authenticate(email, password) do
25 user = Repo.get_by(User, email: email)
26
27 cond do
28 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 prevention
34 {:error, :invalid_credentials}
35 end
36end
37```
38
39### LiveView Authorization (CRITICAL)
40
41```elixir
42# RE-AUTHORIZE IN EVERY EVENT HANDLER
43def handle_event("delete", %{"id" => id}, socket) do
44 post = Blog.get_post!(id)
45
46 # Don't trust that mount authorized this action!
47 with :ok <- Bodyguard.permit(Blog, :delete_post, socket.assigns.current_user, post) do
48 Blog.delete_post(post)
49 {:noreply, stream_delete(socket, :posts, post)}
50 else
51 _ -> {:noreply, put_flash(socket, :error, "Unauthorized")}
52 end
53end
54```
55
56### SQL Injection Prevention
57
58```elixir
59# ✅ SAFE: Parameterized queries
60from(u in User, where: u.name == ^user_input)
61
62# ❌ VULNERABLE: String interpolation
63from(u in User, where: fragment("name = '#{user_input}'"))
64```
65
66## Quick Decisions
67
68### What to validate?
69
70- **All user input** → Ecto changesets
71- **File uploads** → Extension + magic bytes + size
72- **Paths** → `Path.safe_relative/2` for traversal
73- **Atoms** → `String.to_existing_atom/1` only
74
75### What to escape?
76
77- **HTML output** → Auto-escaped by default (`<%= %>`)
78- **User HTML** → HtmlSanitizeEx with scrubber
79- **Never** → `raw/1` with untrusted content
80
81## Anti-patterns
82
83| 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` |
90
91## References
92
93For detailed patterns, see:
94
95- `${CLAUDE_SKILL_DIR}/references/authentication.md` - phx.gen.auth, MFA, sessions
96- `${CLAUDE_SKILL_DIR}/references/authorization.md` - Bodyguard, scopes, LiveView auth
97- `${CLAUDE_SKILL_DIR}/references/input-validation.md` - Changesets, file uploads, paths
98- `${CLAUDE_SKILL_DIR}/references/security-headers.md` - CSP, CSRF, rate limiting, headers
99- `${CLAUDE_SKILL_DIR}/references/oauth-linking.md` - OAuth account linking, token management
100- `${CLAUDE_SKILL_DIR}/references/rate-limiting.md` - Composite key strategies, Hammer patterns
101- `${CLAUDE_SKILL_DIR}/references/advanced-patterns.md` - SSRF prevention, secrets management, supply chain