Module 8 ยท Information Systems ยท Lesson 13 ยท Week 10

Data Security, Authorizations, and Access

Reference material for the last session of the module, in which six controls of data protection are applied to the DataApp of a fictitious card shop in a PostgreSQL that runs inside the browser: the inventory of personal data under the LGPD, roles of least privilege, row level security, pseudonymisation and k-anonymity, an append-only audit log and the access policy written as an automated test. In the second hour each group applies the same controls to the partner data in ClickHouse.

About this session

Data Security, Authorizations, and Access ยท 17/12/2026 ยท Prof. Afonso

Learning objective

By the end of the session, students should be able to classify the personal data of a DataApp under the LGPD and implement, in the database, the access controls that follow from it (roles of least privilege, row level security, pseudonymisation with k-anonymity and an append-only audit log), verifying them with an automated access test, first in the card shop of the lab and then on the partner data in ClickHouse.

Session strategy

Demonstration followed by application. In the first hour the professor applies six controls to the DataApp of a fictitious card shop, live, with a coding agent and six CREATE prompts, in a PostgreSQL (PGlite) that runs inside the browser, proving each control with SET ROLE and closing with a case study of how this portal protects its exams. In the second hour each group applies the same controls to the partner data in the ClickHouse of the class (shrek2) with the seventh prompt.

Session structure

  1. Daily โ€” 15 min
  2. The LGPD, data governance and security in layers (5 min)
  3. Steps 01โ€“02: inventory of personal data; roles and least privilege (12 min)
  4. Steps 03โ€“04: row level security; pseudonymisation and k-anonymity (14 min)
  5. Steps 05โ€“06: audit log; the access policy as an automated test; case study of the exams of the portal (14 min)
  6. Second hour: the six controls on the partner data in ClickHouse (60 min)
Part IFoundations

1. How to read this material

This material accompanies Lesson 13, the last session of Module 8, which has two hours. In the first, the professor applies six controls of data protection to the DataApp of a fictitious card shop, live, with a coding agent and a PostgreSQL that runs inside the browser. In the second hour each group applies the same controls to the partner data in the ClickHouse of the class.

Part I presents what the LGPD protects, what it asks of a DataApp and how data governance divides the duties among jobs. Part II describes the lab and its synthetic data. Part III follows the six steps of the session: the inventory, the roles, the row policies, the masking, the audit log and the access tests. Part IV studies how this portal itself keeps its exams away from the class, Part V carries the controls to ClickHouse for the second hour, and Part VI gathers the prompts, the reference numbers and the mistakes found in the rehearsal. Every number was measured on 08/11/2026 with PGlite 0.5.10 (PostgreSQL 18.6); every date of the data is Unix time in seconds.

2. What the LGPD protects

The Lei Geral de Proteรงรฃo de Dados Pessoais (Law 13,709/2018) regulates every operation on personal data carried out in Brazil, about people in Brazil or for the offer of goods and services to them, whether the operation is collection, storage, combination, analysis or publication. A DataApp that receives the customers of a partner is therefore processing personal data from its first load, and the team that builds it answers for how it does so. The law rests on three definitions of its article 5, which decide which rules apply to each column of a table.

DefinitionArticleConsequence for the DataApp
personal data: information about an identified or identifiable natural personart. 5, Ithe whole law applies; an internal id that links rows to a person is personal data
sensitive personal data: racial or ethnic origin, religious belief, political opinion, union membership, health, sex life, genetic or biometric dataart. 5, II; art. 11stricter legal bases, usually specific and highlighted consent
anonymised data: data about a person who cannot be identified by reasonable technical means available at the timeart. 5, III; art. 12outside the law, as long as the anonymisation cannot be reversed with reasonable effort
pseudonymisation: the data loses the possibility of association with a person except by additional information kept separatelyart. 13, ยง4still personal data; reduces the risk, does not remove the duties

The distinction between the last two rows matters most for a DataApp. A table in which the customer became a key that the company can still link back to the person is pseudonymised and remains under the law; only an aggregate from which no reasonable means recovers a person leaves it. Step 04 builds both, and the dashboard of the shop receives only the second.

3. Principles, legal bases and accountability

Article 6 lists ten principles, and five of them translate directly into controls of a database. The principle of purpose requires a legitimate and explicit reason for each processing; necessity limits the data to the minimum that the purpose needs; security and prevention require technical measures against unauthorised access and incidents; and accountability requires the controller to demonstrate that the measures exist and work. A team that keeps a column without a purpose violates the second principle, and a team that cannot show who accessed a record fails the last one.

Each processing also needs one of the legal bases of article 7, or of article 11 for sensitive data. The card shop uses four: the performance of the contract of sale for most of the customer data, a legal obligation for the CPF on the invoice, consent for marketing, and the specific consent of article 11 for the accessibility need of a customer, which is health data. A legal basis is attached to a purpose, so the same column may be lawful for the store and unlawful for the analysts.

AgentArticleRole
controllerart. 5, VIdecides why and how the data is processed; answers for it
operatorart. 5, VIIprocesses on behalf of the controller, as a DataApp built for a partner does
encarregado (DPO)art. 41the channel between the controller, the data subjects and the ANPD
ANPDart. 55-Athe national authority, which supervises and sanctions; fines of up to 2 % of the revenue in Brazil, limited to R$ 50 million per infraction (art. 52)

Article 37 asks the controller and the operator to keep a record of the processing operations, and article 46 asks for technical and administrative measures that protect the data from unauthorised access and from accidental or unlawful destruction, loss, alteration or disclosure. These two articles are the legal ground of steps 02 to 06.

4. Data governance: jobs, duties and roles

Data governance assigns to each person a job with duties over the data: who owns a dataset, who keeps it correct, who operates the platform, who consumes it and who answers to the authority. These duties stay on paper unless the database enforces them, and it does so only when each job is a role with its own privileges. The lab therefore creates one role per job and makes each person a member of a job, so that replacing a manager is a change of membership and not a review of every grant.

Job in governanceRole in the labMayMay not
custodian of the platformapp_ownerown the tables and change their structureread a row without a policy
the ETL of the DataAppetl_writerinsert customers and ordersread what it wrote
data steward of a storemanager_sp, manager_rj, manager_bhread the own store; look up a contact with a stated purposesee another store
analystanalystread the pseudonymised viewsread a name, an e-mail or a CPF
consumer of a dashboarddashboardread the anonymised aggregateread anything else
encarregado (DPO)dporead the inventory and the audit logread the personal data itself

5. Security in layers

Information security is usually described by three properties: confidentiality, by which only authorised people read the data; integrity, by which only authorised changes happen; and availability, by which the data is there when needed. This lesson concentrates on the first two. A single control rarely guarantees them, because every control fails sometimes, through a careless grant, a bug or a stolen password. Defence in depth stacks independent controls, so that the failure of one is contained by the next.

The six steps of the lab form such a stack. The privilege of the table decides whether a role reaches it; the policy of the row decides which part of it the role sees; the masking of the columns decides what an authorised analyst learns about a person; the audit log records what happened; and the access test detects when a change has weakened any of the layers. Step 06 shows the stack at work: a careless grant opens the first layer, the second still returns no row, and the test fails anyway because the policy demands that both hold.

Part IIThe lab

6. PostgreSQL inside the browser

The lab of this lesson keeps the format of the lab of Lesson 6, with another engine. PGlite 0.5.10 is PostgreSQL 18 compiled to WebAssembly and loaded from a CDN, so the page runs a real PostgreSQL, with roles, grants, row level security, PL/pgSQL functions and triggers, and nothing is installed. The session is always the superuser postgres; SET ROLE plays each job and RESET ROLE comes back, and a badge on the page shows which role is acting. Every statement that changes the database, SET ROLE included, is kept in the localStorage and replayed in order on the next visit, which rebuilds the same roles, policies and log.

TableRowsPersonal data
shop.stores3 (sp, rj, bh)none
shop.customers60name, e-mail, CPF, phone, birth date, city, consent; an accessibility need for 5 customers
shop.orders400the customer, the moment of the sale and the last four digits of the payment card

The data is synthetic and says so. The surnames are Exemplo, Fictรญcio, Teste, Modelo, Amostra or Simulado, the e-mails use example.com, a domain reserved for examples, and every CPF starts with 000. The names of the cards and their prices come from the TCGplayer capture of Lesson 6. A lab about personal data must not hold the data of a real person, and the same rule applies to the test data of any DataApp: a copy of production in a notebook is a processing of personal data without purpose.

At the bottom of the page, the access matrix runs the test of step 06 and draws one cell per role and probe, outlined in coral when the outcome differs from the policy. The page is at lab/lesson-13/index.html.

Part IIISix controls

7. Step 01: the inventory of personal data

No access can be designed before the team knows what it keeps. The first control is a table of the database, gov.data_catalog, with one row per column of the schema shop: its category under article 5, whether it is a direct identifier, a quasi-identifier or neither, its purpose, its legal basis, its retention and what the analytics layer does with it. Two queries test the inventory against the catalogue of PostgreSQL, so that a column added later without classification fails the test.

