Module 8 · Information Systems · Lesson 13 · Week 10

Instruction session · Thursday, December 17, 2026 · one hour of demonstration, one hour in groups

Data Security, Authorizations, and Access

The DataApp of a fictitious card shop keeps names, e-mails, CPFs and one health datum of its customers. In six steps, in a PostgreSQL that runs inside the browser, the data is classified under the LGPD, divided among roles of least privilege, filtered by row, pseudonymised for the analysts, audited, and finally tested as a matrix of who may do what.

LGPDData inventoryRoles and GRANTRow level securityPseudonymisationAudit logAccess tests

Project ritual

Daily · 15 minutes

Each group reports the progress of its deliverables, the work planned for this session and the blockers that require a decision.

15:00
What I didWhat I will doBlockersProgress
Agenda · two hours
One hour securing the shop, one hour securing your DataApp

In the first hour the professor applies six controls to the card shop, live, with a coding agent and the lab of the browser. In the second hour each group applies the same controls to the partner data in the ClickHouse of the class.

0:15 · conceptsLGPD and governanceProfessorPersonal and sensitive data; principles; roles and duties
0:20 · step 01ClassifyAgent: gov.data_catalogInventory of every column, purpose and retention
0:26 · step 02RolesAgent: CREATE ROLE, GRANTOne role per job; least privilege
0:32 · step 03Row level securityAgent: CREATE POLICYEach manager sees only the own store
0:39 · step 04MaskingAgent: analytics.*Pepper, generalisation and k = 5
0:46 · step 05Audit logAgent: audit.eventsWho changed or read what, and why
0:53 · step 06Access testsAgent: gov.access_test()The policy as an automated test
1:00 · groupsYour DataAppEach groupInventory, roles, row policies and pseudonyms on shrek2
0:15 · The law
What the LGPD protects and what it asks of a DataApp

The Lei Geral de Proteção de Dados (Law 13,709/2018) applies to every operation on personal data done in Brazil or about people in Brazil. A DataApp that collects, stores, combines or publishes such data is processing it, and its team answers for how.

ConceptArticleIn the card shop
personal data: identifies a person or makes the person identifiableart. 5, Iname, e-mail, CPF, phone, birth date, the customer id
sensitive personal data: health, religion, ethnicity, biometrics and othersart. 5, IIthe accessibility need of 5 customers
anonymised data: can no longer be linked to a person by reasonable meansart. 5, III; art. 12sales by store and age band, with at least 5 customers per group
principles: purpose, necessity, security, prevention, accountabilityart. 6each column with a purpose; analytics without what it does not need
legal bases: consent, legal obligation, contract, legitimate interestart. 7; art. 11the CPF by legal obligation; the health datum only with specific consent
security measures and a record of the operationsarts. 37 and 46roles, row policies, an audit log
Who answersThe controller decides why and how data is processed, the operator processes on its behalf, and the encarregado (art. 41) is the channel between the controller, the people and the ANPD, the national authority, which may fine up to 2 % of the revenue in Brazil, limited to R$ 50 million per infraction (art. 52).
0:17 · Governance
Every job of the DataApp becomes a role of the database

Data governance assigns to each person a job with duties over the data. The database enforces those duties only when each job is a role with its own privileges, and the six steps of the lab build that correspondence.

Job in governanceRole in the labMayMay not
custodian of the platformapp_ownerown the tables and change their structureread a row without a policy (FORCE)
the ETL of the DataAppetl_writerinsert customers and ordersread what it wrote
data steward of a storemanager_sp, _rj, _bhread the own store; look up a contact with a purposesee another store
analystanalystread 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
Defence in depthEach step adds a layer that works even when the previous one fails: the privilege of the table, the policy of the row, the masking of the column, the record of the access and the test that catches a careless change. Step 06 shows a GRANT that breaks the first layer while the second still holds.
0:19 · The lab
PostgreSQL inside the browser, with SET ROLE for each job

The lab runs PostgreSQL 18 compiled to WebAssembly (PGlite 0.5.10). The session is the superuser postgres, and SET ROLE plays each role, so every grant and policy can be proven by switching role and running the same query.

