8d652a2f34d9fe59210e3dcb3dbd86d7e9a2b49b
[akkoma] / lib / pleroma / plugs / http_security_plug.ex
1 defmodule Pleroma.Plugs.HTTPSecurityPlug do
2 alias Pleroma.Config
3 import Plug.Conn
4
5 def init(opts), do: opts
6
7 def call(conn, options) do
8 if Config.get([:http_security, :enabled]) do
9 conn =
10 merge_resp_headers(conn, headers())
11 |> maybe_send_sts_header(Config.get([:http_security, :sts]))
12 else
13 conn
14 end
15 end
16
17 defp headers do
18 [
19 {"x-xss-protection", "1; mode=block"},
20 {"x-permitted-cross-domain-policies", "none"},
21 {"x-frame-options", "DENY"},
22 {"x-content-type-options", "nosniff"},
23 {"referrer-policy", "same-origin"},
24 {"x-download-options", "noopen"},
25 {"content-security-policy", csp_string() <> ";"}
26 ]
27 end
28
29 defp csp_string do
30 [
31 "default-src 'none'",
32 "base-uri 'self'",
33 "form-action *",
34 "frame-ancestors 'none'",
35 "img-src 'self' data: https:",
36 "media-src 'self' https:",
37 "style-src 'self' 'unsafe-inline'",
38 "font-src 'self'",
39 "script-src 'self'",
40 "connect-src 'self' " <> String.replace(Pleroma.Web.Endpoint.static_url(), "http", "ws"),
41 "upgrade-insecure-requests"
42 ]
43 |> Enum.join("; ")
44 end
45
46 defp maybe_send_sts_header(conn, true) do
47 max_age_sts = Config.get([:http_security, :sts_max_age])
48 max_age_ct = Config.get([:http_security, :ct_max_age])
49
50 merge_resp_headers(conn, [
51 {"strict-transport-security", "max-age=#{max_age_sts}; includeSubDomains"},
52 {"expect-ct", "enforce, max-age=#{max_age_ct}"}
53 ])
54 end
55
56 defp maybe_send_sts_header(conn, _), do: conn
57 end