A direct identifier points at one person alone, as the CPF or the e-mail do. A quasi-identifier does not, but a few of them together do: among 60 customers, the birth date, the city and the store narrow the search to one or two people. Latanya Sweeney showed in 2000 that the ZIP code, the birth date and the sex identify most of the population of the United States, and the same arithmetic applies to any small population. The inventory marks the quasi-identifiers so that step 04 generalises them.

CategoryAnalyticsColumnsWhich
sensitivedrop1accessibility_need
personaldrop7full name, e-mail, CPF, phone, city, consent date, card last 4
personalpseudonymise2customer_id of customers and of orders
personalgeneralise3birth date, customer since, moment of the order
personalkeep2store of the customer, marketing consent
operationalkeep10products, quantities, prices, stores, payment method
sql/01_classify.sql
-- Step 01 ยท Classify the personal data and decide what the DataApp keeps
-- Lesson 13 ยท Module 8 ยท Information Systems ยท Inteli
--
-- LGPD (Law 13,709/2018), art. 5: personal data (I) identifies a natural person
-- or makes the person identifiable; sensitive personal data (II) includes data on
-- health, among others; anonymised data (III) can no longer be linked to a person.
-- Art. 6, III (necessity): only the data needed for the declared purpose.
-- The catalogue below is the first control of the lesson: a column without a
-- category, a purpose and a retention rule has no reason to exist.

CREATE SCHEMA gov;

CREATE TABLE gov.data_catalog (
  table_name     text NOT NULL,
  column_name    text NOT NULL,
  category       text NOT NULL CHECK (category IN ('personal', 'sensitive', 'anonymous', 'operational')),
  identifier     text NOT NULL CHECK (identifier IN ('direct', 'quasi', 'none')),
  purpose        text NOT NULL,
  legal_basis    text NOT NULL,
  retention_days integer,
  analytics      text NOT NULL CHECK (analytics IN ('keep', 'pseudonymise', 'generalise', 'drop')),
  PRIMARY KEY (table_name, column_name)
);

INSERT INTO gov.data_catalog VALUES
  ('stores',    'store_id',           'operational', 'none',   'identify the store',                 'not personal data',                 NULL, 'keep'),
  ('stores',    'city',               'operational', 'none',   'location of the store',              'not personal data',                 NULL, 'keep'),
  ('stores',    'uf',                 'operational', 'none',   'location of the store',              'not personal data',                 NULL, 'keep'),
  ('customers', 'customer_id',        'personal',    'direct', 'link orders to the customer',        'art. 7, V: performance of contract', 1825, 'pseudonymise'),
  ('customers', 'store_id',           'personal',    'quasi',  'store where the customer is served', 'art. 7, V: performance of contract', 1825, 'keep'),
  ('customers', 'full_name',          'personal',    'direct', 'identify the customer at the counter', 'art. 7, V: performance of contract', 1825, 'drop'),
  ('customers', 'email',              'personal',    'direct', 'send the receipt',                   'art. 7, V: performance of contract', 1825, 'drop'),
  ('customers', 'cpf',                'personal',    'direct', 'issue the invoice',                  'art. 7, II: legal obligation',       1825, 'drop'),
  ('customers', 'phone',              'personal',    'direct', 'notify a reserved order',            'art. 7, V: performance of contract', 1825, 'drop'),
  ('customers', 'birth_unix',         'personal',    'quasi',  'confirm the customer is of age',     'art. 7, V: performance of contract', 1825, 'generalise'),
  ('customers', 'city',               'personal',    'quasi',  'delivery',                           'art. 7, V: performance of contract', 1825, 'drop'),
  ('customers', 'accessibility_need', 'sensitive',   'none',   'adapt the service at the store',     'art. 11, I: specific consent',        365, 'drop'),
  ('customers', 'marketing_consent',  'personal',    'none',   'record of the consent',              'art. 7, I: consent',                 1825, 'keep'),
  ('customers', 'consent_unix',       'personal',    'none',   'proof of the consent (art. 8, ยง2)',  'art. 7, I: consent',                 1825, 'drop'),
  ('customers', 'created_unix',       'personal',    'none',   'customer since',                     'art. 7, V: performance of contract', 1825, 'generalise'),
  ('orders',    'order_id',           'operational', 'none',   'identify the order',                 'art. 7, V: performance of contract', 1825, 'keep'),
  ('orders',    'customer_id',        'personal',    'direct', 'link the order to the customer',     'art. 7, V: performance of contract', 1825, 'pseudonymise'),
  ('orders',    'store_id',           'operational', 'none',   'store of the sale',                  'art. 7, V: performance of contract', 1825, 'keep'),
  ('orders',    'ordered_unix',       'personal',    'quasi',  'date of the sale',                   'art. 7, V: performance of contract', 1825, 'generalise'),
  ('orders',    'product',            'operational', 'none',   'what was sold',                      'art. 7, V: performance of contract', 1825, 'keep'),
  ('orders',    'set_name',           'operational', 'none',   'set of the card',                    'art. 7, V: performance of contract', 1825, 'keep'),
  ('orders',    'quantity',           'operational', 'none',   'how many units',                     'art. 7, V: performance of contract', 1825, 'keep'),
  ('orders',    'unit_price',         'operational', 'none',   'price paid',                         'art. 7, V: performance of contract', 1825, 'keep'),
  ('orders',    'payment_method',     'operational', 'none',   'reconcile the cash register',        'art. 7, V: performance of contract', 1825, 'keep'),
  ('orders',    'card_last4',         'personal',    'quasi',  'answer a dispute of the payment',    'art. 7, IX: legitimate interest',     180, 'drop');

COMMENT ON COLUMN shop.customers.accessibility_need IS 'Sensitive personal data (LGPD art. 5, II, health). Store staff only; never in analytics.';
COMMENT ON COLUMN shop.customers.cpf IS 'Direct identifier. Invoice only; never in analytics.';

-- Test 1: every column of the schema shop is classified (expected: no rows).
SELECT c.table_name, c.column_name
FROM information_schema.columns AS c
LEFT JOIN gov.data_catalog AS d USING (table_name, column_name)
WHERE c.table_schema = 'shop' AND d.column_name IS NULL;

-- Test 2: the catalogue has no column that is not in the database (expected: no rows).
SELECT d.table_name, d.column_name
FROM gov.data_catalog AS d
LEFT JOIN information_schema.columns AS c
  ON c.table_schema = 'shop' AND c.table_name = d.table_name AND c.column_name = d.column_name
WHERE c.column_name IS NULL;

-- What reaches the analytics layer, by category.
SELECT category, analytics, count(*) AS columns, string_agg(table_name || '.' || column_name, ', ' ORDER BY table_name, column_name) AS which
FROM gov.data_catalog
GROUP BY category, analytics
ORDER BY category, analytics;

8. Step 02: roles and least privilege

The principle of least privilege gives each job only the privileges its purpose needs. PostgreSQL implements it with roles: a role without LOGIN represents a job, a person is a role that is a member of it, and every privilege is granted to the job. The lab creates ten roles, moves the tables of shop from the superuser to app_owner, revokes from PUBLIC every privilege on the schemas and tables involved, and grants to each job what the table of governance allows.

Three details of PostgreSQL decide whether the grants mean what they seem to mean. A role needs USAGE on a schema before any table of it can be read, so a SELECT on a table of a schema without usage grants nothing. Every new function is executable by PUBLIC unless that privilege is revoked, which steps 03 and 05 do for each function they create. And ALTER DEFAULT PRIVILEGES decides the privileges of objects that do not exist yet: every view that analytics_owner creates in analytics is readable by the analysts without a grant that someone could forget.

The ETL is the clearest case. It inserts customers and orders and reads only the stores it validates against; it cannot select a customer, not even one it inserted. If its password leaks, no customer is exposed, which is the purpose of least privilege.

sql/02_roles.sql
-- Step 02 ยท Roles and least privilege
-- Lesson 13 ยท Module 8 ยท Information Systems ยท Inteli
--
-- One role per job, never per person: people come and go, the jobs stay. A person
-- receives a job by membership (GRANT role TO person). Each job gets only the
-- privileges its purpose needs, and nothing is granted to PUBLIC.
-- In PGlite the session is always the superuser postgres; SET ROLE plays each job.

-- Group roles (jobs). NOLOGIN: nobody connects as a job, only as a person.
CREATE ROLE app_owner        NOLOGIN;              -- owns the tables of shop; not a superuser
CREATE ROLE etl_writer       NOLOGIN;              -- the ETL of the DataApp: writes, does not read customers
CREATE ROLE analytics_owner  NOLOGIN BYPASSRLS;    -- owns the pseudonymised views of analytics
CREATE ROLE analyst          NOLOGIN;              -- reads only analytics
CREATE ROLE dashboard        NOLOGIN;              -- reads only the anonymised aggregate
CREATE ROLE store_manager    NOLOGIN;              -- reads the customers and orders of its own store
CREATE ROLE dpo              NOLOGIN;              -- encarregado (LGPD art. 41): reads the catalogue and the audit log

-- People of the fictitious shop, one per store, who receive the job by membership.
CREATE ROLE manager_sp NOLOGIN IN ROLE store_manager;
CREATE ROLE manager_rj NOLOGIN IN ROLE store_manager;
CREATE ROLE manager_bh NOLOGIN IN ROLE store_manager;

