Using Row-Level Security in Ent Schema

Row-level security (RLS) in PostgreSQL enables tables to implement policies that limit access or modification of rows according to the user’s role, enhancing the basic SQL-standard privileges provided by GRANT.

Once activated, every standard access to the table has to adhere to these policies. If no policies are defined on the table, it defaults to a deny-all rule, meaning no rows can be seen or mutated. These policies can be tailored to specific commands, roles, or both, allowing for detailed management of who can access or change data.

This guide explains how to attach Row-Level Security (RLS) Policies to your Ent types (objects) and configure the schema migration to manage both the RLS and the Ent schema as a single migration unit using Atlas.

Row-Level Security - 图1Atlas Pro Feature

Atlas support for Row-Level Security Policies used in this guide is available exclusively to Pro users. To use this feature, run:

  1. atlas login

Install Atlas

To install the latest release of Atlas, simply run one of the following commands in your terminal, or check out the Atlas website:

  • macOS + Linux
  • Homebrew
  • Docker
  • Windows
  1. curl -sSf https://atlasgo.sh | sh
  1. brew install ariga/tap/atlas
  1. docker pull arigaio/atlas
  2. docker run --rm arigaio/atlas --help

If the container needs access to the host network or a local directory, use the --net=host flag and mount the desired directory:

  1. docker run --rm --net=host \
  2. -v $(pwd)/migrations:/migrations \
  3. arigaio/atlas migrate apply
  4. --url "mysql://root:pass@:3306/test"

Download the latest release and move the atlas binary to a file location on your system PATH.

Login to Atlas

  1. $ atlas login a8m
  2. You are now connected to "a8m" on Atlas Cloud.

Composite Schema

An ent/schema package is mostly used for defining Ent types (objects), their fields, edges and logic. Table policies or any other database native objects do not have representation in Ent models.

In order to extend our PostgreSQL schema to include both our Ent types and their policies, we configure Atlas to read the state of the schema from a Composite Schema data source. Follow the steps below to configure this for your project:

  1. Let’s define a simple schema with two types (tables): users and tenants:

ent/schema/tenant.go

  1. // Tenant holds the schema definition for the Tenant entity.
  2. type Tenant struct {
  3. ent.Schema
  4. }
  5. // Fields of the Tenant.
  6. func (Tenant) Fields() []ent.Field {
  7. return []ent.Field{
  8. field.String("name"),
  9. }
  10. }
  11. // User holds the schema definition for the User entity.
  12. type User struct {
  13. ent.Schema
  14. }
  15. // Fields of the User.
  16. func (User) Fields() []ent.Field {
  17. return []ent.Field{
  18. field.String("name"),
  19. field.Int("tenant_id"),
  20. }
  21. }
  1. Now, suppose we want to limit access to the users table based on the tenant_id field. We can achieve this by defining a Row-Level Security (RLS) policy on the users table. Below is the SQL code that defines the RLS policy:

schema.sql

  1. --- Enable row-level security on the users table.
  2. ALTER TABLE "users" ENABLE ROW LEVEL SECURITY;
  3. -- Create a policy that restricts access to rows in the users table based on the current tenant.
  4. CREATE POLICY tenant_isolation ON "users"
  5. USING ("tenant_id" = current_setting('app.current_tenant')::integer);
  1. Lastly, we create a simple atlas.hcl config file with a composite_schema that includes both our Ent schema and the custom security policies defined in schema.sql:

atlas.hcl

  1. data "composite_schema" "app" {
  2. # Load the ent schema first with all tables.
  3. schema "public" {
  4. url = "ent://ent/schema"
  5. }
  6. # Then, load the RLS schema.
  7. schema "public" {
  8. url = "file://schema.sql"
  9. }
  10. }
  11. env "local" {
  12. src = data.composite_schema.app.url
  13. dev = "docker://postgres/15/dev?search_path=public"
  14. }

Usage

After setting up our composite schema, we can get its representation using the atlas schema inspect command, generate schema migrations for it, apply them to a database, and more. Below are a few commands to get you started with Atlas:

