8000 fix(api): accept only sign-in tokens on the GraphQL socket by mwoods79 · Pull Request #730 · huddlz-hq/huddlz · GitHub
[go: up one dir, main page]

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
80 changes: 47 additions & 33 deletions lib/huddlz_web/graphql_socket.ex
Original file line number Diff line number Diff line change
Expand Up @@ -4,31 +4,27 @@ defmodule HuddlzWeb.GraphqlSocket do
use Absinthe.Phoenix.Socket,
schema: HuddlzWeb.GraphqlSchema

alias AshAuthentication.TokenResource.Actions, as: Tokens
alias Huddlz.Accounts.{Token, User}
alias AshAuthentication.Plug.Helpers, as: BearerAuth
alias Huddlz.Accounts.User

defmodule Session do
@moduledoc false
# Lives in the socket's state, which a crash report prints.
@derive {Inspect, except: [:token]}
defstruct [:token]
end

@impl true
def connect(params, socket, _connect_info) do
socket =
case params["token"] do
nil ->
Absinthe.Phoenix.Socket.put_options(socket, context: %{actor: nil})

token ->
with {:ok, %{"sub" => subject, "jti" => jti, "exp" => expires_at}, _resource} <-
AshAuthentication.Jwt.verify(token, User),
{:ok, user} <- AshAuthentication.subject_to_user(subject, User),
false <- User.suspended?(user) do
Absinthe.Phoenix.Socket.put_options(socket,
context: %{actor: user, graphql_session: %{jti: jti, expires_at: expires_at}}
)
else
_ ->
Absinthe.Phoenix.Socket.put_options(socket, context: %{actor: nil})
end
context =
with token when is_binary(token) <- params["token"],
%User{} = user <- signed_in(token) do
%{actor: user, graphql_session: %Session{token: token}}
else
_ -> %{actor: nil}
end

{:ok, socket}
{:ok, Absinthe.Phoenix.Socket.put_options(socket, context: context)}
end

@impl true
Expand All @@ -41,20 +37,38 @@ defmodule HuddlzWeb.GraphqlSocket do

def id(_socket), do: nil

# A channel outlives the request that authenticated it. Check the credential
# and current account on every document, including before a disconnect lands.
def refresh_context(%{actor: %User{id: id}, graphql_session: session} = context) do
actor =
with true <- session.expires_at > System.system_time(:second),
true <- Tokens.valid_jti?(Token, session.jti),
{:ok, %User{suspended_at: nil} = user} <- Ash.get(User, id, authorize?: false) do
user
else
_ -> nil
end

%{context | actor: actor}
# A channel outlives the request that authenticated it. Authenticate every
# document again, including before a disconnect lands.
def refresh_context(%{actor: %User{}, graphql_session: %Session{token: token}} = context) do
%{context | actor: signed_in(token)}
end

def refresh_context(context), do: context

# The token is checked exactly as `Authorization: Bearer <token>` is on the
# HTTP endpoint (`:load_from_bearer` in the router), so the socket takes a
# stored, unrevoked sign-in token and nothing minted for another purpose.
defp signed_in(token) do
with true <- names_a_subject?(token),
%User{suspended_at: nil} = user <- bearer_user(token) do
user
else
_ -> nil
end
end

defp bearer_user(token) do
conn =
%Plug.Conn{}
|> Plug.Conn.put_req_header("authorization", "Bearer " <> token)
|> BearerAuth.retrieve_from_bearer(:huddlz)

conn.assigns[:current_user]
end

# The library reads a token's subject before verifying it, and raises on one
# that is not a string. A token like that signs nobody in.
defp names_a_subject?(token) do
match?({:ok, %{"sub" => subject}} when is_binary(subject), AshAuthentication.Jwt.peek(token))
end
end
81 changes: 80 additions & 1 deletion test/huddlz_web/graphql_socket_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ defmodule HuddlzWeb.GraphqlSocketTest do
import Huddlz.Generator
import Phoenix.ChannelTest, except: [socket: 0]

alias AshAuthentication.Info
alias AshAuthentication.Strategy.Password
alias Huddlz.Accounts
alias Huddlz.Accounts.{Confirmation, Token, User}
alias HuddlzWeb.GraphqlSocket

@endpoint HuddlzWeb.Endpoint
Expand Down Expand Up @@ -36,6 +39,71 @@ defmodule HuddlzWeb.GraphqlSocketTest do
end
end

# The socket takes what the HTTP GraphQL endpoint takes as a bearer token:
# a stored sign-in token. A token minted for one purpose is not a sign-in.
describe "a token minted for something else" do
test "connects with actor: nil when the token names no person a subject could be" do
header = Base.url_encode64(~s({"alg":"HS256","typ":"JWT"}), padding: false)
claims = Base.url_encode64(~s({"sub":123}), padding: false)

assert {:ok, socket} =
GraphqlSocket.connect(%{"token" => "#{header}.#{claims}.unsigned"}, socket(), %{})

assert socket.assigns.absinthe.opts[:context][:actor] == nil
end

test "a confirmation link does not sign anyone in" do
person = generate(user(role: :user))
{:ok, link} = Confirmation.mint(person)

assert me(link) == nil
end

test "a confirmation link discarded by confirming does not sign anyone in" do
person = generate(user(role: :user))
{:ok, link} = Confirmation.mint(person)
:ok = Confirmation.discard_links(person)

assert me(link) == nil
end

test "a password reset link does not sign anyone in" do
person = generate(user(role: :user))
{:ok, link} = Password.reset_token_for(Info.strategy!(User, :password), person)

assert me(link) == nil
end

test "the short-lived token the sign-in page exchanges does not sign anyone in" do
person =
generate(user_with_password()) |> Ash.Seed.update!(%{confirmed_at: DateTime.utc_now()})

{:ok, signed_in} =
User
|> Ash.Query.for_read(
:sign_in_with_password,
%{email: person.email, password: "Password123!"},
context: %{token_type: :sign_in, private: %{ash_authentication?: true}}
)
|> Ash.read_one(authorize?: false)

assert me(signed_in.__metadata__.token) == nil
end
end

test "a session whose stored token is gone stops working on the next document" do
person = generate(user(role: :user))
channel = open_channel(person)

ref = run_doc(channel, "{ me { id } }")
assert_reply ref, :ok, %{data: %{"me" => %{"id" => _}}}, 0

Huddlz.Repo.delete_all(Token)

ref = run_doc(channel, "{ me { id } }")
assert_reply ref, :ok, %{data: %{"me" => nil}}, 0
end

test "suspension disconnects the transport and refuses mutations on an existing channel" do
person = generate(user(role: :user))
admin = generate(user(role: :admin))
Expand Down Expand Up @@ -81,13 +149,24 @@ defmodule HuddlzWeb.GraphqlSocketTest do
assert id == person.id
end

defp open_channel(user) do
defp open_channel(%User{} = user) do
{:ok, token, _} = AshAuthentication.Jwt.token_for_user(user, %{}, domain: Accounts)
open_channel(token)
end

defp open_channel(token) when is_binary(token) do
{:ok, socket} = connect(GraphqlSocket, %{"token" => token})
{:ok, _, channel} = subscribe_and_join(socket, "__absinthe__:control")
channel
end

# Who the API says is asking, over a connection opened with this token.
defp me(token) do
ref = token |> open_channel() |> run_doc("{ me { id } }")
assert_reply ref, :ok, %{data: %{"me" => me}}, 0
me
end

# The channel replies from inside handle_in, so once it has answered a
# later system message the reply is already in this process's mailbox.
defp run_doc(channel, query) do
Expand Down
0