-- The tables leave the superuser: a non-superuser owner is subject to FORCE ROW LEVEL SECURITY (step 03).
ALTER SCHEMA shop OWNER TO app_owner;
ALTER TABLE shop.stores    OWNER TO app_owner;
ALTER TABLE shop.customers OWNER TO app_owner;
ALTER TABLE shop.orders    OWNER TO app_owner;

-- Nothing for PUBLIC, the implicit role of every user.
REVOKE ALL ON SCHEMA public FROM PUBLIC;
REVOKE ALL ON ALL TABLES IN SCHEMA shop FROM PUBLIC;
REVOKE ALL ON ALL TABLES IN SCHEMA gov  FROM PUBLIC;

-- Schemas of the next steps, created now so that the grants are in one place.
CREATE SCHEMA analytics AUTHORIZATION analytics_owner;
CREATE SCHEMA audit;

-- ETL: writes new customers and orders, reads only the stores it validates against.
GRANT USAGE ON SCHEMA shop TO etl_writer;
GRANT SELECT ON shop.stores TO etl_writer;
GRANT INSERT ON shop.customers, shop.orders TO etl_writer;

-- Store managers: read the operational tables; step 03 limits the rows to their store.
GRANT USAGE ON SCHEMA shop TO store_manager;
GRANT SELECT ON shop.stores, shop.customers, shop.orders TO store_manager;

-- The owner of analytics reads the raw tables to build the pseudonymised views.
GRANT USAGE ON SCHEMA shop TO analytics_owner;
GRANT SELECT ON shop.customers, shop.orders, shop.stores TO analytics_owner;

-- Analysts and the dashboard enter only analytics; step 04 decides which views each one reads.
GRANT USAGE ON SCHEMA analytics TO analyst, dashboard;
ALTER DEFAULT PRIVILEGES FOR ROLE analytics_owner IN SCHEMA analytics GRANT SELECT ON TABLES TO analyst;

-- The DPO reads the governance catalogue and, in step 05, the audit log.
GRANT USAGE ON SCHEMA gov, audit TO dpo;
GRANT SELECT ON gov.data_catalog TO dpo;

-- The privileges as a matrix: which job may SELECT or INSERT in which table.
SELECT r.rolname AS role,
       t.tbl     AS table_name,
       has_table_privilege(r.rolname, t.tbl, 'SELECT') AS can_select,
       has_table_privilege(r.rolname, t.tbl, 'INSERT') AS can_insert,
       has_table_privilege(r.rolname, t.tbl, 'UPDATE') AS can_update,
       has_table_privilege(r.rolname, t.tbl, 'DELETE') AS can_delete
FROM pg_roles AS r
CROSS JOIN (VALUES ('shop.customers'), ('shop.orders'), ('gov.data_catalog')) AS t(tbl)
WHERE r.rolname IN ('etl_writer', 'analyst', 'dashboard', 'manager_sp', 'dpo')
ORDER BY r.rolname, t.tbl;

-- The ETL writes but cannot read what it wrote: least privilege in one line.
SET ROLE etl_writer;
SELECT has_table_privilege('shop.customers', 'INSERT') AS etl_can_insert,
       has_table_privilege('shop.customers', 'SELECT') AS etl_can_select;
RESET ROLE;

9. Step 03: row level security

A grant decides which tables a role reaches; a policy decides which rows of them it sees. With row level security enabled on a table, a row is visible to a role only when some policy for that role returns true for the row, and a table with RLS and no policy for a role shows it nothing. The superuser and the roles with BYPASSRLS ignore the policies, and the owner of the table ignores them too unless the table is set to FORCE ROW LEVEL SECURITY. The lab enables and forces RLS on customers and orders, so that even app_owner, which owns them, sees no customer.

The policy of the managers compares the store of the row with the stores of the acting role, read by the function gov.my_stores() from gov.store_staff, a table that the managers cannot read. The function is SECURITY DEFINER, so it runs with the privileges of its owner, and its search_path is fixed, so that nobody can make it call a function of the same name in another schema. Inside such a function current_user is the owner and not the caller, which is why gov.actor() reads the acting role from current_setting('role') and, with a real login and no SET ROLE, from session_user.

Acting asStores seenOrdersRevenue, US$
manager_spsp16258,258.08
manager_rjrj12865,629.66
postgres (superuser)sp, rj, bh400136,259.33
app_owner (owner, FORCE)none0โ€”

A common shortcut writes the policy over a setting, USING (store_id = current_setting('app.store_id')), which the application sets at the start of each request. The shortcut is safe only when the application is the sole client of the database and no user writes SQL, because any role can run SET app.store_id = 'rj' and read the other store. A DataApp in which analysts open notebooks against the database does not meet that condition.

sql/03_row_security.sql
-- Step 03 ยท Row level security: each manager sees only the rows of the own store
-- Lesson 13 ยท Module 8 ยท Information Systems ยท Inteli
--
-- GRANT decides which tables a role reads; a policy decides which rows. With RLS on,
-- a row is visible only when some policy of the role returns true for it, so a
-- table with RLS and no policy shows nothing to anybody but the superuser and the
-- roles with BYPASSRLS. FORCE extends the rule to the owner of the table.

-- Who works in which store. Kept in gov, which the managers cannot read.
CREATE TABLE gov.store_staff (role_name text NOT NULL, store_id text NOT NULL REFERENCES shop.stores, PRIMARY KEY (role_name, store_id));
INSERT INTO gov.store_staff VALUES ('manager_sp', 'sp'), ('manager_rj', 'rj'), ('manager_bh', 'bh');

-- The role that is acting. Inside a SECURITY DEFINER function current_user is the
-- owner of the function, so the role set by SET ROLE (or the login) is read instead.
CREATE FUNCTION gov.actor() RETURNS text
LANGUAGE sql STABLE
AS $$ SELECT coalesce(nullif(current_setting('role'), 'none'), session_user::text) $$;
GRANT EXECUTE ON FUNCTION gov.actor() TO PUBLIC;

-- The stores of the acting role. SECURITY DEFINER: the policy can read gov.store_staff
-- without granting it to the managers; search_path is fixed so nobody can hijack it.
CREATE FUNCTION gov.my_stores() RETURNS SETOF text
LANGUAGE sql STABLE SECURITY DEFINER SET search_path = pg_catalog, gov
AS $$ SELECT store_id FROM gov.store_staff WHERE role_name = gov.actor() $$;
REVOKE EXECUTE ON FUNCTION gov.my_stores() FROM PUBLIC;
GRANT EXECUTE ON FUNCTION gov.my_stores() TO store_manager;

ALTER TABLE shop.customers ENABLE ROW LEVEL SECURITY;
ALTER TABLE shop.orders    ENABLE ROW LEVEL SECURITY;
ALTER TABLE shop.customers FORCE ROW LEVEL SECURITY;
ALTER TABLE shop.orders    FORCE ROW LEVEL SECURITY;

CREATE POLICY manager_reads_own_store ON shop.customers
  FOR SELECT TO store_manager
  USING (store_id IN (SELECT gov.my_stores()));
CREATE POLICY manager_reads_own_store ON shop.orders
  FOR SELECT TO store_manager
  USING (store_id IN (SELECT gov.my_stores()));

-- The ETL inserts rows of any store, but only of a store that exists.
CREATE POLICY etl_inserts ON shop.customers
  FOR INSERT TO etl_writer
  WITH CHECK (store_id IN ('sp', 'rj', 'bh'));
CREATE POLICY etl_inserts ON shop.orders
  FOR INSERT TO etl_writer
  WITH CHECK (store_id IN ('sp', 'rj', 'bh'));

-- The same query, three roles, three answers.
SET ROLE manager_sp;
SELECT 'manager_sp' AS role, store_id, count(*) AS orders, round(sum(quantity * unit_price), 2) AS revenue FROM shop.orders GROUP BY store_id;
SET ROLE manager_rj;
SELECT 'manager_rj' AS role, store_id, count(*) AS orders, round(sum(quantity * unit_price), 2) AS revenue FROM shop.orders GROUP BY store_id;
RESET ROLE;
SELECT 'postgres (superuser)' AS role, store_id, count(*) AS orders, round(sum(quantity * unit_price), 2) AS revenue FROM shop.orders GROUP BY store_id ORDER BY store_id;

-- FORCE at work: the owner of the table has no policy, so it sees no customer.
SET ROLE app_owner;
SELECT 'app_owner' AS role, count(*) AS customers_visible FROM shop.customers;
RESET ROLE;

-- An anti-pattern, for comparison: a policy over a setting that the user can change.
--   USING (store_id = current_setting('app.store_id'))
-- Any role runs SET app.store_id = 'rj' and reads the other store. A setting is safe
-- only when the application is the sole client and the users never write SQL.

10. Step 04: pseudonymisation, generalisation and aggregation

The analysts of the shop need to know how customers behave, not who they are. The analytics layer applies the decisions of the inventory with three techniques. Pseudonymisation replaces the customer id by a key, the first 16 hexadecimal characters of the SHA-256 of a secret pepper followed by the id. Without the pepper the key would be useless as protection, because there are only 60 ids and computing their 60 hashes reverses every key; with it, only the holder of the pepper can link a key back to a customer, which is exactly the "additional information kept separately" of article 13, ยง4.

