1defmodule Snowglobe.Plausible do
2 import Plug.Conn
3 alias PlausibleWeb.{Endpoint, UserAuth}
4
5 @unavailable "Sign-in is unavailable. Try again."
6 @sign_in "Open Plausible to sign in, then try again."
7
8 def init(opts), do: opts
9
10 def call(conn, _opts) do
11 public =
12 (conn.method in ["GET", "HEAD"] and
13 Regex.match?(~r{\A/js/[A-Za-z0-9._-]+\.js\z}, conn.request_path)) or
14 (conn.method in ["POST", "OPTIONS"] and conn.request_path == "/api/event")
15
16 cond do
17 conn.method in ["GET", "HEAD"] and conn.request_path == "/api/health" ->
18 case auth_request(conn, "/ping") do
19 {:ok, %{status: 200}} -> Endpoint.call(conn, Endpoint.init([]))
20 _ -> send_resp(conn, 503, @unavailable)
21 end
22
23 public ->
24 Endpoint.call(conn, Endpoint.init([]))
25
26 conn.method == "GET" and
27 conn.request_path in ~w(/snow.oauth2/start /snow.oauth2/callback /snow.oauth2/sign_in /snow.oauth2/sign_out) ->
28 case auth_request(conn, conn.request_path <> query(conn)) do
29 {:ok, response} ->
30 conn
31 |> prepend_resp_headers(
32 Enum.reject(response.headers, fn {name, _} ->
33 name in ~w(connection content-length transfer-encoding)
34 end)
35 )
36 |> send_resp(response.status, response.body)
37
38 {:error, _} ->
39 send_resp(conn, 503, @unavailable)
40 end
41
42 true ->
43 authenticate(conn)
44 end
45 end
46
47 defp authenticate(conn) do
48 case auth_request(conn, "/snow.oauth2/auth") do
49 {:ok, %{status: status, headers: headers}} when status in 200..299 ->
50 groups =
51 for {"x-auth-request-groups", value} <- headers,
52 group <- String.split(value, ~r/[,\s]+/, trim: true),
53 do: group
54
55 conn =
56 prepend_resp_headers(
57 conn,
58 Enum.filter(headers, fn {name, _} -> name == "set-cookie" end)
59 )
60
61 if "role:infra-admin" in groups do
62 owner_session(conn)
63 else
64 send_resp(
65 conn,
66 403,
67 "Your account cannot access Plausible. Ask an administrator for access."
68 )
69 end
70
71 {:ok, %{status: status}} when status in [401, 403] ->
72 if conn.method in ["GET", "HEAD"] and
73 not String.starts_with?(conn.request_path, ["/api/", "/live/"]) do
74 destination = System.fetch_env!("BASE_URL") <> conn.request_path <> query(conn)
75
76 Phoenix.Controller.redirect(conn,
77 to: "/snow.oauth2/start?" <> URI.encode_query(%{"rd" => destination})
78 )
79 else
80 send_resp(conn, 401, @sign_in)
81 end
82
83 _ ->
84 send_resp(conn, 503, @unavailable)
85 end
86 end
87
88 defp owner_session(conn) do
89 conn = %{conn | secret_key_base: Endpoint.config(:secret_key_base)} |> fetch_cookies()
90 config = Plug.Session.init(Endpoint.runtime_session_opts())
91
92 # Leave the endpoint responsible for installing its session hook.
93 session =
94 if cookie = conn.req_cookies[config.key] do
95 {_, session} = Plug.Session.COOKIE.get(conn, cookie, config.store_config)
96 UserAuth.get_user_session(session)
97 end
98
99 owner_email = System.fetch_env!("ADMIN_EMAIL")
100
101 cond do
102 conn.method in ["POST", "DELETE"] and
103 Enum.map(conn.path_info, &URI.decode/1) in [["settings", "security", "email"], ["me"]] ->
104 send_resp(
105 conn,
106 403,
107 "This shared owner account uses the configured email address. Ask the server administrator to change or remove it."
108 )
109
110 conn.method == "GET" and conn.request_path == "/logout" ->
111 conn = conn |> Plug.Session.call(config) |> fetch_session() |> UserAuth.log_out_user()
112
113 Phoenix.Controller.redirect(conn,
114 to:
115 "/snow.oauth2/sign_out?" <>
116 URI.encode_query(%{"rd" => System.fetch_env!("SSO_HOME_URL")})
117 )
118
119 conn.method == "GET" and conn.request_path == "/login" ->
120 Phoenix.Controller.redirect(conn, to: "/sites")
121
122 match?({:ok, %{user: %{email: ^owner_email}}}, session) ->
123 {:ok, user_session} = session
124 Endpoint.call(assign(conn, :current_user_session, user_session), Endpoint.init([]))
125
126 conn.method == "GET" and not String.starts_with?(conn.request_path, ["/api/", "/live/"]) ->
127 user = Plausible.Repo.get_by!(Plausible.Auth.User, email: owner_email)
128
129 conn
130 |> put_private(:phoenix_endpoint, Endpoint)
131 |> Plug.Session.call(config)
132 |> fetch_session()
133 |> put_resp_header("cache-control", "no-store")
134 |> UserAuth.log_in_user(user, conn.request_path <> query(conn))
135
136 true ->
137 send_resp(conn, 401, @sign_in)
138 end
139 end
140
141 defp query(%{query_string: ""}), do: ""
142 defp query(conn), do: "?" <> conn.query_string
143
144 defp auth_request(conn, path) do
145 host = URI.parse(System.fetch_env!("BASE_URL")).host
146
147 headers =
148 Enum.filter(conn.req_headers, fn {name, _} -> name in ~w(cookie user-agent accept) end) ++
149 [
150 {"x-forwarded-proto", "https"},
151 {"x-forwarded-host", host},
152 {"x-forwarded-uri", conn.request_path <> query(conn)},
153 {"x-forwarded-method", conn.method}
154 ]
155
156 Finch.build(:get, System.fetch_env!("SSO_AUTH_URL") <> path, headers)
157 |> Finch.request(Plausible.Finch, pool_timeout: 1_000, receive_timeout: 3_000)
158 end
159end
160
161# Keep a single listener so no route can bypass forward authentication.
162endpoint = Application.fetch_env!(:plausible, PlausibleWeb.Endpoint)
163Application.put_env(:plausible, PlausibleWeb.Endpoint, Keyword.put(endpoint, :server, false))
164Application.put_env(:plug_cowboy, :conn_in_exception_metadata, false)
165{:ok, _} = Application.ensure_all_started(:plausible)
166
167{:ok, _} =
168 Supervisor.start_child(
169 Plausible.Supervisor,
170 {Plug.Cowboy,
171 scheme: :http,
172 plug: Snowglobe.Plausible,
173 options: [port: Application.fetch_env!(:plausible, PlausibleWeb.Endpoint)[:http][:port]]}
174 )
175
176Process.sleep(:infinity)