1endpoint = Application.fetch_env!(:plausible, PlausibleWeb.Endpoint)
2Application.put_env(:plausible, PlausibleWeb.Endpoint, Keyword.put(endpoint, :server, false))
3oban = Application.fetch_env!(:plausible, Oban)
4Application.put_env(:plausible, Oban, Keyword.merge(oban, queues: [], plugins: [], peer: false))
5{:ok, _} = Application.ensure_all_started(:plausible)
6{:__block__, _, [bridge | _]} = Code.string_to_quoted!(File.read!("/sso.exs"))
7Code.eval_quoted(bridge)
8
9defmodule Snowglobe.PlausibleAuthFixture do
10 import Plug.Conn
11 def init(opts), do: opts
12
13 def call(conn, _opts) do
14 conn = fetch_cookies(conn)
15
16 case {conn.request_path, conn.req_cookies["fixture"]} do
17 {_, "down"} ->
18 send_resp(conn, 503, "Unavailable")
19
20 {"/ping", _} ->
21 send_resp(conn, 200, "OK")
22
23 {"/snow.oauth2/auth", "admin"} ->
24 conn
25 |> put_resp_header("x-auth-request-groups", "role:media,role:infra-admin")
26 |> send_resp(204, "")
27
28 {"/snow.oauth2/auth", "similar-role"} ->
29 conn
30 |> put_resp_header("x-auth-request-groups", "role:infra-admin-extra")
31 |> send_resp(204, "")
32
33 {"/snow.oauth2/auth", _} ->
34 send_resp(conn, 401, "Unauthorized")
35
36 _ ->
37 conn
38 |> prepend_resp_headers([
39 {"set-cookie", "one=; Max-Age=0"},
40 {"set-cookie", "two=; Max-Age=0"}
41 ])
42 |> put_resp_header("location", System.fetch_env!("SSO_HOME_URL"))
43 |> send_resp(302, "")
44 end
45 end
46end
47
48{:ok, _} = Plug.Cowboy.http(Snowglobe.PlausibleAuthFixture, [], ip: {127, 0, 0, 1}, port: 0)
49port = :ranch.get_port(Snowglobe.PlausibleAuthFixture.HTTP)
50System.put_env("SSO_AUTH_URL", "http://127.0.0.1:#{port}")
51
52import Plug.Conn
53alias PlausibleWeb.{Endpoint, UserAuth}
54
55request = fn method, path, cookie, headers ->
56 conn =
57 Plug.Test.conn(method, System.fetch_env!("BASE_URL") <> path)
58 |> put_req_header("cookie", cookie)
59
60 conn =
61 Enum.reduce(headers, conn, fn {name, value}, conn -> put_req_header(conn, name, value) end)
62
63 Snowglobe.Plausible.call(conn, [])
64end
65
66check = fn condition, name ->
67 unless condition, do: raise("Failed: " <> name)
68 IO.puts("PASS " <> name)
69end
70
71owner_cookie = fn ->
72 conn = request.(:get, "/sites", "fixture=admin", [])
73 value = conn.resp_cookies["_plausible_key"].value
74 config = Plug.Session.init(Endpoint.runtime_session_opts())
75
76 {_, session} =
77 Plug.Session.COOKIE.get(
78 %{conn | secret_key_base: Endpoint.config(:secret_key_base)},
79 value,
80 config.store_config
81 )
82
83 token = Map.fetch!(session, "user_token")
84 Process.put(:created_tokens, [token | Process.get(:created_tokens, [])])
85 {"_plausible_key=" <> value, token, conn}
86end
87
88try do
89 conn =
90 request.(:get, "/sites?period=all", "", [
91 {"x-auth-request-groups", "role:infra-admin"},
92 {"authorization", "Basic ZmFrZTpmYWtl"}
93 ])
94
95 destination =
96 "/snow.oauth2/start?" <>
97 URI.encode_query(%{"rd" => System.fetch_env!("BASE_URL") <> "/sites?period=all"})
98
99 check.(
100 conn.status == 302 and get_resp_header(conn, "location") == [destination] and
101 not Map.has_key?(conn.resp_cookies, "_plausible_key"),
102 "forged headers cannot bypass SSO"
103 )
104
105 conn = request.(:get, "/sites", "fixture=similar-role", [])
106
107 check.(
108 conn.status == 403 and not Map.has_key?(conn.resp_cookies, "_plausible_key"),
109 "exact role match"
110 )
111
112 {cookie, token, login} = owner_cookie.()
113
114 owner =
115 case Plausible.Auth.UserSessions.get_by_token(token) do
116 {:ok, %{user: user}} -> user.email == System.fetch_env!("ADMIN_EMAIL")
117 _ -> false
118 end
119
120 secure_cookie =
121 Enum.any?(get_resp_header(login, "set-cookie"), fn value ->
122 String.starts_with?(value, "_plausible_key=") and
123 Enum.all?(
124 ["secure", "httponly", "samesite=lax"],
125 &String.contains?(String.downcase(value), &1)
126 )
127 end)
128
129 check.(owner and secure_cookie, "secure normal owner session")
130
131 conn = request.(:get, "/sites", "fixture=admin; " <> cookie, [])
132
133 check.(
134 conn.status == 200 and not Map.has_key?(conn.resp_cookies, "logged_in"),
135 "reuse the existing owner session"
136 )
137
138 conn = request.(:get, "/sites", cookie, [])
139 check.(conn.status == 302, "Plausible cookie alone cannot enter the dashboard")
140 conn = request.(:get, "/api/stats/paperclover.net/top-stats", cookie, [])
141 check.(conn.status == 401, "Plausible cookie alone cannot read statistics")
142
143 Plausible.Auth.UserSessions.remove_by_token(token)
144 conn = request.(:get, "/sites?period=all", "fixture=admin; " <> cookie, [])
145 value = conn.resp_cookies["_plausible_key"].value
146 config = Plug.Session.init(Endpoint.runtime_session_opts())
147
148 {_, session} =
149 Plug.Session.COOKIE.get(
150 %{conn | secret_key_base: Endpoint.config(:secret_key_base)},
151 value,
152 config.store_config
153 )
154
155 Process.put(:created_tokens, [session["user_token"] | Process.get(:created_tokens, [])])
156 valid = match?({:ok, _}, UserAuth.get_user_session(session))
157
158 check.(
159 conn.status == 302 and get_resp_header(conn, "location") == ["/sites?period=all"] and valid,
160 "replace expired sessions and preserve the destination"
161 )
162
163 {cookie, token, _} = owner_cookie.()
164 conn = request.(:get, "/logout", "fixture=admin; " <> cookie, [])
165 revoked = match?({:error, :not_found}, Plausible.Auth.UserSessions.get_by_token(token))
166
167 destination =
168 "/snow.oauth2/sign_out?" <> URI.encode_query(%{"rd" => System.fetch_env!("SSO_HOME_URL")})
169
170 check.(
171 conn.status == 302 and get_resp_header(conn, "location") == [destination] and revoked,
172 "logout revokes the owner session"
173 )
174
175 conn = request.(:get, "/snow.oauth2/sign_out", "", [])
176 check.(length(get_resp_header(conn, "set-cookie")) == 2, "forward every SSO logout cookie")
177
178 for {method, path, cookie} <- [
179 {:post, "/settings/security/password", ""},
180 {:get, "/live/websocket", ""},
181 {:post, "/settings/security/password", "fixture=admin"},
182 {:get, "/live/websocket", "fixture=admin"}
183 ] do
184 conn = request.(method, path, cookie, [])
185
186 check.(
187 conn.status == 401 and not Map.has_key?(conn.resp_cookies, "_plausible_key"),
188 "private writes and WebSockets require both sessions"
189 )
190 end
191
192 {cookie, _, _} = owner_cookie.()
193
194 rejected =
195 try do
196 request.(:post, "/settings/security/password", "fixture=admin; " <> cookie, []).status ==
197 403
198 rescue
199 e ->
200 is_struct(e, Plug.CSRFProtection.InvalidCSRFTokenError) or
201 (is_struct(e, Plug.Conn.WrapperError) and
202 is_struct(e.reason, Plug.CSRFProtection.InvalidCSRFTokenError))
203 end
204
205 check.(rejected, "native CSRF protection remains active")
206
207 for path <- ["/settings/security/email", "/settings/security/%65mail", "/me"] do
208 conn = request.(:post, path, "fixture=admin; " <> cookie, [])
209 check.(conn.status == 403, "the configured owner identity cannot be changed through the app")
210 end
211
212 conn = request.(:get, "/sites", "fixture=down", [])
213 check.(conn.status == 503, "SSO failure closes private pages")
214 conn = request.(:get, "/api/health", "fixture=down", [])
215 check.(conn.status == 503, "health includes the auth sidecar")
216 conn = request.(:get, "/js/script.js", "fixture=down", [])
217 check.(conn.status == 200, "scripts remain public during SSO failure")
218
219 conn =
220 request.(:options, "/api/event", "", [
221 {"origin", "https://paperclover.net"},
222 {"access-control-request-method", "POST"}
223 ])
224
225 check.(conn.status in [200, 204], "tracking preflight remains public")
226
227 for path <- ["/js/../sites", "/js/%2e%2e/sites", "/js/%2f..%2fsites", "/api/event/../stats"] do
228 conn = request.(:get, path, cookie, [])
229
230 check.(
231 conn.status in [302, 401] and not Map.has_key?(conn.resp_cookies, "_plausible_key"),
232 "public paths cannot traverse into private pages"
233 )
234 end
235
236 original_domain = System.fetch_env!("SITE_DOMAIN")
237 fixture_domain = "plausible-sso-bootstrap.invalid"
238 System.put_env("SITE_DOMAIN", fixture_domain)
239
240 try do
241 Code.eval_file("/bootstrap.exs")
242 check.(Plausible.Sites.get_by_domain(fixture_domain) != nil, "fresh site bootstrap")
243 after
244 System.put_env("SITE_DOMAIN", original_domain)
245 if site = Plausible.Sites.get_by_domain(fixture_domain), do: Plausible.Site.Removal.run(site)
246 end
247
248 IO.puts("SSO boundary checks passed")
249after
250 Enum.each(Process.get(:created_tokens, []), &Plausible.Auth.UserSessions.remove_by_token/1)
251end