Generalisation reduces the precision of the quasi-identifiers: the birth date becomes an age band (18-24, 25-34, 35-49, 50+), the moment of an order becomes its day in Unix time (ordered_unix / 86400 * 86400), and the e-mail is masked as its first letter and its domain. Aggregation with a minimum group size, the k-anonymity of Samarati and Sweeney, publishes only the groups with at least k distinct customers: with k = 5, of the 11 segments of store and age band, 7 are published and 4 are suppressed, with 7 customers in them.

The three views belong to analytics_owner, which reads shop and has BYPASSRLS. A view runs with the privileges of its owner, so the analysts read the views without any grant on the raw tables, and the dashboard reads only the aggregate. The pepper is a table that only analytics_owner reads; in production it belongs to a secret manager or to an environment variable outside the repository, since whoever holds the pepper and the keys can reverse every pseudonym. In the lab the pepper is drawn again at each replay, so the keys change after a reload, while the customers behind them do not.

sql/04_masking.sql
-- Step 04 ยท Pseudonymisation, masking and an anonymised aggregate
-- Lesson 13 ยท Module 8 ยท Information Systems ยท Inteli
--
-- The analytics layer never sees a name, an e-mail or a CPF. Three techniques:
--   pseudonymisation (LGPD art. 13, ยง4): the customer becomes a key that only the
--     holder of a secret pepper can link back to the person, so it is still personal data;
--   generalisation: birth date -> age band, timestamp -> day, which reduces the
--     quasi-identifiers of the catalogue;
--   aggregation with a minimum group size (k-anonymity): a group with fewer than k
--     customers is suppressed, so the dashboard shows data that is anonymised (art. 5, III, and art. 12).
-- The views belong to analytics_owner, which reads shop; the analysts read only the views.

-- The pepper. In production it lives in a secret manager or in an environment variable
-- outside the repository; here it is a table that only analytics_owner reads.
CREATE TABLE gov.pepper (name text PRIMARY KEY, value text NOT NULL);
INSERT INTO gov.pepper VALUES ('customer_key', md5(random()::text) || md5(random()::text));
REVOKE ALL ON gov.pepper FROM PUBLIC;
GRANT USAGE ON SCHEMA gov TO analytics_owner;
GRANT SELECT ON gov.pepper TO analytics_owner;

SET ROLE analytics_owner;

CREATE VIEW analytics.customers_pseudo AS
SELECT left(encode(sha256(convert_to(p.value || ':' || c.customer_id, 'UTF8')), 'hex'), 16) AS customer_key,
       c.store_id,
       CASE WHEN a.age < 25 THEN '18-24' WHEN a.age < 35 THEN '25-34' WHEN a.age < 50 THEN '35-49' ELSE '50+' END AS age_band,
       left(c.email, 1) || '***@' || split_part(c.email, '@', 2) AS email_masked,
       c.marketing_consent,
       c.created_unix / 86400 * 86400 AS customer_since_day_unix
FROM shop.customers AS c
CROSS JOIN gov.pepper AS p
CROSS JOIN LATERAL (SELECT floor((extract(epoch FROM now()) - c.birth_unix) / 31557600)::int AS age) AS a
WHERE p.name = 'customer_key';

CREATE VIEW analytics.orders_pseudo AS
SELECT o.order_id,
       left(encode(sha256(convert_to(p.value || ':' || o.customer_id, 'UTF8')), 'hex'), 16) AS customer_key,
       o.store_id,
       o.ordered_unix / 86400 * 86400 AS day_unix,
       o.product, o.set_name, o.quantity, o.unit_price, o.payment_method
FROM shop.orders AS o
CROSS JOIN gov.pepper AS p
WHERE p.name = 'customer_key';

-- k = 5: a store and age band with fewer than five customers does not appear.
CREATE VIEW analytics.sales_by_segment AS
SELECT c.store_id, c.age_band,
       count(DISTINCT c.customer_key) AS customers,
       count(*) AS orders,
       round(sum(o.quantity * o.unit_price), 2) AS revenue
FROM analytics.orders_pseudo AS o
JOIN analytics.customers_pseudo AS c USING (customer_key)
GROUP BY c.store_id, c.age_band
HAVING count(DISTINCT c.customer_key) >= 5;

RESET ROLE;

-- The dashboard reads only the aggregate; the default privilege of step 02 already
-- gave every view of analytics to the analysts.
GRANT SELECT ON analytics.sales_by_segment TO dashboard;

-- What the analyst sees.
SET ROLE analyst;
SELECT * FROM analytics.customers_pseudo ORDER BY customer_key LIMIT 8;
SELECT * FROM analytics.sales_by_segment ORDER BY store_id, age_band;
RESET ROLE;

-- How many segments k = 5 suppressed, and how many customers were in them.
WITH seg AS (
  SELECT c.store_id, c.age_band, count(*) AS customers
  FROM analytics.customers_pseudo AS c
  WHERE c.customer_key IN (SELECT customer_key FROM analytics.orders_pseudo)
  GROUP BY 1, 2
)
SELECT count(*) FILTER (WHERE customers < 5) AS suppressed_segments,
       coalesce(sum(customers) FILTER (WHERE customers < 5), 0) AS customers_in_them,
       count(*) FILTER (WHERE customers >= 5) AS published_segments
FROM seg;

11. Step 05: the audit log

Article 37 asks for a record of the processing operations, and the accountability principle asks the controller to be able to show it. The log of the lab, audit.events, records who acted, what was done, on which table and row, when (Unix time), with what purpose and on which columns. Two mechanisms feed it. A trigger on shop.customers records every INSERT, UPDATE and DELETE; a read, which no trigger sees, can only be recorded by the code that serves it, so the contact data of a customer is served only by shop.lookup_customer(id, purpose), which checks that the actor manages the store of the customer, demands a purpose of at least ten characters and writes a READ event.

The log records the names of the changed columns and never their values. A log with the old and the new e-mail would be a second store of personal data, with its own retention and its own leaks, and would have to be protected as carefully as the table it audits. The log is also append-only: a trigger refuses every UPDATE and DELETE of audit.events, the owner included, and only the DPO reads it.

ActorActionRowPurposeColumns
manager_spREADcustomer 1Notify the customer that a reserved order arrivedemail, full_name, phone
etl_writerINSERTcustomer 61โ€”the 12 columns of the row
postgresUPDATEcustomer 1โ€”email

The function refuses by raising an error, which rolls back the transaction and, with it, any event it could have written. A refused lookup therefore leaves no trace, and an attacker who tries every customer of another store is invisible to the DPO. Part IV shows how the exams of this portal solve the same problem.

sql/05_audit.sql
-- Step 05 ยท Audit log: who did what, when and why
-- Lesson 13 ยท Module 8 ยท Information Systems ยท Inteli
--
-- LGPD art. 37: the controller keeps a record of the processing operations; art. 46:
-- technical measures protect the data from unauthorised access. Two kinds of event:
--   changes, caught by a trigger on every INSERT, UPDATE and DELETE of shop.customers;
--   reads of contact data, which a trigger cannot see, so they happen only through a
--   function that checks the store, demands a purpose and writes the event.
-- The log records the names of the changed columns and never their values, otherwise
-- the log itself would become a second copy of the personal data.

CREATE TABLE audit.events (
  event_id   bigserial PRIMARY KEY,
  at_unix    bigint NOT NULL DEFAULT extract(epoch FROM now())::bigint,
  actor      text   NOT NULL,
  action     text   NOT NULL,
  table_name text   NOT NULL,
  row_key    text,
  purpose    text,
  columns    text[]
);
REVOKE ALL ON audit.events FROM PUBLIC;
GRANT SELECT ON audit.events TO dpo;

-- Append-only: an UPDATE or DELETE of the log fails for every role, the owner included.
CREATE FUNCTION audit.refuse_change() RETURNS trigger
LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'audit.events is append-only'; END $$;
CREATE TRIGGER append_only BEFORE UPDATE OR DELETE ON audit.events
  FOR EACH STATEMENT EXECUTE FUNCTION audit.refuse_change();

-- Changes. SECURITY DEFINER: the trigger writes the log, which the actor cannot touch.
CREATE FUNCTION audit.log_change() RETURNS trigger
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, audit, gov
AS $$
DECLARE
  changed text[];
  rec jsonb := to_jsonb(coalesce(NEW, OLD));
BEGIN
  IF TG_OP = 'UPDATE' THEN
    SELECT array_agg(n.key ORDER BY n.key) INTO changed
    FROM jsonb_each(to_jsonb(NEW)) AS n
    JOIN jsonb_each(to_jsonb(OLD)) AS o USING (key)
    WHERE n.value IS DISTINCT FROM o.value;
  ELSE
    SELECT array_agg(k ORDER BY k) INTO changed FROM jsonb_object_keys(rec) AS k;
  END IF;
  INSERT INTO audit.events (actor, action, table_name, row_key, columns)
  VALUES (gov.actor(), TG_OP, TG_TABLE_SCHEMA || '.' || TG_TABLE_NAME, rec ->> 'customer_id', changed);
  RETURN NULL;