TableRowsPersonal data
shop.stores3none
shop.customers60name, e-mail, CPF, phone, birth date, city, accessibility need, consent
shop.orders400the customer, the moment and the last 4 digits of the card
Synthetic peopleThe surnames are Exemplo, Teste or Fictício, the e-mails use example.com and every CPF starts with 000. Card names and prices come from the TCGplayer capture of Lesson 6.
What survives a reloadEvery statement that changes the database, SET ROLE included, is kept in the localStorage and replayed in order. The access matrix at the bottom of the page runs the test of step 06.

Step 01 · 0:20 · Classify

An inventory of every column before any access

A column without a category, a purpose, a legal basis and a retention has no reason to be kept. The inventory is a table of the database, so that the next steps and the tests can read it.

Writes

gov.data_catalog with one row per column of shop, two tests of completeness and a summary by category.

Review before moving on
  • Do both tests return no rows?
  • Is accessibility_need sensitive, with consent as its basis?
  • Does every direct identifier leave the analytics layer?
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.
Step 01 · Result
Twenty-five columns, and what reaches the analysts

The principle of necessity (art. 6, III) turns the inventory into a decision per column: keep it, pseudonymise it, generalise it or drop it from the analytics layer. Step 04 implements exactly these decisions.

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
Identifiers and quasi-identifiersA direct identifier points at one person alone. A quasi-identifier does not, but a few together do: birth date, city and store narrow 60 customers down to one or two. That is why they are generalised and not kept as they are.

Step 02 · 0:26 · Roles

One role per job, and nothing for PUBLIC

Least privilege gives each job only what its purpose needs. People change and jobs stay, so privileges are granted to jobs, and a person receives a job by membership.

Writes

Ten roles, the tables owned by app_owner, the REVOKE from PUBLIC, the schemas analytics and audit, the grants and the privilege matrix.

Review before moving on
  • Is every role NOLOGIN, with the people as members of store_manager?
  • Does the ETL insert customers without being able to select them?
  • Does any table of shop keep a privilege of PUBLIC?
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.
Step 02 · Theory
GRANT decides which tables a job reaches

PostgreSQL checks the privilege of the schema first and of the table after it, and a new function is executable by PUBLIC by default. A grant left to PUBLIC is a grant to every user, present and future.

Jobs, not people

Group roles

CREATE ROLE manager_sp NOLOGIN IN ROLE store_manager: the privileges belong to store_manager, and replacing a manager is one membership, not a review of every grant.

The ETL is blind

Write without read

The ETL inserts customers and orders but cannot select them. A leaked password of the ETL then exposes no customer, which is the point of least privilege.

Future objects

Default privileges

ALTER DEFAULT PRIVILEGES FOR ROLE analytics_owner IN SCHEMA analytics GRANT SELECT ON TABLES TO analyst: every view created later is readable by the analysts, without a forgotten grant.

Roleshop.customersshop.ordersgov.data_catalog
etl_writerinsertinsertnone
manager_spselectselectnone
analyst, dashboardnonenonenone
dpononenoneselect

Step 03 · 0:32 · Row level security

Each manager sees only the rows of the own store

GRANT gave the managers the table of customers; a policy now decides which rows of it each one sees. The rule lives in the database, so it holds for every client: the lab, a notebook or a dashboard.

Writes

gov.store_staff, gov.actor(), gov.my_stores(), RLS enabled and forced on customers and orders, the policies and the proof with three roles.

Review before moving on
  • Does manager_sp see 162 orders and manager_rj 128?
  • Does app_owner, the owner of the table, see no customer?
  • Is the policy over a function, not over a setting the user can change?
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.
Step 03 · Result
The same query, three roles, three answers

With RLS on, a row is visible only when some policy of the role is true for it. The superuser and the roles with BYPASSRLS ignore policies, and FORCE makes even the owner of the table obey them.

