Skip to content
Tech Atlas, home
Search
Esc
  • All roadmapsBrowse every learning path
  • ExploreFind a technology area
  • ProjectsGuided projects and builds
  • My AtlasYour learning dashboard
Lesson 4 of 6 · Lab · 25 min · revision 2

Lab: Catalog Entries, Classification and Access Control

In PostgreSQL 17, register two tables in a small catalogue with owners, descriptions and sensitivity classes, then enforce access from those classes: role grants, column privileges, a masking view generated from the catalogue, default privileges, tenant row-level security and an access log.

Contentsand lesson path

What you will learn

  • Register datasets in a catalog with owners, descriptions and sensitivity classifications, and apply role-based access, column masking and row-level filters.

01. Goal and setup

Two teams store customer data in a shared mart. Analysts want to count customers by country, support agents need names, fraud investigators need everything, and a customer-facing app must show each customer company, or tenant, only its own orders. Writing a separate copy of the data for each group would multiply the personal data and drift out of date. Instead, you will keep one copy and control access to it.

Access rules are only as good as what you know about the data, so the lab starts with a catalogue: a register of datasets with an owner, a description and a sensitivity classification for each table and column. Here the classes are public, internal and pii (personally identifiable information). Then you will enforce access in the database itself, so that it applies to every tool that connects:

  • Role-based access control (RBAC): privileges go to group roles such as analyst, and people log in as users who are members.
  • Column privileges for support, and a masking view, generated from the catalogue, for analysts.
  • Row-level security (RLS) for the app's tenants.
  • An access log that records who read what.

Real catalogues, such as DataHub, OpenMetadata or a cloud provider's catalogue, store the same facts with search and lineage on top. A few tables are enough to see how classification drives policy. You need Docker. The lab was tested with PostgreSQL 17.11 in the postgres:17-alpine image; every command runs psql inside the container.

Terminal
mkdir catalog-lab && cd catalog-lab
docker run -d --name catalog-lab-pg -e POSTGRES_USER=lab -e POSTGRES_PASSWORD=lab \
  -e POSTGRES_DB=shop postgres:17-alpine
until docker exec catalog-lab-pg pg_isready -h 127.0.0.1 -U lab -q; do sleep 1; done

Save two small shell helpers and source them. pg runs SQL as the administrator; as_user connects as one lab user and runs one query. Inside the container the image trusts connections from 127.0.0.1, so passwords are not checked in this lab, but every privilege and policy is. A real server must require a password or a certificate for every login.

Bash · helpers.sh
# Source this file: pg runs SQL as the admin, as_user runs one query as a lab user.
pg() { docker exec -i catalog-lab-pg psql -X -q -U lab -d shop "$@"; }
as_user() {
  docker exec -i catalog-lab-pg psql -X -q \
    "postgresql://$1:[email protected]/shop" -c "$2"
}
Terminal
source helpers.sh

02. Step 1: Create the mart

Two tables: customers, with personal data, and orders. Both carry the tenant they belong to.

SQL · schema.sql
-- A small mart with personal data, shared by two tenants (customer companies).
SET client_min_messages = warning;
CREATE SCHEMA marts;
CREATE TABLE marts.customers (
  customer_id int PRIMARY KEY, tenant text NOT NULL, full_name text,
  email text, phone text, country text);
CREATE TABLE marts.orders (
  order_id int PRIMARY KEY, tenant text NOT NULL,
  customer_id int REFERENCES marts.customers, amount numeric(10, 2));
INSERT INTO marts.customers VALUES
  (1, 'acme',   'Ana Lima',     '[email protected]',   '+44 20 7946 0101', 'GB'),
  (2, 'acme',   'Ben Okafor',   '[email protected]', '+44 20 7946 0102', 'GB'),
  (3, 'globex', 'Chen Wei',     '[email protected]',   '+49 30 1234 5603', 'DE'),
  (4, 'globex', 'Dara Novak',   '[email protected]', '+49 30 1234 5604', 'DE');
INSERT INTO marts.orders VALUES
  (101, 'acme', 1, 120.00), (102, 'acme', 2, 35.50), (103, 'acme', 1, 99.90),
  (201, 'globex', 3, 410.00), (202, 'globex', 4, 15.25);
Terminal
pg -v ON_ERROR_STOP=1 < schema.sql
pg -c '\dt marts.*'
Expected output
         List of relations
 Schema |   Name    | Type  | Owner
--------+-----------+-------+-------
 marts  | customers | table | lab
 marts  | orders    | table | lab
(2 rows)

03. Step 2: Register the datasets in the catalogue

Each dataset gets an owner, the person or team who answers questions, approves access and handles incidents, and a description in plain words. Each column gets a class. The CHECK constraints keep the vocabulary small, which matters because policies will match on these exact words. Descriptions are also stored on the objects with COMMENT, where tools such as psql and BI tools display them. Then ask the catalogue a governance question: where is personal data, and who owns it?

