Skip to content

Commit

Permalink
feat: row level security on config_items & components
Browse files Browse the repository at this point in the history
  • Loading branch information
adityathebe committed Nov 8, 2024
1 parent fbf1801 commit 08fde2d
Show file tree
Hide file tree
Showing 4 changed files with 33 additions and 5 deletions.
1 change: 1 addition & 0 deletions api/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ type Config struct {
LogLevel string
LogName string

EnableRLS bool // Enable Row-level security
RunMigrations bool
SkipMigrations bool
SkipMigrationFiles []string
Expand Down
11 changes: 6 additions & 5 deletions migrate/migrate.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,6 @@ import (
"github.com/samber/oops"
)

type MigrateOptions struct {
Skip bool // Skip running migrations
IgnoreFiles []string
}

func RunMigrations(pool *sql.DB, config api.Config) error {
l := logger.GetLogger("migrate")

Expand All @@ -39,6 +34,12 @@ func RunMigrations(pool *sql.DB, config api.Config) error {
return errors.New("pool is nil")
}

if config.EnableRLS {
config.SkipMigrationFiles = append(config.SkipMigrationFiles, "035_rls-disable.sql")
} else {
config.SkipMigrationFiles = append(config.SkipMigrationFiles, "034_rls-enable.sql")
}

row := pool.QueryRow("SELECT current_database();")
var name string
if err := row.Scan(&name); err != nil {
Expand Down
18 changes: 18 additions & 0 deletions views/034_rls_enable.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
ALTER TABLE config_items ENABLE ROW LEVEL SECURITY;

ALTER TABLE components ENABLE ROW LEVEL SECURITY;

-- POLICIES
DROP POLICY IF EXISTS config_items_auth ON config_items;

CREATE POLICY config_items_auth ON config_items
FOR ALL TO postgrest_api, postgrest_anon
USING (tags::jsonb @> (current_setting('request.jwt.claims', TRUE)::json ->> 'tags')::jsonb
OR current_setting('request.jwt.claims', TRUE)::json ->> 'agent_id' = agent_id::text);

DROP POLICY IF EXISTS components_auth ON components;

CREATE POLICY components_auth ON components
FOR ALL TO postgrest_api, postgrest_anon
USING (current_setting('request.jwt.claims', TRUE)::json ->> 'agent_id' = agent_id::text);

8 changes: 8 additions & 0 deletions views/035_rls-disable.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
ALTER TABLE config_items DISABLE ROW LEVEL SECURITY;

ALTER TABLE components DISABLE ROW LEVEL SECURITY;

-- POLICIES
DROP POLICY IF EXISTS config_items_auth ON config_items;

DROP POLICY IF EXISTS components_auth ON components;

0 comments on commit 08fde2d

Please sign in to comment.