END $$;
CREATE TRIGGER audit_customers AFTER INSERT OR UPDATE OR DELETE ON shop.customers
  FOR EACH ROW EXECUTE FUNCTION audit.log_change();

-- Reads of contact data: the only door to name, e-mail and phone for a manager.
CREATE FUNCTION shop.lookup_customer(p_customer_id integer, p_purpose text)
RETURNS TABLE (customer_id integer, full_name text, email text, phone text)
LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, shop, gov, audit
AS $$
DECLARE
  v_store text;
BEGIN
  IF NOT pg_has_role(gov.actor(), 'store_manager', 'MEMBER') THEN
    RAISE EXCEPTION 'only a store manager may look up a customer';
  END IF;
  IF length(coalesce(trim(p_purpose), '')) < 10 THEN
    RAISE EXCEPTION 'state the purpose of the lookup (at least 10 characters)';
  END IF;
  SELECT c.store_id INTO v_store FROM shop.customers AS c WHERE c.customer_id = p_customer_id;
  IF v_store IS NULL OR v_store NOT IN (SELECT s.store_id FROM gov.store_staff AS s WHERE s.role_name = gov.actor()) THEN
    RAISE EXCEPTION 'customer % is not a customer of your store', p_customer_id;
  END IF;
  INSERT INTO audit.events (actor, action, table_name, row_key, purpose, columns)
  VALUES (gov.actor(), 'READ', 'shop.customers', p_customer_id::text, p_purpose, ARRAY['email', 'full_name', 'phone']);
  RETURN QUERY SELECT c.customer_id, c.full_name, c.email, c.phone FROM shop.customers AS c WHERE c.customer_id = p_customer_id;
END $$;
ALTER FUNCTION shop.lookup_customer(integer, text) OWNER TO postgres;
-- A new function is executable by PUBLIC by default; this one is for managers only.
REVOKE EXECUTE ON FUNCTION shop.lookup_customer(integer, text) FROM PUBLIC;
GRANT EXECUTE ON FUNCTION shop.lookup_customer(integer, text) TO store_manager;

-- Three events: a manager looks up a customer of the own store, the ETL inserts a new
-- customer, and the back office (the superuser here) corrects an e-mail at the request of
-- the customer (art. 18, III).
SET ROLE manager_sp;
SELECT * FROM shop.lookup_customer(1, 'Notify the customer that a reserved order arrived');
SET ROLE etl_writer;
INSERT INTO shop.customers VALUES (61, 'rj', 'Ulisses Exemplo', 'ulisses.exemplo61@example.com', '000.123.456-61', '(21) 90000-0061', 820497600, 'Rio de Janeiro', NULL, true, 1794052860, 1794052800);
RESET ROLE;
UPDATE shop.customers SET email = 'ana.exemplo.new@example.com' WHERE customer_id = 1;

-- Who did what (the DPO reads the log).
SET ROLE dpo;
SELECT event_id, at_unix, actor, action, table_name, row_key, purpose, columns FROM audit.events ORDER BY event_id;
SELECT actor, action, count(*) AS events FROM audit.events GROUP BY actor, action ORDER BY actor, action;
RESET ROLE;

12. Step 06: the policy as an automated test

A policy that nobody tests drifts with the next grant, because the person who adds a privilege on a busy day rarely reviews the whole policy. The last control writes the expected access of each role as data, in gov.expected_access, from the table of governance and before the first run, and a function runs every probe as every role and compares. The expectations must come from the policy; copying them from a first run would turn the test into a photograph of whatever the database does, errors included.

gov.try_as(role, sql) runs the statement twice, first as the superuser and then under SET LOCAL ROLE, each time inside a block of PL/pgSQL with an exception handler, which PostgreSQL executes as a subtransaction. The block always ends by raising a known exception, so the subtransaction is always rolled back: an INSERT or a DELETE that succeeds leaves no row, not even an event in the audit log. The outcome is denied when the statement fails, none when it returns no row, some when it returns fewer rows than the superuser and all otherwise.

Roleread customersread ordersinsert customerlookup contactread pseudonymsread segmentsread pepperread audit logerase audit log
etl_writerdenieddeniedalldenieddenieddenieddenieddenieddenied
manager_spsomesomedeniedalldenieddenieddenieddenieddenied
manager_rjsomesomedenieddenieddenieddenieddenieddenieddenied
analystdenieddenieddenieddeniedallalldenieddenieddenied
dashboarddenieddenieddenieddenieddeniedalldenieddenieddenied
dpodenieddenieddenieddenieddenieddenieddeniedalldenied
app_ownernonenonedenieddenieddenieddenieddenieddenieddenied

The 63 pairs pass. The script then makes the careless change on purpose, GRANT USAGE ON SCHEMA shop TO analyst and GRANT SELECT ON ALL TABLES IN SCHEMA shop TO analyst, and two pairs fail: the analyst now reaches customers and orders, and RLS, having no policy for the analyst, still returns no row. The second layer held, the observed outcome is none instead of denied, and the test fails because the policy demands that the first layer holds too. After the REVOKE the test passes again. The same function runs in a CI pipeline against the database of a project, which is what the second request of prompt 06 asks for in pytest.

sql/06_access_tests.sql
-- Step 06 ยท The access matrix as an automated test
-- Lesson 13 ยท Module 8 ยท Information Systems ยท Inteli
--
-- A security policy that nobody tests drifts with the next GRANT. The policy of the
-- DataApp is written as a table of expectations (role ร— probe -> denied, none, some
-- or all of the rows), and a function runs every probe as every role and compares.
-- Each probe runs inside a subtransaction that is always rolled back, so an INSERT
-- or DELETE that succeeds leaves no trace, not even in the audit log.

CREATE TABLE gov.probes (probe text PRIMARY KEY, ord integer NOT NULL, sql text NOT NULL);
INSERT INTO gov.probes VALUES
  ('read customers',   1, 'SELECT * FROM shop.customers'),
  ('read orders',      2, 'SELECT * FROM shop.orders'),
  ('insert customer',  3, $q$INSERT INTO shop.customers VALUES (900, 'rj', 'Zeca Teste', 'zeca.teste90@example.com', '000.000.000-90', NULL, NULL, 'Rio de Janeiro', NULL, false, NULL, 1794052800)$q$),
  ('lookup contact',   4, $q$SELECT * FROM shop.lookup_customer(1, 'Notify a reserved order')$q$),
  ('read pseudonyms',  5, 'SELECT * FROM analytics.orders_pseudo'),
  ('read segments',    6, 'SELECT * FROM analytics.sales_by_segment'),
  ('read pepper',      7, 'SELECT * FROM gov.pepper'),
  ('read audit log',   8, 'SELECT * FROM audit.events'),
  ('erase audit log',  9, 'DELETE FROM audit.events');

-- Runs a statement as a role and classifies the outcome against the superuser:
-- denied (error), none (0 rows), some (fewer rows than the superuser) or all.
CREATE FUNCTION gov.try_as(p_role text, p_sql text) RETURNS text
LANGUAGE plpgsql AS $$
DECLARE
  n bigint; base bigint; msg text;
BEGIN
  BEGIN
    EXECUTE p_sql; GET DIAGNOSTICS base = ROW_COUNT;
    RAISE EXCEPTION USING ERRCODE = 'P0001', MESSAGE = 'rollback';
  EXCEPTION WHEN raise_exception THEN NULL; WHEN others THEN base := NULL;
  END;
  BEGIN
    EXECUTE format('SET LOCAL ROLE %I', p_role);
    EXECUTE p_sql; GET DIAGNOSTICS n = ROW_COUNT;
    RAISE EXCEPTION USING ERRCODE = 'P0001', MESSAGE = 'rollback';
  EXCEPTION
    WHEN raise_exception THEN
      IF SQLERRM <> 'rollback' THEN RETURN 'denied'; END IF;
    WHEN others THEN
      RETURN 'denied';
  END;
  IF n = 0 THEN RETURN 'none'; END IF;
  IF base IS NULL OR n >= base THEN RETURN 'all'; END IF;
  RETURN 'some';
END $$;
REVOKE EXECUTE ON FUNCTION gov.try_as(text, text) FROM PUBLIC;

-- The policy of the DataApp, written before the test. Read a row as a requirement:
-- "the analyst must be denied the raw customers".
CREATE TABLE gov.expected_access (role text, probe text REFERENCES gov.probes, expected text NOT NULL CHECK (expected IN ('denied', 'none', 'some', 'all')), PRIMARY KEY (role, probe));
INSERT INTO gov.expected_access
SELECT r.role, p.probe, e.expected
FROM (VALUES
  ('etl_writer', ARRAY['denied', 'denied', 'all',    'denied', 'denied', 'denied', 'denied', 'denied', 'denied']),
  ('manager_sp', ARRAY['some',   'some',   'denied', 'all',    'denied', 'denied', 'denied', 'denied', 'denied']),
  ('manager_rj', ARRAY['some',   'some',   'denied', 'denied', 'denied', 'denied', 'denied', 'denied', 'denied']),
  ('analyst',    ARRAY['denied', 'denied', 'denied', 'denied', 'all',    'all',    'denied', 'denied', 'denied']),
  ('dashboard',  ARRAY['denied', 'denied', 'denied', 'denied', 'denied', 'all',    'denied', 'denied', 'denied']),
  ('dpo',        ARRAY['denied', 'denied', 'denied', 'denied', 'denied', 'denied', 'denied', 'all',    'denied']),
  ('app_owner',  ARRAY['none',   'none',   'denied',   'denied', 'denied', 'denied', 'denied', 'denied', 'denied'])
) AS r(role, list)
CROSS JOIN LATERAL unnest(r.list) WITH ORDINALITY AS e(expected, ord)
JOIN gov.probes AS p ON p.ord = e.ord;

