-
-
Notifications
You must be signed in to change notification settings - Fork 370
fix: Apply RLS rules to Channel controller #758
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
00a0a28
fix: Apply RLS rules to Channel controller
filipecabaco fb1d3c1
move authz out of helpers and properly test it
filipecabaco d107246
add tenant database to docker setup
filipecabaco 1b87005
Improve typespecs and refactor code
filipecabaco 9978e34
separate migrations; remove some of the setup
filipecabaco 8a693d0
create auth functions if required only
filipecabaco 2549d19
revert db setup; add db for ci
filipecabaco f443227
setup plugs to be used by controllers with RLS
filipecabaco 8fa311e
handle authorization on channel controller for read operations
filipecabaco 310caf5
add channel name rls handling; refactor to clean tests
filipecabaco f9d5afd
cleanup minor code changes; add docs
filipecabaco 63b6fbc
fix format
filipecabaco 21976f9
fix test with proper 401 message
filipecabaco a39d821
simplify tests; refactor param setting
filipecabaco 5eacb4d
add structs for authorization params and permissions
filipecabaco b7fe48d
remove auth functions from migrations
filipecabaco File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
File renamed without changes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,109 @@ | ||
defmodule Realtime.Tenants.Authorization do | ||
@moduledoc """ | ||
Runs validations based on RLS policies to set permissions for a given connection. | ||
|
||
It will assign the a new key to a socket or a conn with the following: | ||
* read - a boolean indicating whether the connection has read permissions | ||
""" | ||
require Logger | ||
defstruct [:channel_name, :headers, :jwt, :claims, :role] | ||
|
||
defmodule Permissions do | ||
defstruct read: false | ||
|
||
@type t :: %__MODULE__{ | ||
:read => boolean() | ||
} | ||
end | ||
|
||
@type t :: %__MODULE__{ | ||
:channel_name => binary() | nil, | ||
:claims => map(), | ||
:headers => keyword({binary(), binary()}), | ||
:jwt => map(), | ||
:role => binary() | ||
} | ||
@doc """ | ||
Builds a new authorization params struct. | ||
""" | ||
def build_authorization_params(%{ | ||
channel_name: channel_name, | ||
headers: headers, | ||
jwt: jwt, | ||
claims: claims, | ||
role: role | ||
}) do | ||
%__MODULE__{ | ||
channel_name: channel_name, | ||
headers: headers, | ||
jwt: jwt, | ||
claims: claims, | ||
role: role | ||
} | ||
end | ||
|
||
@spec get_authorizations(Phoenix.Socket.t() | Plug.Conn.t(), DBConnection.t(), __MODULE__.t()) :: | ||
{:ok, Phoenix.Socket.t() | Plug.Conn.t()} | {:error, :unauthorized} | ||
@doc """ | ||
Runs validations based on RLS policies to set permissions for a given connection (either Phoenix.Socket or Plug.Conn). | ||
""" | ||
def get_authorizations(%Phoenix.Socket{} = socket, db_conn, params) do | ||
case get_permissions_for_connection(db_conn, params) do | ||
{:ok, permissions} -> {:ok, Phoenix.Socket.assign(socket, :permissions, permissions)} | ||
_ -> {:error, :unauthorized} | ||
end | ||
end | ||
|
||
def get_authorizations(%Plug.Conn{} = conn, db_conn, params) do | ||
case get_permissions_for_connection(db_conn, params) do | ||
{:ok, permissions} -> {:ok, Plug.Conn.assign(conn, :permissions, permissions)} | ||
_ -> {:error, :unauthorized} | ||
end | ||
end | ||
|
||
defp get_permissions_for_connection(conn, params) do | ||
%__MODULE__{ | ||
channel_name: channel_name, | ||
headers: headers, | ||
jwt: jwt, | ||
claims: claims, | ||
role: role | ||
} = params | ||
|
||
sub = Map.get(claims, :sub) | ||
claims = Jason.encode!(claims) | ||
headers = headers |> Map.new() |> Jason.encode!() | ||
|
||
Postgrex.transaction(conn, fn conn -> | ||
Postgrex.query( | ||
conn, | ||
""" | ||
SELECT | ||
set_config('role', $1, true), | ||
set_config('realtime.channel_name', $2, true), | ||
set_config('request.jwt.claim.role', $3, true), | ||
set_config('request.jwt', $4, true), | ||
set_config('request.jwt.claim.sub', $5, true), | ||
filipecabaco marked this conversation as resolved.
Show resolved
Hide resolved
|
||
set_config('request.jwt.claims', $6, true), | ||
set_config('request.headers', $7, true) | ||
""", | ||
[role, channel_name, role, jwt, sub, claims, headers] | ||
) | ||
|
||
case Postgrex.query(conn, "SELECT name from realtime.channels", [], mode: :savepoint) do | ||
chasers marked this conversation as resolved.
Show resolved
Hide resolved
|
||
{:ok, %{num_rows: 0}} -> | ||
{:ok, %Permissions{read: false}} | ||
|
||
{:ok, _} -> | ||
{:ok, %Permissions{read: true}} | ||
|
||
{:error, %Postgrex.Error{postgres: %{code: :insufficient_privilege}}} -> | ||
{:ok, %Permissions{read: false}} | ||
|
||
{:error, error} -> | ||
Logger.error("Error getting permissions for connection: #{inspect(error)}") | ||
{:error, error} | ||
end | ||
end) | ||
end | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
23 changes: 23 additions & 0 deletions
23
lib/realtime/tenants/repo/migrations/20231204144023_set_required_grants.ex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
defmodule Realtime.Tenants.Migrations.SetRequiredGrants do | ||
@moduledoc false | ||
|
||
use Ecto.Migration | ||
|
||
def change do | ||
execute(""" | ||
GRANT USAGE ON SCHEMA realtime TO postgres, anon, authenticated, service_role | ||
""") | ||
|
||
execute(""" | ||
GRANT SELECT ON ALL TABLES IN SCHEMA realtime TO postgres, anon, authenticated, service_role | ||
""") | ||
|
||
execute(""" | ||
GRANT EXECUTE ON ALL FUNCTIONS IN SCHEMA realtime TO postgres, anon, authenticated, service_role | ||
""") | ||
|
||
execute(""" | ||
GRANT USAGE ON ALL SEQUENCES IN SCHEMA realtime TO postgres, anon, authenticated, service_role | ||
""") | ||
end | ||
end |
13 changes: 13 additions & 0 deletions
13
lib/realtime/tenants/repo/migrations/20231204144024_create_rls_helper_functions.ex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,13 @@ | ||
defmodule Realtime.Tenants.Migrations.CreateRlsHelperFunctions do | ||
@moduledoc false | ||
|
||
use Ecto.Migration | ||
|
||
def change do | ||
execute(""" | ||
create or replace function realtime.channel_name() returns text as $$ | ||
select nullif(current_setting('realtime.channel_name', true), '')::text; | ||
$$ language sql stable; | ||
""") | ||
end | ||
end |
9 changes: 9 additions & 0 deletions
9
lib/realtime/tenants/repo/migrations/20231204144025_enable_channels_rls.ex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
defmodule Realtime.Tenants.Migrations.EnableChannelsRls do | ||
@moduledoc false | ||
|
||
use Ecto.Migration | ||
|
||
def change do | ||
execute("ALTER TABLE realtime.channels ENABLE row level security") | ||
end | ||
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.