Inspect the Schema

The atlas schema inspect command is commonly used to inspect databases. However, we can also use it to inspect our composite_schema and print the SQL representation of it:

  1. atlas schema inspect \
  2. --env local \
  3. --url env://src \
  4. --format '{{ sql . }}'

The command above prints the following SQL. Note, the tenant_isolation policy is defined in the schema after the users table:

  1. -- Create "users" table
  2. CREATE TABLE "users" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "name" character varying NOT NULL, "tenant_id" bigint NOT NULL, PRIMARY KEY ("id"));
  3. -- Enable row-level security for "users" table
  4. ALTER TABLE "users" ENABLE ROW LEVEL SECURITY;
  5. -- Create policy "tenant_isolation"
  6. CREATE POLICY "tenant_isolation" ON "users" AS PERMISSIVE FOR ALL TO PUBLIC USING (tenant_id = (current_setting('app.current_tenant'::text))::integer);
  7. -- Create "tenants" table
  8. CREATE TABLE "tenants" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "name" character varying NOT NULL, PRIMARY KEY ("id"));

Generate Migrations For the Schema

To generate a migration for the schema, run the following command:

  1. atlas migrate diff \
  2. --env local

Note that a new migration file is created with the following content:

migrations/20240712090543.sql

  1. -- Create "users" table
  2. CREATE TABLE "users" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "name" character varying NOT NULL, "tenant_id" bigint NOT NULL, PRIMARY KEY ("id"));
  3. -- Enable row-level security for "users" table
  4. ALTER TABLE "users" ENABLE ROW LEVEL SECURITY;
  5. -- Create policy "tenant_isolation"
  6. CREATE POLICY "tenant_isolation" ON "users" AS PERMISSIVE FOR ALL TO PUBLIC USING (tenant_id = (current_setting('app.current_tenant'::text))::integer);
  7. -- Create "tenants" table
  8. CREATE TABLE "tenants" ("id" bigint NOT NULL GENERATED BY DEFAULT AS IDENTITY, "name" character varying NOT NULL, PRIMARY KEY ("id"));

Apply the Migrations

To apply the migration generated above to a database, run the following command:

  1. atlas migrate apply \
  2. --env local \
  3. --url "postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable"

Row-Level Security - 图2Apply the Schema Directly on the Database

Sometimes, there is a need to apply the schema directly to the database without generating a migration file. For example, when experimenting with schema changes, spinning up a database for testing, etc. In such cases, you can use the command below to apply the schema directly to the database:

  1. atlas schema apply \
  2. --env local \
  3. --url "postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable"

Or, using the Atlas Go SDK:

  1. ac, err := atlasexec.NewClient(".", "atlas")
  2. if err != nil {
  3. log.Fatalf("failed to initialize client: %w", err)
  4. }
  5. // Automatically update the database with the desired schema.
  6. // Another option, is to use 'migrate apply' or 'schema apply' manually.
  7. if _, err := ac.SchemaApply(ctx, &atlasexec.SchemaApplyParams{
  8. Env: "local",
  9. URL: "postgres://postgres:pass@localhost:5432/database?search_path=public&sslmode=disable",
  10. }); err != nil {
  11. log.Fatalf("failed to apply schema changes: %w", err)
  12. }

Code Example

After setting up our Ent schema and the RLS policies, we can open an Ent client and pass the different mutations and queries the relevant tenant ID we work on. This ensures that the database upholds our RLS policy:

  1. ctx1, ctx2 := sql.WithIntVar(ctx, "app.current_tenant", a8m.ID), sql.WithIntVar(ctx, "app.current_tenant", r3m.ID)
  2. users1 := client.User.Query().AllX(ctx1)
  3. // Users1 can only see users from tenant a8m.
  4. users2 := client.User.Query().AllX(ctx2)
  5. // Users2 can only see users from tenant r3m.

Row-Level Security - 图3Real World Example

In real applications, users can utilize hooks and interceptors to set the app.current_tenant variable based on the user’s context.

The code for this guide can be found in GitHub.