SQL · catalog.sql
-- A minimal catalogue: owner, description and sensitivity of datasets and columns.
CREATE SCHEMA catalog;
CREATE TABLE catalog.datasets (
  dataset text PRIMARY KEY, owner text NOT NULL, description text NOT NULL,
  classification text NOT NULL CHECK (classification IN ('public', 'internal', 'pii')));
CREATE TABLE catalog.columns (
  dataset text REFERENCES catalog.datasets, column_name text,
  classification text NOT NULL CHECK (classification IN ('public', 'internal', 'pii')),
  PRIMARY KEY (dataset, column_name));
INSERT INTO catalog.datasets VALUES
  ('marts.customers', '[email protected]', 'One row per customer of a tenant.',
   'pii'),
  ('marts.orders', '[email protected]', 'One row per order, with its tenant.',
   'internal');
INSERT INTO catalog.columns VALUES
  ('marts.customers', 'customer_id', 'internal'),
  ('marts.customers', 'tenant', 'internal'),
  ('marts.customers', 'full_name', 'pii'),
  ('marts.customers', 'email', 'pii'),
  ('marts.customers', 'phone', 'pii'),
  ('marts.customers', 'country', 'public');
-- Descriptions also go on the objects themselves, where database tools show them.
COMMENT ON TABLE marts.customers IS 'Customers of each tenant. Owner: crm-team.';
COMMENT ON COLUMN marts.customers.email IS 'Contact email. PII: masked for analysts.';
Terminal
pg -v ON_ERROR_STOP=1 < catalog.sql
pg -c "SELECT c.dataset, c.column_name, d.owner
       FROM catalog.columns c JOIN catalog.datasets d USING (dataset)
       WHERE c.classification = 'pii' ORDER BY 1, 2"
Expected output
     dataset     | column_name |        owner
-----------------+-------------+----------------------
 marts.customers | email       | [email protected]
 marts.customers | full_name   | [email protected]
 marts.customers | phone       | [email protected]
(3 rows)

04. Step 3: Roles, grants and column privileges

roles.sql creates four group roles and one login per person or app. Privileges are granted to the groups only. When someone changes team, you change their membership, and nothing else. GRANT SELECT (column, ...) gives support a column privilege: they can read some columns of customers and not others. ALTER DEFAULT PRIVILEGES makes tables that are created later in marts readable by fraud investigators automatically; step 5 tests it.

SQL · roles.sql
-- Group roles carry the privileges; people log in as users who are members.
CREATE ROLE analyst NOLOGIN;
CREATE ROLE support NOLOGIN;
CREATE ROLE fraud NOLOGIN;
CREATE ROLE app_reader NOLOGIN;
CREATE ROLE ana LOGIN PASSWORD 'ana-lab-pass' IN ROLE analyst;
CREATE ROLE sam LOGIN PASSWORD 'sam-lab-pass' IN ROLE support;
CREATE ROLE fay LOGIN PASSWORD 'fay-lab-pass' IN ROLE fraud;
CREATE ROLE acme_app LOGIN PASSWORD 'acme_app-lab-pass' IN ROLE app_reader;
CREATE ROLE globex_app LOGIN PASSWORD 'globex_app-lab-pass' IN ROLE app_reader;
GRANT USAGE ON SCHEMA marts, catalog TO analyst, support, fraud, app_reader;
GRANT SELECT ON ALL TABLES IN SCHEMA catalog TO analyst, support, fraud;
-- Fraud investigators read everything in marts, including tables created later.
GRANT SELECT ON ALL TABLES IN SCHEMA marts TO fraud;
ALTER DEFAULT PRIVILEGES IN SCHEMA marts GRANT SELECT ON TABLES TO fraud;
-- Support may read some columns of customers and nothing else.
GRANT SELECT (customer_id, tenant, full_name, country) ON marts.customers TO support;
Terminal
pg -v ON_ERROR_STOP=1 < roles.sql
as_user sam "SELECT customer_id, full_name, country FROM marts.customers"
as_user sam "SELECT email FROM marts.customers"
as_user fay "SELECT full_name, email, phone FROM marts.customers WHERE customer_id = 3"
Expected output
 customer_id | full_name  | country
-------------+------------+---------
           1 | Ana Lima   | GB
           2 | Ben Okafor | GB
           3 | Chen Wei   | DE
           4 | Dara Novak | DE
(4 rows)

ERROR:  permission denied for table customers
 full_name |        email         |      phone
-----------+----------------------+------------------
 Chen Wei  | [email protected] | +49 30 1234 5603
(1 row)

05. Step 4: A masking view generated from the catalogue