-- The test: every pair of the policy, observed against expected.
CREATE FUNCTION gov.access_test()
RETURNS TABLE (role text, probe text, ord integer, expected text, observed text, pass boolean)
LANGUAGE sql AS $$
  SELECT e.role, e.probe, p.ord, e.expected, o.observed, o.observed = e.expected
  FROM gov.expected_access AS e
  JOIN gov.probes AS p USING (probe)
  CROSS JOIN LATERAL (SELECT gov.try_as(e.role, p.sql) AS observed) AS o
$$;
REVOKE EXECUTE ON FUNCTION gov.access_test() FROM PUBLIC;

-- The verdict: expected 63 pairs, 63 passed.
SELECT count(*) AS pairs, count(*) FILTER (WHERE pass) AS passed, count(*) FILTER (WHERE NOT pass) AS failed FROM gov.access_test();

-- The matrix, one row per role (the same matrix the lab draws below the editor).
SELECT role,
       max(observed) FILTER (WHERE ord = 1) AS read_customers,
       max(observed) FILTER (WHERE ord = 2) AS read_orders,
       max(observed) FILTER (WHERE ord = 3) AS insert_customer,
       max(observed) FILTER (WHERE ord = 4) AS lookup_contact,
       max(observed) FILTER (WHERE ord = 5) AS read_pseudonyms,
       max(observed) FILTER (WHERE ord = 6) AS read_segments,
       max(observed) FILTER (WHERE ord = 7) AS read_pepper,
       max(observed) FILTER (WHERE ord = 8) AS read_audit,
       max(observed) FILTER (WHERE ord = 9) AS erase_audit
FROM gov.access_test()
GROUP BY role
ORDER BY role;

-- A regression on purpose: the careless "give the analyst access to shop" of a busy day.
-- RLS still returns no row (none instead of denied), so the second layer held; the test
-- fails anyway, because the policy says the first layer must hold too.
GRANT USAGE ON SCHEMA shop TO analyst;
GRANT SELECT ON ALL TABLES IN SCHEMA shop TO analyst;
SELECT role, probe, expected, observed FROM gov.access_test() WHERE NOT pass;
REVOKE SELECT ON ALL TABLES IN SCHEMA shop FROM analyst;
REVOKE USAGE ON SCHEMA shop FROM analyst;
SELECT count(*) FILTER (WHERE NOT pass) AS failed_after_revoke FROM gov.access_test();
Part IVCase study

13. How this portal keeps the exams away from the class

The repository of these lessons is public, so any text versioned in it can be read by the class days before a session. A written exam projected from a deck therefore cannot live in the HTML of the deck, nor in the SQL that loads it. The design adopted by the portal applies the controls of this lesson to that problem, and its source is the file supabase/prova-schema.sql of the repository, which contains the structure and no exam.

ControlHow the exams use itStep of the lab
deny by defaultthe tables of the exam have RLS enabled and no policy, and REVOKE ALL from the roles of the public API03
one doorprova_abrir(slug, token), SECURITY DEFINER with a fixed search_path, is the only way to read a statement05
secret as a hashthe function compares the SHA-256 of the token typed by the professor with a stored hash; the token in clear exists in no table, no file and no page04
every attempt loggedeach attempt, right or wrong, is a row of a log, which also limits guessing: after eight wrong tokens in five minutes the next wrong ones are refused05
secrets outside the repositorythe SQL that loads each exam lives in a folder that git ignores, and the password of the database in the environment file of the infrastructure04

Two decisions of the design answer problems that the lab leaves open. The function returns a refusal as data, {"ok": false}, instead of raising an error, because an error rolls back the transaction and the record of the attempt with it; without that choice, the counter of failures would never grow and the limit would never close. And the function checks the right token before the limit of attempts, so that eight wrong guesses from anywhere cannot prevent the professor from projecting the exam on time, which would turn the protection into a denial of service against the class. Both decisions are possible improvements of shop.lookup_customer.

Part VYour DataApp

14. The same controls in ClickHouse

In the second hour each group applies the six controls to the partner data in the ClickHouse of the class (shrek2, database lab, objects gNN_). ClickHouse implements the same ideas with its own syntax: roles and grants, row policies, and functions of hash for the pseudonyms. It has no trigger, but it records every query in system.query_log, with the user, the kind of query, the tables read and the moment, which serves as the audit of reads. The user of each group may lack the privilege ACCESS MANAGEMENT, in which case the statements of roles, grants and policies are a reference that the administrator of the server runs.

ControlPostgreSQL (lab)ClickHouse (shrek2)
roleCREATE ROLE analyst NOLOGINCREATE ROLE g01_analyst
grantGRANT SELECT ON analytics.x TO analystGRANT SELECT ON lab.g01_x TO g01_analyst
row policyCREATE POLICY ... USING (...) + ENABLE ROW LEVEL SECURITYCREATE ROW POLICY g01_p ON lab.g01_x USING ... TO g01_analyst
pseudonymencode(sha256(convert_to(p || id, 'UTF8')), 'hex')hex(SHA256(concat(p, ':', toString(id))))
k-anonymityHAVING count(DISTINCT c) >= 5HAVING uniqExact(c) >= 5
audit of readsa function that writes the eventsystem.query_log
checkhas_table_privilege, gov.access_test()SHOW GRANTS FOR g01_analyst
the reads of the personal tables of group 01 in the last 7 days
SELECT event_time, user, query_kind, tables
FROM system.query_log
WHERE type = 'QueryFinish'
  AND has(tables, 'lab.g01_db_ingestion')
  AND event_time > now() - INTERVAL 7 DAY
ORDER BY event_time DESC
LIMIT 50;

Two behaviours matter for the design. Once a table has a row policy, the users that no policy covers see no row by default, the same deny by default of RLS; the server setting users_without_row_policies_can_read_rows can change that, so the group confirms it with a query as each role. And a row policy filters reads only: the documentation of ClickHouse warns that it makes sense for read-only users, because a user who can modify the table or copy its partitions defeats it, so who may load is decided by the grant alone.

15. What each group delivers

  • docs/data_inventory.md: every field of lab.gNN_db_ingestion, by data_tag, and of the gold views, classified as in step 01, with the analytics decision of each.
  • docs/access_policy.md: the jobs of the DataApp of the group (who loads, who analyses, which dashboard reads, who answers for the data at the partner) and the expected access of each job, as the table of step 06.
  • sql/clickhouse/security.sql: the roles, the grants, a row policy when the partner has a regional or business cut, a pseudonymised view and an aggregate with k = 5, ending with SHOW GRANTS.
  • docs/audit.md: the query of system.query_log that lists the reads of the personal tables of the group.

The pepper of the group never enters the repository: it is an environment variable of the ETL or a setting of the server.

Part VILab reference

16. The prompts of the session

The professor runs each prompt with a coding agent in a new folder, pastes the SQL in the lab and compares the result with the reference SQL of the step. Each prompt states the facts measured in the rehearsal, so that both the agent and the class can check the result.

Step 01 ยท Classify

Prompt 01 ยท CREATE
[C] Character
You are the data protection engineer of a DataApp. A fictitious card shop
with three stores (sp, rj, bh) sells TCGplayer cards and keeps its customers
and orders in PostgreSQL. Before anybody gets access to anything, you
classify every column under the LGPD (Law 13,709/2018).

[R] Request
1. docs/data_inventory.md: for each column of shop.stores, shop.customers
   and shop.orders, its category under art. 5 (personal, sensitive,
   anonymous or operational), whether it is a direct identifier, a
   quasi-identifier or neither, the purpose, the legal basis of art. 7 or
   art. 11, the retention in days and what the analytics layer does with it
   (keep, pseudonymise, generalise or drop), justified by the principle of
   necessity of art. 6, III.
2. sql/01_classify.sql, schema gov:
   - table gov.data_catalog with those eight attributes, CHECK constraints
     on the closed lists, primary key (table_name, column_name), and one
     row per column;
   - COMMENT ON COLUMN for the sensitive column and for the CPF;
   - test 1: the columns of shop that are not in the catalogue (no rows);
   - test 2: the rows of the catalogue that are not columns of shop (no rows);
   - a summary of the columns by category and by analytics decision.

Facts measured on 08/11/2026 (confirm before use):
- 3 stores, 60 customers, 400 orders; 25 columns in the three tables.
- accessibility_need is health data, so sensitive (art. 5, II); 5 customers
  have it filled.

