Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/bind-socket-handshake-origin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@frontman/frontman-server-assets": patch
---

Bind embedded client WebSocket authentication to the actual browser handshake origin instead of a client-supplied socket parameter. Reject missing, malformed, duplicate, or unapproved handshake origins while preserving dynamically approved embedding sites and localhost development.
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,11 @@ defmodule FrontmanServerWeb.UserSocket do
channel "task:*", FrontmanServerWeb.TaskChannel

@impl true
def connect(%{"origin" => origin}, socket, %{auth_token: token})
when is_binary(origin) and is_binary(token) do
with {:ok, normalized_origin} <- EmbeddedClientOrigin.normalize(origin),
def connect(_params, socket, %{auth_token: token, x_headers: headers})
when is_binary(token) do
with [{"x-frontman-socket-origin", origin}] <-
Enum.filter(headers, fn {name, _value} -> name == "x-frontman-socket-origin" end),
{:ok, normalized_origin} <- EmbeddedClientOrigin.normalize(origin),
{%Scope{} = scope, token_id} <-
Accounts.get_scope_by_embedded_client_token(token, normalized_origin) do
Accounts.touch_embedded_client_token(scope, token_id)
Expand Down
17 changes: 16 additions & 1 deletion apps/frontman_server/lib/frontman_server_web/endpoint.ex
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,26 @@ defmodule FrontmanServerWeb.Endpoint do
)

socket("/socket", FrontmanServerWeb.UserSocket,
websocket: [check_origin: false, max_frame_size: 8_000_014],
websocket: [check_origin: false, connect_info: [:x_headers], max_frame_size: 8_000_014],
longpoll: false,
auth_token: true
)

def call(%{path_info: ["socket", "websocket"]} = conn, opts) do
conn = Plug.Conn.delete_req_header(conn, "x-frontman-socket-origin")

with [origin] <- Plug.Conn.get_req_header(conn, "origin"),
{:ok, origin} <- FrontmanServerWeb.EmbeddedClientOrigin.normalize(origin) do
conn
|> Plug.Conn.put_req_header("x-frontman-socket-origin", origin)
|> super(opts)
else
_ -> conn |> Plug.Conn.send_resp(403, "") |> Plug.Conn.halt()
end
end

def call(conn, opts), do: super(conn, opts)

plug(Plug.Static,
at: "/",
from: :frontman_server,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,12 @@ defmodule FrontmanServerWeb.UserSocketTest do
end)

assert socket_opts[:auth_token] == true
assert socket_opts[:websocket] == [check_origin: false, max_frame_size: 8_000_014]

assert socket_opts[:websocket] == [
check_origin: false,
connect_info: [:x_headers],
max_frame_size: 8_000_014
]

limit = socket_opts[:websocket][:max_frame_size]

Expand All @@ -36,8 +41,8 @@ defmodule FrontmanServerWeb.UserSocketTest do
token = Accounts.generate_embedded_client_token(user, "https://customer.example")