Acting asStores seenOrdersRevenue, US$
manager_spsp16258,258.08
manager_rjrj12865,629.66
postgres (superuser)sp, rj, bh400136,259.33
app_owner (owner, FORCE)none0—
the policy
CREATE POLICY manager_reads_own_store
  ON shop.orders
  FOR SELECT TO store_manager
  USING (store_id IN
         (SELECT gov.my_stores()));
An anti-patternA policy over a setting, USING (store_id = current_setting('app.store_id')), is defeated by SET app.store_id = 'rj'. It is safe only when the application is the sole client and the users never write SQL; the lab reads the acting role instead, which a user cannot forge.

Step 04 · 0:39 · Masking

The analysts see behaviour, never the person

The analytics layer receives a key instead of the customer, an age band instead of the birth date and the day instead of the moment. The dashboard receives only groups with at least five customers.

Writes

gov.pepper, the views analytics.customers_pseudo, orders_pseudo and sales_by_segment, owned by analytics_owner.

Review before moving on
  • Does the analyst read the views with no grant on shop?
  • Is the key a hash with a secret, not a hash of the id alone?
  • Are 7 segments published and 4 suppressed by k = 5?
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.
Step 04 · Theory
Pseudonymised is still personal; anonymised is not

The LGPD draws the line by the possibility of linking the data back to the person. A key that a secret can reverse is pseudonymisation (art. 13, §4) and the law still applies; an aggregate that no reasonable means links to a person is anonymised (art. 12).

Pseudonymise

A peppered key

sha256(pepper || ':' || customer_id), cut to 16 hex characters. Without the pepper, a hash of the id alone is reversed by computing the hash of the 60 possible ids.

Generalise

Fewer details

The birth date becomes 18-24, 25-34, 35-49 or 50+; the moment of the order becomes its day, ordered_unix / 86400 * 86400; the e-mail becomes a***@example.com.

Aggregate

k-anonymity, k = 5

A store and age band with fewer than five customers is not published. Of 11 segments, 7 are published and 4 are suppressed, with 7 customers in them.

Where the pepper livesIn the lab it is a table that only analytics_owner reads. In production it is a secret of the server or an environment variable outside the repository, because whoever holds the pepper and the keys can reverse every pseudonym.

Step 05 · 0:46 · Audit log

Who changed or read what, when and why

The LGPD asks the controller to record its operations on personal data (art. 37). Changes are caught by a trigger; reads of contact data, which no trigger sees, happen only through a function that demands a purpose.

Writes

audit.events (append-only), the trigger audit.log_change(), the function shop.lookup_customer(id, purpose) and three events read by the DPO.

Review before moving on
  • Does the log keep the names of the changed columns and never their values?
  • Is an UPDATE or DELETE of the log refused, even for the owner?
  • Does lookup refuse a customer of another store?
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.
Step 05 · Result
Three events, read by the DPO

The actor is the role that was acting, read inside the SECURITY DEFINER function from current_setting('role'), because there current_user is the owner of the function and would hide who called 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 log is not a copy

Writing the old and new values would make the log a second store of e-mails and CPFs, with its own retention and its own leaks. It keeps the key of the row and the names of the columns.

Append-only

A trigger refuses every UPDATE and DELETE of audit.events, the owner included. The superuser could drop the trigger, and that DDL is itself an event to watch.

Case study
How this portal keeps the exams away from the class

The repository of these lessons is public, so any exam written in it would be readable days before the class. The statement lives in the PostgreSQL of the course, behind PostgREST, with the same controls of the lab.

Deny by default

RLS with no policy

The tables of the exam have RLS enabled and no policy at all, plus REVOKE ALL from the public roles of the API. No call reads a row of them directly.

One door

prova_abrir(slug, token)

A SECURITY DEFINER function with a fixed search_path compares the SHA-256 of the token typed by the professor with the hash it keeps. The token in clear exists in no table, no file and no page.

Every attempt logged

Refusal as data

Each attempt, right or wrong, is a row of a log. A refusal returns {"ok": false} instead of raising an error, because an error rolls back the transaction and the record of the attempt with it.

Secrets outside

Nothing in git