[E] Example
shop.customers(customer_id, store_id, full_name, email, cpf, phone,
  birth_unix, city, accessibility_need, marketing_consent, consent_unix,
  created_unix)
('customers', 'cpf', 'personal', 'direct', 'issue the invoice',
 'art. 7, II: legal obligation', 1825, 'drop')

[A] Adjustments
- The data is synthetic: every person is fake, the e-mails use the reserved
  domain example.com and the CPFs start with 000. Never write a real person.
- An internal id that links rows to a person is still personal data.
- A quasi-identifier alone does not identify, but a few of them together
  do (birth date, city, store): mark them, step 04 generalises them.
- Every date is Unix time in seconds (BIGINT).
- The script is pasted into the lab page and runs in PGlite 0.5.10
  (PostgreSQL 18 compiled to WebAssembly) as the superuser postgres.

[T] Type of output
The two files and nothing else.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Review before moving on:

  • both tests return no rows
  • accessibility_need is sensitive, with specific consent
  • every direct identifier leaves analytics

Step 02 ยท Roles

Prompt 02 ยท CREATE
[C] Character
You are the data protection engineer of the card shop of step 01. The
inventory is done; now you decide who may touch what, by least privilege.

[R] Request
1. docs/access_policy.md: the jobs of the DataApp and, for each one, what it
   needs and why: app_owner (owns the tables, not a superuser), etl_writer
   (the ETL: inserts customers and orders, reads only the stores),
   analytics_owner (owns the pseudonymised views, BYPASSRLS), analyst
   (reads only analytics), dashboard (reads only the anonymised aggregate),
   store_manager (reads its own store) and dpo (the encarregado of art. 41:
   reads the catalogue and the audit log); and one person per store,
   manager_sp, manager_rj and manager_bh, members of store_manager.
2. sql/02_roles.sql:
   - every role NOLOGIN; the people receive the job with IN ROLE;
   - schema shop and its tables owned by app_owner;
   - REVOKE ALL from PUBLIC on the schema public, on the tables of shop
     and of gov;
   - schemas analytics (AUTHORIZATION analytics_owner) and audit;
   - the GRANTs of each job, and ALTER DEFAULT PRIVILEGES so that every
     view analytics_owner creates in analytics is readable by analyst;
   - the privilege matrix with has_table_privilege for five roles and three
     tables;
   - SET ROLE etl_writer, the proof that it inserts but cannot select
     customers, RESET ROLE.

[E] Example
CREATE ROLE store_manager NOLOGIN;
CREATE ROLE manager_sp NOLOGIN IN ROLE store_manager;
GRANT SELECT ON shop.customers TO store_manager;

[A] Adjustments
- One role per job, never per person; a person is a member of a job.
- Nothing is granted to PUBLIC; a function is executable by PUBLIC by
  default, which step 03 and step 05 revoke.
- A schema needs USAGE before any table of it can be read.
- PGlite has one session, the superuser postgres: SET ROLE plays each role
  and RESET ROLE comes back. End the script with RESET ROLE.

[T] Type of output
The two files and nothing else.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Review before moving on:

  • ten roles, all NOLOGIN
  • the ETL inserts customers and cannot select them
  • no privilege left to PUBLIC on shop

Step 03 ยท Row level security

Prompt 03 ยท CREATE
[C] Character
You are the data protection engineer of the card shop. GRANT decided the
tables each job reads; now row level security decides the rows, so that a
store manager sees only the customers and orders of the own store.

[R] Request
1. sql/03_row_security.sql:
   - table gov.store_staff (role_name, store_id) with the three managers;
   - function gov.actor(): the role that is acting, read from
     current_setting('role') and, when there is no SET ROLE, session_user;
   - function gov.my_stores(), SECURITY DEFINER with a fixed search_path,
     executable only by store_manager, returning the stores of the actor;
   - ENABLE and FORCE ROW LEVEL SECURITY on shop.customers and shop.orders;
   - a SELECT policy for store_manager over gov.my_stores(), and an INSERT
     policy for etl_writer that accepts only existing stores;
   - the proof: the same query of orders and revenue by store as
     manager_sp, as manager_rj and as the superuser; and app_owner seeing
     zero customers because of FORCE.
2. docs/access_policy.md: a section on RLS, with the anti-pattern of a
   policy over a setting that the user can change (SET app.store_id).

Facts measured on 08/11/2026 (confirm before use):
- orders by store: sp 162 (US$ 58,258.08), rj 128 (US$ 65,629.66),
  bh 110 (US$ 12,371.59).

[E] Example
CREATE POLICY manager_reads_own_store ON shop.orders
  FOR SELECT TO store_manager
  USING (store_id IN (SELECT gov.my_stores()));

[A] Adjustments
- Inside a SECURITY DEFINER function current_user is the owner of the
  function, not the caller: use gov.actor().
- The superuser and the roles with BYPASSRLS ignore every policy; FORCE
  makes the owner of the table obey them.
- A table with RLS and no policy for a role shows no row to that role.
- End the script with RESET ROLE.

[T] Type of output
The SQL file and the new section, nothing else.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Review before moving on:

  • manager_sp sees 162 orders and manager_rj 128
  • app_owner sees no customer
  • the policy reads a function, not a setting

Step 04 ยท Masking

Prompt 04 ยท CREATE
[C] Character
You are the data protection engineer of the card shop. The analysts need
sales by customer profile, never the name, the e-mail or the CPF of a
customer.

[R] Request
1. sql/04_masking.sql:
   - table gov.pepper with one random secret, readable only by
     analytics_owner;
   - as analytics_owner, three views in analytics:
     - customers_pseudo: customer_key (the first 16 hex characters of the
       SHA-256 of pepper || ':' || customer_id), store_id, age_band
       (18-24, 25-34, 35-49, 50+), email_masked (first letter, ***, domain),
       marketing_consent and the day the customer arrived, in Unix time;
     - orders_pseudo: the order with customer_key instead of customer_id,
       the day in Unix time and no card_last4;
     - sales_by_segment: customers, orders and revenue by store and age
       band, suppressing every group with fewer than 5 distinct customers;
   - SELECT on sales_by_segment for dashboard;
   - as analyst, eight rows of customers_pseudo and the whole aggregate;
   - how many segments k = 5 suppressed and how many customers were in them.
2. docs/data_inventory.md: a section on the difference between pseudonymised
   data (still personal, art. 13, ยง4) and anonymised data (art. 5, III and
   art. 12), and where the pepper lives in production.

Facts measured on 08/11/2026 (confirm before use):
- 7 segments published, 4 suppressed with 7 customers in them.

[E] Example
SELECT left(encode(sha256(convert_to(p.value || ':' || c.customer_id,
       'UTF8')), 'hex'), 16) AS customer_key
FROM shop.customers AS c CROSS JOIN gov.pepper AS p

[A] Adjustments
- A hash of the id without a secret is reversible by brute force: 60 ids
  take 60 hashes.
- A view runs with the privileges of its owner, so the analyst reads the
  view without any GRANT on shop.
- PGlite has sha256() and md5() built in; there is no pgcrypto.
- Every date is Unix time in seconds; the day is ts / 86400 * 86400.
- End the script with RESET ROLE.

[T] Type of output
The SQL file and the new section, nothing else.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Review before moving on:

  • the analyst reads the views without grants on shop
  • the key uses the pepper
  • 7 segments published, 4 suppressed

Step 05 ยท Audit log

Prompt 05 ยท CREATE
[C] Character
You are the data protection engineer of the card shop. The LGPD asks the
controller to keep a record of the operations on personal data (art. 37);
you write the audit log of the DataApp.

[R] Request
1. sql/05_audit.sql:
   - table audit.events (event_id, at_unix, actor, action, table_name,
     row_key, purpose, columns), readable only by dpo;
   - a trigger that refuses every UPDATE and DELETE of audit.events;
   - a SECURITY DEFINER trigger on shop.customers that logs every INSERT,
     UPDATE and DELETE with the actor and the names of the changed columns,
     never their values;
   - function shop.lookup_customer(customer_id, purpose), SECURITY DEFINER,
     the only door to name, e-mail and phone: it refuses who is not a store
     manager, a purpose shorter than 10 characters and a customer of another
     store, and logs a READ event with the purpose; EXECUTE revoked from
     PUBLIC and granted to store_manager;
   - three events: manager_sp looks up customer 1, etl_writer inserts
     customer 61, the superuser corrects the e-mail of customer 1;
   - as dpo, the log and the count of events by actor and action.

[E] Example
INSERT INTO audit.events (actor, action, table_name, row_key, columns)
VALUES (gov.actor(), TG_OP, TG_TABLE_SCHEMA || '.' || TG_TABLE_NAME,
        rec ->> 'customer_id', changed);

[A] Adjustments
- A trigger never sees a SELECT: reads of personal data are logged by the
  function that serves them.
- The log is append-only and holds no personal data besides the key of the
  row, otherwise it becomes a second copy to protect.
- at_unix is Unix time in seconds (extract(epoch FROM now())::bigint).
- Fix the search_path of every SECURITY DEFINER function.
- End the script with RESET ROLE.

[T] Type of output
The SQL file and nothing else.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Review before moving on:

  • three events, with the purpose of the READ
  • only names of columns, never values
  • UPDATE and DELETE of the log are refused

