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
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:
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: security-173description: 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
8> **Ash projects**: `AshAuthentication` has its own strategy/token patterns — use the `ash-framework` skill. CSRF, XSS, and secret management patterns below still apply.
9
10Quick reference for security patterns in Elixir/Phoenix.
11
12## Iron Laws — Never Violate These
13
141. **VALIDATE AT BOUNDARIES** — Never trust client input. All data through changesets
152. **NEVER INTERPOLATE USER INPUT** — Use Ecto's `^` operator, never string interpolation
163. **NO String.to_atom WITH USER INPUT** — Atom exhaustion DoS. Use `to_existing_atom/1`
174. **AUTHORIZE EVERYWHERE** — Check in contexts AND re-validate in LiveView events
185. **ESCAPE BY DEFAULT** — Never use `raw/1` with untrusted content
196. **SECRETS NEVER IN CODE** — All secrets in `runtime.exs` from env vars
20
21## Quick Patterns
22
23### Timing-Safe Authentication
24
25```elixir
26def authenticate(email, password) do
27 user = Repo.get_by(User, email: email)
28
29 cond do
30 user && Argon2.verify_pass(password, user.hashed_password) ->
31 {:ok, user}
32 user ->
33 {:error, :invalid_credentials}
34 true ->
35 Argon2.no_user_verify() # Timing attack prevention
36 {:error, :invalid_credentials}
37 end
38end
39```
40
41### LiveView Authorization (CRITICAL)
42
43```elixir
44# RE-AUTHORIZE IN EVERY EVENT HANDLER
45def handle_event("delete", %{"id" => id}, socket) do
46 post = Blog.get_post!(id)
47
48 # Don't trust that mount authorized this action!
49 with :ok <- Bodyguard.permit(Blog, :delete_post, socket.assigns.current_user, post) do
50 Blog.delete_post(post)
51 {:noreply, stream_delete(socket, :posts, post)}
52 else
53 _ -> {:noreply, put_flash(socket, :error, "Unauthorized")}
54 end
55end
56```
57
58### SQL Injection Prevention
59
60```elixir
61# ✅ SAFE: Parameterized queries
62from(u in User, where: u.name == ^user_input)
63
64# ❌ VULNERABLE: String interpolation
65from(u in User, where: fragment("name = '#{user_input}'"))
66```
67
68## Quick Decisions
69
70### What to validate?
71
72- **All user input** → Ecto changesets
73- **File uploads** → Extension + magic bytes + size
74- **Paths** → `Path.safe_relative/2` for traversal
75- **Atoms** → `String.to_existing_atom/1` only
76
77### What to escape?
78
79- **HTML output** → Auto-escaped by default (`<%= %>`)
80- **User HTML** → HtmlSanitizeEx with scrubber
81- **Never** → `raw/1` with untrusted content
82
83## Anti-patterns
84
85| Wrong | Right |
86|-------|-------|
87| `"SELECT * FROM users WHERE name = '#{name}'"` | `from(u in User, where: u.name == ^name)` |
88| `String.to_atom(user_input)` | `String.to_existing_atom(user_input)` |
89| `<%= raw @user_comment %>` | `<%= @user_comment %>` |
90| Hardcoded secrets in config | `runtime.exs` from env vars |
91| Auth only in mount | Re-auth in every `handle_event` |
92
93## References
94
95For detailed patterns, see:
96
97- `references/authentication.md` - phx.gen.auth, MFA, sessions
98- `references/authorization.md` - Bodyguard, scopes, LiveView auth
99- `references/input-validation.md` - Changesets, file uploads, paths
100- `references/security-headers.md` - CSP, CSRF, rate limiting, headers
101- `references/oauth-linking.md` - OAuth account linking, token management
102- `references/rate-limiting.md` - Composite key strategies, Hammer patterns
103- `references/advanced-patterns.md` - SSRF prevention, secrets management, supply chain