Analysts may count and group customers, but they must not read contact details. Column masking returns a changed value instead of the real one: the first letter and domain of an email, the last four digits of a phone number. mask.sql builds the view from the catalogue. It reads the table's columns from information_schema, passes public and internal columns through, masks every pii column, and masks any column that has no class at all. That last rule, deny by default, protects you when someone adds a column and forgets the catalogue.

Analysts get SELECT on the view but not on the table. A view normally runs with the rights of its owner, so the analyst can read the masked values without being able to read the table itself.

SQL · mask.sql
-- Build marts.customers_masked from the catalogue. A column classified as pii,
-- or not classified at all, is masked; only public and internal columns pass.
SET client_min_messages = warning;
DO $$
DECLARE select_list text;
BEGIN
  SELECT string_agg(CASE
           WHEN coalesce(k.classification, 'pii') <> 'pii'
             THEN quote_ident(c.column_name)
           WHEN c.column_name = 'email' THEN format(
             'left(%1$I, 1) || ''***@'' || split_part(%1$I, ''@'', 2) AS %1$I',
             c.column_name)
           WHEN c.column_name = 'phone' THEN format(
             '''*** '' || right(%1$I, 4) AS %1$I', c.column_name)
           ELSE format('''***'' AS %I', c.column_name)
         END, ', ' ORDER BY c.ordinal_position)
    INTO select_list
    FROM information_schema.columns c
    LEFT JOIN catalog.columns k
      ON k.dataset = 'marts.customers' AND k.column_name = c.column_name
   WHERE c.table_schema = 'marts' AND c.table_name = 'customers';
  EXECUTE 'DROP VIEW IF EXISTS marts.customers_masked';
  EXECUTE format('CREATE VIEW marts.customers_masked AS SELECT %s FROM marts.customers',
                 select_list);
END $$;
GRANT SELECT ON marts.customers_masked TO analyst;
Terminal
pg -v ON_ERROR_STOP=1 < mask.sql
as_user ana "SELECT * FROM marts.customers_masked"
as_user ana "SELECT email FROM marts.customers"
Expected output
 customer_id | tenant | full_name |      email       |  phone   | country
-------------+--------+-----------+------------------+----------+---------
           1 | acme   | ***       | a***@example.com | *** 0101 | GB
           2 | acme   | ***       | b***@example.com | *** 0102 | GB
           3 | globex | ***       | c***@example.com | *** 5603 | DE
           4 | globex | ***       | d***@example.com | *** 5604 | DE
(4 rows)

ERROR:  permission denied for table customers

Now add a column without classifying it, and rebuild the view. A view's columns are fixed when it is created, so the build must run again whenever the table changes; in a real pipeline it runs after every migration.

Terminal
pg -c "ALTER TABLE marts.customers ADD COLUMN birth_date date"
pg < mask.sql
as_user ana "SELECT customer_id, email, birth_date FROM marts.customers_masked"
Expected output
 customer_id |      email       | birth_date
-------------+------------------+------------
           1 | a***@example.com | ***
           2 | b***@example.com | ***
           3 | c***@example.com | ***
           4 | d***@example.com | ***
(4 rows)

06. Step 5: Default privileges for tables created later

Create a new table in marts. The fraud role can read it at once, because of the default privileges from step 3; the analyst role cannot, because nobody granted it anything on the new table.

Terminal
pg -c "CREATE TABLE marts.refunds (order_id int, amount numeric(10, 2))"
as_user fay "SELECT count(*) AS refunds FROM marts.refunds"
as_user ana "SELECT count(*) AS refunds FROM marts.refunds"
Expected output
 refunds
---------
       0
(1 row)

ERROR:  permission denied for table refunds

07. Step 6: Row-level security for tenants

The app connects with one login per tenant. Row-level security adds a filter that the database applies to every query on the table. Once it is enabled, PostgreSQL shows a role only the rows that one of its policies allows, and a role with no matching policy sees nothing. The tenant comes from current_user, the login itself, through the tenant_logins table, so a session cannot claim to be another tenant. The second policy lets fraud investigators keep reading every order.

SQL · rls.sql
-- Which tenant each application login belongs to.
CREATE TABLE marts.tenant_logins (login text PRIMARY KEY, tenant text NOT NULL);
INSERT INTO marts.tenant_logins VALUES ('acme_app', 'acme'), ('globex_app', 'globex');
GRANT SELECT ON marts.tenant_logins, marts.orders TO app_reader;

-- Row-level security: an app login sees only the rows of its own tenant.
ALTER TABLE marts.orders ENABLE ROW LEVEL SECURITY;
CREATE POLICY tenant_isolation ON marts.orders FOR SELECT TO app_reader
  USING (tenant = (SELECT t.tenant FROM marts.tenant_logins t
                   WHERE t.login = current_user));

-- With RLS on, a role without a policy sees no rows. Fraud investigators see all.
CREATE POLICY fraud_reads_all ON marts.orders FOR SELECT TO fraud USING (true);
Terminal
pg -v ON_ERROR_STOP=1 < rls.sql
as_user acme_app "SELECT * FROM marts.orders"
as_user globex_app "SELECT count(*) AS orders FROM marts.orders"
as_user fay "SELECT count(*) AS orders FROM marts.orders"
Expected output
 order_id | tenant | customer_id | amount
----------+--------+-------------+--------
      101 | acme   |           1 | 120.00
      102 | acme   |           2 |  35.50
      103 | acme   |           1 |  99.90
(3 rows)

 orders
--------
      2
(1 row)

 orders
--------
      5
(1 row)

08. Step 7: A view that leaks, and the fix

The app team adds a summary view and grants it to the app role. Ask for it as Acme.

SQL · views.sql
-- A summary view for the app. By default a view runs with its owner's rights.
CREATE VIEW marts.order_totals AS
  SELECT tenant, count(*) AS orders, sum(amount) AS amount
  FROM marts.orders GROUP BY tenant ORDER BY tenant;
GRANT SELECT ON marts.order_totals TO app_reader;
Terminal
pg -v ON_ERROR_STOP=1 < views.sql
as_user acme_app "SELECT * FROM marts.order_totals"
Expected output
 tenant | orders | amount
--------+--------+--------
 acme   |      3 | 255.40
 globex |      2 | 425.25
(2 rows)

Acme sees Globex's totals. The view runs with its owner's rights, the owner is lab, and superusers and table owners normally bypass row security. The masking view in step 4 relied on exactly this behaviour; here it is a leak. Since PostgreSQL 15, security_invoker = true makes a view check the privileges and policies of the user who queries it.

Terminal
pg -c "ALTER VIEW marts.order_totals SET (security_invoker = true)"
as_user acme_app "SELECT * FROM marts.order_totals"
Expected output
 tenant | orders | amount
--------+--------+--------
 acme   |      3 | 255.40
(1 row)

09. Step 8: Record who reads personal data

An access log answers "who read this column, and when?". Here the server puts the user and database in every log line, and logs every statement that fay runs. Role settings apply to the login role, so the setting is on fay, not on the fraud group. Run a query as Fay and look for it in the server log.

SQL · audit.sql
-- Put the user and database in every log line, and log all statements by fay.
ALTER SYSTEM SET log_line_prefix = '%m [%p] user=%u db=%d ';
ALTER ROLE fay SET log_statement = 'all';
SELECT pg_reload_conf();
Terminal
pg -v ON_ERROR_STOP=1 < audit.sql > /dev/null
as_user fay "SELECT email FROM marts.customers LIMIT 1" > /dev/null
docker logs catalog-lab-pg 2>&1 | grep -o "user=fay.*"
Expected output
user=fay db=shop LOG:  statement: SELECT email FROM marts.customers LIMIT 1

In production, the pgAudit extension produces structured audit records per object, and the logs go to central storage with their own retention, so that they survive the database and cannot be edited by the people they describe. Logs are only useful if each person has their own login: a shared account would make every line say the same user. Remove the container and its data volume when you have finished: docker rm -f -v catalog-lab-pg.

10. Check your understanding

Practice check · 3 questions

Catalogue, grants and policies

Each question changes one detail of the lab. Pick the best answer.

Q1. You create a login `initech_app` in the `app_reader` role but forget to add it to `marts.tenant_logins`. What does `SELECT count(*) FROM marts.orders` return for it?
Q2. An engineer adds `ip_address` to `marts.customers` and does not run `mask.sql` again. What do analysts see in `customers_masked`?
Q3. Why did `acme_app` see Globex totals through `marts.order_totals` in step 7?
Practice only: not graded, not saved, not evidence.

11. Apply it

This is the access part of the skill practice. For a pipeline you built:

  • Register its main tables with owner, description and a class per column, and add a test that fails when a table has an unclassified column.
  • Mask the email column for an analyst role with a generated view, or with column privileges, and give a second role full access.
  • Enforce tenant isolation with a row-level policy, and make every view on that table use security_invoker = true.
  • Turn on access logging for the roles that may read personal data, and write down where the logs are kept and for how long.

12. Review prompt

Without looking back, explain: why a catalogue needs an owner and a class for each column; how group roles, column privileges and default privileges differ; how the masking view uses the catalogue and why unclassified columns are masked; what RLS does for a role with no matching policy; why a view can bypass RLS and how security_invoker fixes it; and what an access log must contain to be useful.

References

Your progress

Reading state

Sign in to save that you finished reading this lesson.

Sign in to mark reading complete

Prove this skill

10 questions · about 8 minutes · scored automatically. Marking a lesson as read never demonstrates a skill.
Take the skill check