Step 06 ยท Access tests

Prompt 06 ยท CREATE
[C] Character
You are the data protection engineer of the card shop. A policy that nobody
tests drifts with the next GRANT, so you turn the access policy into an
automated test that runs every probe as every role.

[R] Request
1. sql/06_access_tests.sql:
   - table gov.probes (probe, ord, sql) with nine probes: read customers,
     read orders, insert customer, lookup contact, read pseudonyms, read
     segments, read pepper, read audit log, erase audit log;
   - function gov.try_as(role, sql): runs the statement first as the
     superuser and then under SET LOCAL ROLE, each time inside a
     subtransaction that is always rolled back, and returns denied (error),
     none (0 rows), some (fewer rows than the superuser) or all;
   - table gov.expected_access with the expected outcome of the nine probes
     for etl_writer, manager_sp, manager_rj, analyst, dashboard, dpo and
     app_owner, written from docs/access_policy.md before running anything;
   - function gov.access_test() returning role, probe, ord, expected,
     observed and pass;
   - the verdict (pairs, passed, failed) and the matrix with one row per role;
   - a regression on purpose: GRANT USAGE on shop and SELECT on all its
     tables to analyst, the failing pairs, the REVOKE, and the test green again.
2. tests/test_access.py: the same verdict run by pytest against the
   PostgreSQL of the project, failing when any pair fails.

Facts measured on 08/11/2026 (confirm before use):
- 63 pairs, 63 passed. After the careless GRANT: analyst reads customers
  and orders as none instead of denied, 2 failures.

[E] Example
BEGIN
  EXECUTE format('SET LOCAL ROLE %I', p_role);
  EXECUTE p_sql; GET DIAGNOSTICS n = ROW_COUNT;
  RAISE EXCEPTION USING ERRCODE = 'P0001', MESSAGE = 'rollback';
EXCEPTION WHEN raise_exception THEN ...

[A] Adjustments
- The expectations come from the policy, never from a first run of the test.
- A probe that raises an exception of its own (P0001 with another message)
  is denied.
- The rollback also removes the events that a successful probe would write
  to the audit log.

[T] Type of output
The two files and nothing else.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop at the end.

Review before moving on:

  • 63 of 63 pairs
  • 2 failures after the careless grant
  • 0 failures after the REVOKE

Second hour ยท Your DataApp in ClickHouse

Prompt 07 ยท CREATE
[C] Character
You are the data protection engineer of our group. The DataApp of the
partner keeps its landing table, its gold layer and its reports in the
ClickHouse of the class (shrek2), in the database lab, where every object
of the group starts with gNN_. We apply the six steps of the lab to it.

[R] Request
1. docs/data_inventory.md: every column of lab.gNN_db_ingestion (the fields
   of data_json, by data_tag) and of the gold views, classified as in step
   01, with the analytics decision of each one.
2. docs/access_policy.md: the jobs of our DataApp (who loads, who analyses,
   which dashboard reads, who answers for the data at the partner) and the
   expected access of each job, as the table of step 06.
3. sql/clickhouse/security.sql, as a reference that the administrator of
   shrek2 runs (our user may lack the privilege ACCESS MANAGEMENT):
   - CREATE ROLE gNN_etl, gNN_analyst, gNN_dashboard;
   - GRANT INSERT ON lab.gNN_db_ingestion TO gNN_etl; GRANT SELECT on the
     gold views to gNN_analyst; GRANT SELECT on one aggregate to
     gNN_dashboard;
   - CREATE ROW POLICY gNN_by_region ON lab.gNN_<table> USING <condition>
     TO gNN_analyst, when the partner has a regional or business-unit cut;
   - a view lab.gNN_<entity>_pseudo with
     substring(hex(SHA256(concat(<pepper>, ':', toString(id)))), 1, 16)
     instead of the identifier, and generalised quasi-identifiers;
   - an aggregate lab.gNN_<entity>_segments with HAVING uniqExact(...) >= 5;
   - SHOW GRANTS FOR each role, as the check.
4. docs/audit.md: where ClickHouse already records who ran what
   (system.query_log: user, query_kind, tables, event_time) and the query
   that lists the reads of our personal tables in the last 7 days.

[E] Example
CREATE ROW POLICY g01_by_state ON lab.g01_fact_sales
  USING state = 'SP' TO g01_analyst;

[A] Adjustments
- The pepper never goes to the repository: it is an environment variable
  of the ETL or a setting of the server, as in the case of the exams of
  this portal.
- In ClickHouse, once a table has a row policy, the users that no policy
  covers see no row by default (unless the server enables
  users_without_row_policies_can_read_rows): check it as each role.
- A row policy filters reads only; whoever may INSERT is decided by GRANT.
- Every date is Unix time in seconds (Int64).
- Replace gNN with the number of the group; never grant or drop anything
  of another group.

[T] Type of output
The files and the statements we could run with our user, with their result.

[E] Extras
Show the plan before editing. Record this prompt in docs/prompts.md.
Stop after the inventory and the policy and wait for our review before
the SQL.

17. Reference numbers

MeasureValue
data3 stores, 60 customers, 400 orders; 25 columns; 5 customers with an accessibility need
inventory1 sensitive column, 7 personal columns dropped, 2 pseudonymised, 3 generalised
roles10 roles, all NOLOGIN; 3 people in store_manager
row level securitysp 162 orders (US$ 58,258.08), rj 128 (US$ 65,629.66), bh 110 (US$ 12,371.59); app_owner sees 0 customers
masking11 segments of store and age band; 7 published, 4 suppressed with 7 customers
audit3 events: READ by manager_sp, INSERT by etl_writer, UPDATE of the e-mail only
access test63 pairs, 63 passed; 2 failures after the careless grant; 0 after the REVOKE
replay100 statements replayed in order after a reload; the matrix stays at 63 of 63

18. Mistakes found in the rehearsal

The traps below appeared while the lab was rehearsed on 08/11/2026, and the prompts carry the corresponding adjustments.

A grant that grants nothing

The first version of the regression of step 06 granted SELECT on the customers to the analyst and expected a failure of the test, which did not come: without USAGE on the schema, the privilege on the table had no effect. The schema is a layer of its own, and the regression now grants both.

Who is the current user

An audit trigger written with current_user recorded postgres for every event, because a SECURITY DEFINER function runs as its owner. The acting role is read from current_setting('role'), with session_user as the fallback for a real login without SET ROLE.

The owner under FORCE

With FORCE ROW LEVEL SECURITY and no policy for app_owner, the owner of the tables cannot read nor insert a row. The expectation of the test for the owner's insert is therefore denied, not all, and a team that forces RLS needs a policy, or a separate role, for the maintenance it still has to do.

Superusers ignore every policy

The session of the lab is the superuser, which bypasses RLS even on a forced table. Every proof of a policy must run under SET ROLE, and the scripts end with RESET ROLE, so that the next step does not run as the last role used.

19. Glossary

TermMeaning in this lesson
personal datainformation about an identified or identifiable person (LGPD art. 5, I)
sensitive personal datapersonal data of the categories of art. 5, II, such as health
quasi-identifiera field that does not identify alone but does in combination with others
least privilegeeach job receives only the privileges its purpose needs
rolea PostgreSQL principal; a job when NOLOGIN, a person when it logs in
row level securitypolicies that decide which rows of a table a role sees or writes
SECURITY DEFINERa function that runs with the privileges of its owner
peppera secret mixed into a hash so that the hash cannot be reversed by enumeration
k-anonymitypublishing only groups with at least k distinct people
audit logan append-only record of who did what, when and why

20. Checklist

  • Every column has a category, a purpose, a legal basis and a retention.
  • Every privilege belongs to a job, and nothing is left to PUBLIC.
  • The tables with personal data have RLS enabled and forced.
  • No policy depends on a setting that the user can change.
  • The analytics layer has no direct identifier, and its keys use a secret.
  • The dashboard reads only groups with at least five people.
  • Every change and every read of contact data is in an append-only log without values.
  • The expected access is a table, and a test compares it with the database after every change.
  • No secret is in the repository.

21. References and self-study

  • BRASIL. Lei nยบ 13.709, de 14 de agosto de 2018: Lei Geral de Proteรงรฃo de Dados Pessoais (LGPD).
  • URM Consulting. GDPR - Back to Basics (self-study 1, 40 min).
  • GDPR & Data Security Fundamentals (self-study 2, video, 30 min).
  • Cloudian. Data Protection Principles: Core Principles of the GDPR (self-study 3, 40 min).
  • PostgreSQL Global Development Group. PostgreSQL 18 documentation: Database Roles; Privileges; Row Security Policies; CREATE FUNCTION (Writing SECURITY DEFINER Functions Safely). postgresql.org/docs.
  • ClickHouse. Access Control and Account Management; Row Policy; system.query_log. clickhouse.com/docs.
  • SWEENEY, L. k-anonymity: a model for protecting privacy. International Journal of Uncertainty, Fuzziness and Knowledge-Based Systems, v. 10, n. 5, p. 557-570, 2002.
  • ElectricSQL. PGlite: Postgres in WASM. pglite.dev.