From 24a07650b67368d48f93bd3a5f2345d6756a0c0e Mon Sep 17 00:00:00 2001 From: jimmay5469 Date: Wed, 18 Jul 2018 11:40:48 -0400 Subject: [PATCH] Dynamically add websocket endpoints to connect-src CSP --- .../lib/explorer_web/csp_header.ex | 29 +++++++++++++++++++ apps/explorer_web/lib/explorer_web/router.ex | 12 +------- 2 files changed, 30 insertions(+), 11 deletions(-) create mode 100644 apps/explorer_web/lib/explorer_web/csp_header.ex diff --git a/apps/explorer_web/lib/explorer_web/csp_header.ex b/apps/explorer_web/lib/explorer_web/csp_header.ex new file mode 100644 index 0000000000..d7cbd87b37 --- /dev/null +++ b/apps/explorer_web/lib/explorer_web/csp_header.ex @@ -0,0 +1,29 @@ +defmodule ExplorerWeb.CSPHeader do + @moduledoc """ + Plug to set content-security-policy with websocket endpoints + """ + + alias Phoenix.Controller + + def init(opts), do: opts + + def call(conn, _opts) do + Controller.put_secure_browser_headers(conn, %{ + "content-security-policy" => "\ + connect-src 'self' #{websocket_endpoints(conn)}; \ + default-src 'self';\ + script-src 'self' 'unsafe-inline' 'unsafe-eval';\ + style-src 'self' 'unsafe-inline' 'unsafe-eval' https://fonts.googleapis.com;\ + img-src 'self' 'unsafe-inline' 'unsafe-eval' data:;\ + font-src 'self' 'unsafe-inline' 'unsafe-eval' https://fonts.gstatic.com data:;\ + " + }) + end + + defp websocket_endpoints(conn) do + endpoint = Controller.endpoint_module(conn) + ws_endpoint = %{endpoint.struct_url | scheme: "ws"} |> URI.to_string() + wss_endpoint = %{endpoint.struct_url | scheme: "wss"} |> URI.to_string() + "#{ws_endpoint} #{wss_endpoint}" + end +end diff --git a/apps/explorer_web/lib/explorer_web/router.ex b/apps/explorer_web/lib/explorer_web/router.ex index c2e519af67..e253e822e3 100644 --- a/apps/explorer_web/lib/explorer_web/router.ex +++ b/apps/explorer_web/lib/explorer_web/router.ex @@ -6,17 +6,7 @@ defmodule ExplorerWeb.Router do plug(:fetch_session) plug(:fetch_flash) plug(:protect_from_forgery) - - plug(:put_secure_browser_headers, %{ - "content-security-policy" => "\ - connect-src 'self' ws://localhost:*;\ - default-src 'self';\ - script-src 'self' 'unsafe-inline' 'unsafe-eval';\ - style-src 'self' 'unsafe-inline' 'unsafe-eval' https://fonts.googleapis.com;\ - img-src 'self' 'unsafe-inline' 'unsafe-eval' data:;\ - font-src 'self' 'unsafe-inline' 'unsafe-eval' https://fonts.gstatic.com data:;\ - " - }) + plug(ExplorerWeb.CSPHeader) end pipeline :api do