assert {:ok, socket} =
connect(UserSocket, %{"origin" => "https://customer.example"},
connect_info: %{auth_token: token}
connect(UserSocket, %{},
connect_info: connect_info(token, "https://customer.example")
)

assert socket.assigns.scope.user.id == user.id
Expand All @@ -47,23 +52,28 @@ defmodule FrontmanServerWeb.UserSocketTest do

test "rejects missing auth token" do
assert :error = connect(UserSocket, %{}, connect_info: %{})

assert :error =
connect(UserSocket, %{},
connect_info: %{
x_headers: [{"x-frontman-socket-origin", "https://customer.example"}]
}
)
end

test "rejects invalid auth token" do
assert :error =
connect(UserSocket, %{"origin" => "https://customer.example"},
connect_info: %{auth_token: "invalid"}
connect(UserSocket, %{},
connect_info: connect_info("invalid", "https://customer.example")
)
end

test "rejects wrong origin" do
test "rejects a handshake origin not approved by the token" do
user = user_fixture()
token = Accounts.generate_embedded_client_token(user, "https://customer.example")

assert :error =
connect(UserSocket, %{"origin" => "https://evil.example"},
connect_info: %{auth_token: token}
)
connect(UserSocket, %{}, connect_info: connect_info(token, "https://evil.example"))
end

test "rejects legacy token params" do
Expand All @@ -72,4 +82,141 @@ defmodule FrontmanServerWeb.UserSocketTest do

assert :error = connect(UserSocket, %{"token" => token}, connect_info: %{})
end

test "rejects a claimed approved origin with a different handshake origin" do
token = Accounts.generate_embedded_client_token(user_fixture(), "https://customer.example")

assert :error =
connect(UserSocket, %{"origin" => "https://customer.example"},
connect_info: connect_info(token, "https://evil.example")
)
end

test "ignores client-supplied origin params" do
token = Accounts.generate_embedded_client_token(user_fixture(), "https://customer.example")

for params <- [
%{},
%{"origin" => "https://evil.example"},
%{"origin" => "null"},
%{"origin" => ["https://customer.example"]}
] do
assert {:ok, _socket} =
connect(UserSocket, params,
connect_info: connect_info(token, "https://customer.example")
)
end
end

test "requires a valid handshake origin even with a valid bearer and claimed origin" do
token = Accounts.generate_embedded_client_token(user_fixture(), "https://customer.example")

assert :error =
connect(UserSocket, %{"origin" => "https://customer.example"},
connect_info: %{auth_token: token}
)

for headers <- [
[],
[{"x-frontman-socket-origin", "null"}],
[{"x-frontman-socket-origin", "https://customer.example/path"}],
[
{"x-frontman-socket-origin", "https://customer.example"},
{"x-frontman-socket-origin", "https://customer.example"}
]
] do
assert :error =
connect(UserSocket, %{"origin" => "https://customer.example"},
connect_info: %{auth_token: token, x_headers: headers}
)
end
end

test "normalizes handshake origins and preserves local development origins" do
for {approved, actual} <- [
{"https://customer.example", "https://CUSTOMER.example:443"},
{"http://localhost:5173", "http://localhost:5173"}
] do
token = Accounts.generate_embedded_client_token(user_fixture(), approved)

assert {:ok, _socket} =
connect(UserSocket, %{}, connect_info: connect_info(token, actual))
end
end

test "endpoint uses actual Origin and overwrites forged internal headers before dispatch" do
token = Accounts.generate_embedded_client_token(user_fixture(), "https://customer.example")

assert handshake(token, [
{"origin", "https://CUSTOMER.example:443"},
{"x-frontman-socket-origin", "https://evil.example"}
]).state == :upgraded

assert handshake(
token,
[
{"origin", "https://evil.example"},
{"x-frontman-socket-origin", "https://customer.example"}
],
%{"origin" => "https://customer.example"}
).status == 403

assert handshake(token, [
{"origin", "https://evil.example"}
]).status == 403

assert handshake("invalid", [
{"origin", "https://customer.example"}
]).status == 403

for headers <- [
[{"x-frontman-socket-origin", "https://customer.example"}],
[{"origin", "null"}],
[{"origin", ""}],
[{"origin", "https://customer.example/path"}],
[{"origin", "https://customer.example, https://evil.example"}],
[{"origin", "https://customer.example"}, {"origin", "https://customer.example"}]
] do
assert handshake(token, headers, %{"origin" => "https://customer.example"}).status == 403
end
end

test "endpoint authenticates without claimed origin and ignores legacy origin params" do
for origin <- ["https://customer.example", "http://localhost:5173"] do
token = Accounts.generate_embedded_client_token(user_fixture(), origin)

for params <- [%{}, %{"origin" => "https://evil.example"}, %{"origin" => "null"}] do
assert handshake(token, [{"origin", origin}], params).state == :upgraded
end
end
end

defp connect_info(token, origin) do
%{auth_token: token, x_headers: [{"x-frontman-socket-origin", origin}]}
end

defp handshake(token, headers, params \\ %{}) do
conn =
Plug.Test.conn(
:get,
"/socket/websocket?" <>
URI.encode_query(Map.put(params, "vsn", "2.0.0"))
)

conn = %{
conn
| req_headers: [
{"host", "www.example.com"},
{"connection", "upgrade"},
{"upgrade", "websocket"},
{"sec-websocket-key", "dGhlIHNhbXBsZSBub25jZQ=="},
{"sec-websocket-version", "13"},
{"sec-websocket-protocol",
"phoenix, base64url.bearer.phx.#{Base.encode64(token, padding: false)}"}
| headers
]
}

FrontmanServerWeb.Endpoint.call(conn, FrontmanServerWeb.Endpoint.init([]))
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,11 @@ defmodule FrontmanServerWeb.ClientTokenControllerTest do
assert :error =
Phoenix.ChannelTest.connect(
FrontmanServerWeb.UserSocket,
%{"origin" => "https://customer.example"},
connect_info: %{auth_token: token}
%{},
connect_info: %{
auth_token: token,
x_headers: [{"x-frontman-socket-origin", "https://customer.example"}]
}
)
end

Expand Down
3 changes: 3 additions & 0 deletions libs/bindings/src/Phoenix.res
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
type socket
type channel

type rec pushResponse = {receive: (~status: string, ~callback: JSON.t => unit) => pushResponse}

@send external socketParams: socket => dict<string> = "params"
8 changes: 0 additions & 8 deletions libs/frontman-client/src/FrontmanClient__ACP.res
Original file line number Diff line number Diff line change
Expand Up @@ -181,14 +181,6 @@ let connect = async (
| (Ok(token), Ok()) =>
let socketOpts: Socket.socketOptions = {
authToken: token,
params: Dict.fromArray([
(
"origin",
WebAPI.Window.current
->WebAPI.Window.location
->FrontmanBindings.Bindings__WebAPI.locationOrigin,
),
]),
}
let socket = Socket.make(~endpoint=config.endpoint, ~opts=socketOpts)
let channel = socket->Socket.channel(~topic=Constants.tasksTopic)
Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
type t
type t = FrontmanBindings.Phoenix.socket

type channel = FrontmanBindings.Phoenix.channel

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,13 @@ let connect = async () => {
let create = connection =>
ACP.createSession(connection, ~sessionId, ~onUpdate=(_, _) => (), ~onTitleUpdated=(_, _) => ())

testAsync("connects without sending a client-supplied origin param", async t => {
let (_, connection) = await connect()
t
->expect(connection.socket->FrontmanBindings.Phoenix.socketParams->Dict.get("origin"))
->Expect.toEqual(None)
})

[
JSON.Encode.null,
JSON.Encode.bool(false),
Expand Down
2 changes: 1 addition & 1 deletion mise.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ elixir-ls="0.30.0"
mprocs="0.7.1"
mkcert="1.4.4"
"aqua:stripe/stripe-cli"="latest"
"npm:@rescript/language-server"="latest"
"npm:@rescript/language-server" = { version = "latest", allow_low_downloads = true }
"npm:rescript"="latest"
"npm:corepack"="latest"
"npm:@tailwindcss/language-server"="latest"
Expand Down
Loading