The SQL that loads each exam sits in a folder that git ignores, and the database password in the environment file of the infrastructure. After eight wrong tokens in five minutes the function refuses, but never the right token.

Back to step 05shop.lookup_customer raises an error when it refuses, so a refused lookup leaves no event. Making refusals visible to the DPO is the exercise the case suggests.

Step 06 · 0:53 · Access tests

The policy written as a test

A policy that nobody tests drifts with the next GRANT. The expected access of each role is a table, written from the policy before the first run, and a function runs every probe as every role and compares.

Writes

gov.probes, gov.try_as(role, sql), gov.expected_access, gov.access_test(), the verdict, the matrix and a regression on purpose.

Review before moving on
  • Does every probe run inside a subtransaction that is rolled back?
  • Were the expectations written from the policy, not copied from a first run?
  • 63 of 63 pairs; 2 failures after the careless GRANT; 0 after the REVOKE?
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.
Step 06 · Result
Sixty-three pairs, and the GRANT that breaks two

Each probe runs first as the superuser and then as the role, inside a subtransaction that always rolls back. Its outcome is denied (an error), none (zero rows), some (fewer rows than the superuser) or all.

Roleread customersread ordersinsert customerlookup contactread pseudonymsread segmentsread audit log
etl_writerdenieddeniedalldenieddenieddenieddenied
manager_spsomesomedeniedalldenieddenieddenied
manager_rjsomesomedenieddenieddenieddenieddenied
analystdenieddenieddenieddeniedallalldenied
dashboarddenieddenieddenieddenieddeniedalldenied
dpodenieddenieddenieddenieddenieddeniedall
app_ownernonenonedenieddenieddenieddenieddenied
The regressionAfter GRANT USAGE ON SCHEMA shop and GRANT SELECT ON ALL TABLES IN SCHEMA shop TO analyst, the analyst reads customers and orders as none instead of denied: RLS still hid every row, but the test fails twice, because the policy demands that the first layer holds too.
1:00 · Second hour · groups
The same six controls on the DataApp of the group

Each group applies the controls to the partner data in the ClickHouse of the class (shrek2), database lab, objects gNN_, with prompt 07 of the lab.

Deliver in the repository of the group
  • docs/data_inventory.md: every field classified, with the analytics decision
  • docs/access_policy.md: the jobs and their expected access
  • sql/clickhouse/security.sql: roles, grants, row policies, a pseudonymised view and an aggregate with k = 5
  • docs/audit.md: the reads of the personal tables in system.query_log
ClickHouse, in short
CREATE ROLE g01_analyst;
GRANT SELECT ON lab.g01_fact_sales
  TO g01_analyst;
CREATE ROW POLICY g01_by_state
  ON lab.g01_fact_sales
  USING state = 'SP' TO g01_analyst;
SHOW GRANTS FOR g01_analyst;

The user of the group may lack ACCESS MANAGEMENT: the access statements are a reference that the administrator runs.

Closing the module
What a DataApp needs besides the data

Module 8 built one DataApp over the prices of TCGplayer: a model, a package, a scheduler, tests, metrics, infographics and a cost. This last lesson adds the condition for any of it to reach real people's data.

ControlQuestion it answersWhere in the lab
inventorywhat personal data do we keep, why, and for how long?gov.data_catalog
roles and grantswhich job reaches which table?CREATE ROLE, GRANT, REVOKE ... FROM PUBLIC
row policieswhich rows of the table does each job see?CREATE POLICY, FORCE ROW LEVEL SECURITY
maskingwhat does analysis need of each person?analytics.*, pepper, k = 5
auditwho touched which person's data, and why?audit.events, shop.lookup_customer
testsdoes the policy still hold after the last change?gov.access_test()
Self-study
Self-study for this session

Readings and a video assigned on Adalove, on the principles of data protection that the GDPR and the LGPD share, with the reading material of the session.

Self-study 1

GDPR - Back to Basics

Core GDPR principles, from lawful processing and minimisation to integrity and accountability.

urmconsulting.com· 40 min

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)