name: security description: Elixir/Phoenix安全模式 - 身份认证、授权、输入验证、OWASP。在实施安全功能时加载。 user-invocable: false
Elixir/Phoenix 安全参考
快速参考Elixir/Phoenix中的安全模式。
铁律 — 切勿违反
- 在边界验证 — 永远不要信任客户端输入。所有数据通过变化集
- 永不插值用户输入 — 使用Ecto的
^操作符,永不使用字符串插值 - 不使用String.to_atom处理用户输入 — 原子耗尽DoS。使用
to_existing_atom/1 - 处处授权 — 在上下文中检查并在LiveView事件中重新验证
- 默认转义 — 永不使用
raw/1处理不受信任的内容 - 秘密永不放在代码中 — 所有秘密在
runtime.exs中从环境变量获取
快速模式
时序安全身份认证
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() # 时序攻击预防
{:error, :invalid_credentials}
end
end
LiveView授权(关键)
# 在每个事件处理程序中重新授权
def handle_event("delete", %{"id" => id}, socket) do
post = Blog.get_post!(id)
# 不要信任mount已经授权了这个操作!
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, "未经授权")}
end
end
SQL注入预防
# ✅ 安全:参数化查询
from(u in User, where: u.name == ^user_input)
# ❌ 易受攻击:字符串插值
from(u in User, where: fragment("name = '#{user_input}'"))
快速决策
验证什么?
- 所有用户输入 → Ecto变化集
- 文件上传 → 扩展名 + 魔术字节 + 大小
- 路径 → 使用
Path.safe_relative/2防止遍历 - 原子 → 仅使用
String.to_existing_atom/1
转义什么?
- HTML输出 → 默认自动转义 (
<%= %>) - 用户HTML → 使用HtmlSanitizeEx和清理器
- 永不 → 使用
raw/1处理不受信任的内容
反模式
| 错误 | 正确 |
|---|---|
"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 %> |
| 配置中硬编码秘密 | runtime.exs中从环境变量获取秘密 |
| 仅在mount中授权 | 在每个handle_event中重新授权 |
参考资料
详细模式,请见:
references/authentication.md- phx.gen.auth, MFA, sessionsreferences/authorization.md- Bodyguard, scopes, LiveView authreferences/input-validation.md- Changesets, file uploads, pathsreferences/security-headers.md- CSP, CSRF, rate limiting, headersreferences/oauth-linking.md- OAuth账户链接,令牌管理references/rate-limiting.md- 复合键策略,Hammer模式references/advanced-patterns.md- SSRF预防,秘密管理,供应链