Snowflake SQL Tutorial 165 - I Wrote The Masking Policy Myself And Snowflake Still Hid My Data From Me

Snowflake SQL · Episode 165

In this post we are going to cover masking policies in Snowflake.

A masking policy is a named object with a body. The body takes the column value and returns whatever you want the reader to see instead. You then attach the policy to a column, and from that moment every query against that column goes through the body.

We will start with the smallest policy there is and build it up step by step. Along the way we will run exactly the same SELECT as three different roles and get three different answers, and one of those three is the owner of the table and of the policy.

Every person, email address and card number below is invented. The card numbers come from the 4111 test range, so none of them belongs to anybody.

Episode 165 of the Snowflake SQL: Zero to Hero series on TechBrothersIT.

Let's create some sample data

We need a table with something in it worth hiding. The script below makes a schema for this post, a table of six invented people, and puts a name, an email, a card number, a salary and a city on each of them.

Sample data
-- Sample data for this post. Everything here is invented.
-- The card numbers are from the 4111 test range, so none of them is anybody's.
USE DATABASE DEMO_DB;

CREATE OR REPLACE SCHEMA DEMO_DB.MASK_T165
  COMMENT = 'episode 165 - masking policies, dropped at the end';

USE SCHEMA DEMO_DB.MASK_T165;

CREATE OR REPLACE TABLE DEMO_DB.MASK_T165.PEOPLE_T165 (
  PERSON_ID   NUMBER,
  FULL_NAME   VARCHAR(60),
  EMAIL       VARCHAR(80),
  CARD_NUMBER VARCHAR(25),
  SALARY      NUMBER(10,2),
  CITY        VARCHAR(40)
);

INSERT INTO DEMO_DB.MASK_T165.PEOPLE_T165
  (PERSON_ID, FULL_NAME, EMAIL, CARD_NUMBER, SALARY, CITY)
VALUES
  (1, 'Ayesha Khan',   'ayesha@example.com', '4111-1111-1111-1111', 92000.00, 'Karachi'),
  (2, 'Bilal Ahmed',   'bilal@example.com',  '4111-1111-1111-2222', 78500.00, 'Lahore'),
  (3, 'Clara Fernand', 'clara@example.com',  '4111-1111-1111-3333', 61000.00, 'Toronto'),
  (4, 'Danish Iqbal',  'danish@example.com', '4111-1111-1111-4444', 115000.00,'Dubai'),
  (5, 'Esha Malik',    'esha@example.com',   '4111-1111-1111-5555', 54000.00, 'Karachi'),
  (6, 'Farid Noor',    'farid@example.com',  '4111-1111-1111-6666', 88000.00, 'Lahore');

Let's look at what we just created.

Query
SELECT * FROM DEMO_DB.MASK_T165.PEOPLE_T165 ORDER BY PERSON_ID;
Result6 rows · 6 columns · scroll →
PERSON_IDFULL_NAMEEMAILCARD_NUMBERSALARYCITY
1Ayesha Khanayesha@example.com4111-1111-1111-111192000.00Karachi
2Bilal Ahmedbilal@example.com4111-1111-1111-222278500.00Lahore
3Clara Fernandclara@example.com4111-1111-1111-333361000.00Toronto
4Danish Iqbaldanish@example.com4111-1111-1111-4444115000.00Dubai
5Esha Malikesha@example.com4111-1111-1111-555554000.00Karachi
6Farid Noorfarid@example.com4111-1111-1111-666688000.00Lahore

Six rows and six columns, all of it readable. Hold on to this grid, because we are going to run this same SELECT several more times.

And one control before we go any further

This whole post is about two roles getting two different answers. That only works if USE ROLE really changes what the session can do, so the secondary roles have to be switched off first.

Query
USE SECONDARY ROLES NONE;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
ACCOUNTADMIN{"roles":"","value":""}

The secondary roles cell is empty, and this was run before a single policy existed. Without that, every comparison below would have been one role against itself and the policy would have looked like it did nothing.

And here is the account before we start, so we know everything we see later is ours.

Query
SHOW MASKING POLICIES IN ACCOUNT;
Result0 rows · 9 columns · scroll →
created_onnamedatabase_nameschema_namekindownercommentowner_role_typeoptions
Query
SELECT COUNT(*) AS POLICIES_ALREADY_HERE
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 1 column
POLICIES_ALREADY_HERE
0

Let's start with the smallest masking policy there is

The smallest policy takes one argument, returns one type, and ignores the argument completely.

Query
CREATE OR REPLACE MASKING POLICY DEMO_DB.MASK_T165.MASK_FULL_T165
  AS (VAL VARCHAR) RETURNS VARCHAR ->
  '*** MASKED ***';
Result1 row · 1 column
status
Masking policy MASK_FULL_T165 successfully created.

Created. It is an object in a schema like any other, so SHOW finds it.

Query
SELECT "name", "kind", "database_name", "schema_name", "owner", "comment"
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 6 columns · scroll →
namekinddatabase_nameschema_nameownercomment
MASK_FULL_T165MASKING_POLICYDEMO_DBMASK_T165ACCOUNTADMIN

Now let's ask DESCRIBE, which is where the interesting part is.

Query
DESCRIBE MASKING POLICY DEMO_DB.MASK_T165.MASK_FULL_T165;
Result1 row · 4 columns
namesignaturereturn_typebody
MASK_FULL_T165(VAL VARCHAR)VARCHAR'*** MASKED ***'

A signature, a return type and a body. That is the whole object. The body is the string it will hand back.

And GET_DDL gives us the same thing as a statement we could run again.

Query
SELECT GET_DDL('POLICY', 'DEMO_DB.MASK_T165.MASK_FULL_T165') AS THE_DDL;
Result1 row · 1 column
THE_DDL
create or replace masking policy MASK_FULL_T165 as (VAL VARCHAR) returns VARCHAR -> '*** MASKED ***' ;

Nothing has happened to our table yet. A policy that is not attached to anything does nothing at all.

Now let's attach it to a column

A policy is attached with ALTER TABLE ... MODIFY COLUMN. Let's put it on the card number.

Query
ALTER TABLE DEMO_DB.MASK_T165.PEOPLE_T165
  MODIFY COLUMN CARD_NUMBER SET MASKING POLICY DEMO_DB.MASK_T165.MASK_FULL_T165;
Result1 row · 1 column
status
Statement executed successfully.

Now let's run exactly the same SELECT we ran in the first section, as exactly the same role.

Query
SELECT * FROM DEMO_DB.MASK_T165.PEOPLE_T165 ORDER BY PERSON_ID;
Result6 rows · 6 columns · scroll →
PERSON_IDFULL_NAMEEMAILCARD_NUMBERSALARYCITY
1Ayesha Khanayesha@example.com*** MASKED ***92000.00Karachi
2Bilal Ahmedbilal@example.com*** MASKED ***78500.00Lahore
3Clara Fernandclara@example.com*** MASKED ***61000.00Toronto
4Danish Iqbaldanish@example.com*** MASKED ***115000.00Dubai
5Esha Malikesha@example.com*** MASKED ***54000.00Karachi
6Farid Noorfarid@example.com*** MASKED ***88000.00Lahore

Masked. We did not change the table and we did not change our role. The only thing that changed is that a policy is now attached to one column, and the answer is different.

Query
SELECT PERSON_ID, FULL_NAME, CARD_NUMBER
  FROM DEMO_DB.MASK_T165.PEOPLE_T165
 ORDER BY PERSON_ID;
Result6 rows · 3 columns
PERSON_IDFULL_NAMECARD_NUMBER
1Ayesha Khan*** MASKED ***
2Bilal Ahmed*** MASKED ***
3Clara Fernand*** MASKED ***
4Danish Iqbal*** MASKED ***
5Esha Malik*** MASKED ***
6Farid Noor*** MASKED ***

So where would you find that out?

DESCRIBE TABLE has grown a column.

Query
DESCRIBE TABLE DEMO_DB.MASK_T165.PEOPLE_T165;
Result6 rows · 13 columns · scroll →
The policy name column is the eleventh one — scroll right
nametypekindnull?defaultprimary keyunique keycheckexpressioncommentpolicy nameprivacy domainwrite default
PERSON_IDNUMBER(38,0)COLUMNYNULLNNNULLNULLNULLNULLNULLNULL
FULL_NAMEVARCHAR(60)COLUMNYNULLNNNULLNULLNULLNULLNULLNULL
EMAILVARCHAR(80)COLUMNYNULLNNNULLNULLNULLNULLNULLNULL
CARD_NUMBERVARCHAR(25)COLUMNYNULLNNNULLNULLNULLDEMO_DB.MASK_T165.MASK_FULL_T165NULLNULL
SALARYNUMBER(10,2)COLUMNYNULLNNNULLNULLNULLNULLNULLNULL
CITYVARCHAR(40)COLUMNYNULLNNNULLNULLNULLNULLNULLNULL

That grid is wide, so here are the two rows that matter with four of the columns.

Query
SELECT "name", "type", "null?", "policy name"
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
 WHERE "name" IN ('CARD_NUMBER', 'FULL_NAME');
Result2 rows · 4 columns
nametypenull?policy name
FULL_NAMEVARCHAR(60)YNULL
CARD_NUMBERVARCHAR(25)YDEMO_DB.MASK_T165.MASK_FULL_T165

The full name of the policy beside CARD_NUMBER and a real NULL beside the column that has no policy on it.

And POLICY_REFERENCES answers the same question from the policy's side.

Query
SELECT POLICY_NAME, REF_ENTITY_NAME, REF_ENTITY_DOMAIN, REF_COLUMN_NAME,
       POLICY_STATUS
  FROM TABLE(DEMO_DB.INFORMATION_SCHEMA.POLICY_REFERENCES(
         POLICY_NAME => 'DEMO_DB.MASK_T165.MASK_FULL_T165'));
Result1 row · 5 columns
POLICY_NAMEREF_ENTITY_NAMEREF_ENTITY_DOMAINREF_COLUMN_NAMEPOLICY_STATUS
MASK_FULL_T165PEOPLE_T165TABLECARD_NUMBERACTIVE

Then from the table's side, and the two agree.

Query
SELECT POLICY_NAME, POLICY_KIND, REF_COLUMN_NAME, POLICY_STATUS
  FROM TABLE(DEMO_DB.INFORMATION_SCHEMA.POLICY_REFERENCES(
         REF_ENTITY_NAME   => 'DEMO_DB.MASK_T165.PEOPLE_T165',
         REF_ENTITY_DOMAIN => 'TABLE'));
Result1 row · 4 columns
POLICY_NAMEPOLICY_KINDREF_COLUMN_NAMEPOLICY_STATUS
MASK_FULL_T165MASKING_POLICYCARD_NUMBERACTIVE

Now let's write a policy that treats two roles differently

A body can be a CASE expression, and it can ask who is running the query. Let's make two roles first.

Two roles
-- Two roles, and both of them handed to me so I can wear each in turn.
-- The GRANT ROLE lines name a user; YOUR_USER_NAME stands in for mine.
CREATE OR REPLACE ROLE RSEE_T165
  COMMENT = 'episode 165 - the role the policy will exempt';
CREATE OR REPLACE ROLE RHIDE_T165
  COMMENT = 'episode 165 - the role the policy will mask for';

GRANT USAGE ON DATABASE DEMO_DB            TO ROLE RSEE_T165;
GRANT USAGE ON DATABASE DEMO_DB            TO ROLE RHIDE_T165;
GRANT USAGE ON WAREHOUSE COMPUTE_WH        TO ROLE RSEE_T165;
GRANT USAGE ON WAREHOUSE COMPUTE_WH        TO ROLE RHIDE_T165;
GRANT USAGE ON SCHEMA DEMO_DB.MASK_T165    TO ROLE RSEE_T165;
GRANT USAGE ON SCHEMA DEMO_DB.MASK_T165    TO ROLE RHIDE_T165;
GRANT SELECT ON TABLE DEMO_DB.MASK_T165.PEOPLE_T165 TO ROLE RSEE_T165;
GRANT SELECT ON TABLE DEMO_DB.MASK_T165.PEOPLE_T165 TO ROLE RHIDE_T165;

GRANT ROLE RSEE_T165  TO USER YOUR_USER_NAME;
GRANT ROLE RHIDE_T165 TO USER YOUR_USER_NAME;

Now a policy whose body names one of those roles and nobody else.

Query
CREATE OR REPLACE MASKING POLICY DEMO_DB.MASK_T165.MASK_COND_T165
  AS (VAL VARCHAR) RETURNS VARCHAR ->
  CASE
    WHEN CURRENT_ROLE() = 'RSEE_T165' THEN VAL
    ELSE '**** **** **** ' || RIGHT(VAL, 4)
  END;
Result1 row · 1 column
status
Masking policy MASK_COND_T165 successfully created.

Read that body carefully. If the current role is RSEE_T165 it hands back the value. Otherwise it hands back stars and the last four digits.

Let's swap the column onto this policy. A column holds one policy, so the old one comes off first.

Query
ALTER TABLE DEMO_DB.MASK_T165.PEOPLE_T165
  MODIFY COLUMN CARD_NUMBER UNSET MASKING POLICY;
Result1 row · 1 column
status
Statement executed successfully.
Query
ALTER TABLE DEMO_DB.MASK_T165.PEOPLE_T165
  MODIFY COLUMN CARD_NUMBER SET MASKING POLICY DEMO_DB.MASK_T165.MASK_COND_T165;
Result1 row · 1 column
status
Statement executed successfully.

The owner first

Let's run the select as ACCOUNTADMIN, which owns the table and owns the policy.

Query
SELECT PERSON_ID, FULL_NAME, CARD_NUMBER
  FROM DEMO_DB.MASK_T165.PEOPLE_T165
 ORDER BY PERSON_ID;
Result6 rows · 3 columns
PERSON_IDFULL_NAMECARD_NUMBER
1Ayesha Khan**** **** **** 1111
2Bilal Ahmed**** **** **** 2222
3Clara Fernand**** **** **** 3333
4Danish Iqbal**** **** **** 4444
5Esha Malik**** **** **** 5555
6Farid Noor**** **** **** 6666

Stars. We will come back to that in a moment, because it is the grid this whole post is built on.

Now the role the body names

Query
USE ROLE RSEE_T165;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT PERSON_ID, FULL_NAME, CARD_NUMBER
  FROM DEMO_DB.MASK_T165.PEOPLE_T165
 ORDER BY PERSON_ID;
Result6 rows · 3 columns
PERSON_IDFULL_NAMECARD_NUMBER
1Ayesha Khan4111-1111-1111-1111
2Bilal Ahmed4111-1111-1111-2222
3Clara Fernand4111-1111-1111-3333
4Danish Iqbal4111-1111-1111-4444
5Esha Malik4111-1111-1111-5555
6Farid Noor4111-1111-1111-6666

The real digits. Same table, same statement, different role.

And now the role it does not name

Query
USE ROLE RHIDE_T165;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT PERSON_ID, FULL_NAME, CARD_NUMBER
  FROM DEMO_DB.MASK_T165.PEOPLE_T165
 ORDER BY PERSON_ID;
Result6 rows · 3 columns
PERSON_IDFULL_NAMECARD_NUMBER
1Ayesha Khan**** **** **** 1111
2Bilal Ahmed**** **** **** 2222
3Clara Fernand**** **** **** 3333
4Danish Iqbal**** **** **** 4444
5Esha Malik**** **** **** 5555
6Farid Noor**** **** **** 6666

Stars and the last four digits, which is exactly what the body was written to do.

Query
USE ROLE ACCOUNTADMIN;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CURRENT_ROLE() AS THE_ROLE;
Result1 row · 1 column
THE_ROLE
ACCOUNTADMIN

So why could the owner not see the real values?

Look at those three grids side by side. The exempt role saw the real card numbers. The other role saw stars. And the owner of the table, the owner of the policy, the person who typed that CASE expression, also saw stars.

The reason is in one sentence, and it is the sentence worth taking away from this post. A masking policy is attached to a column. It is not granted to a role.

There is nothing to own your way past. The body names RSEE_T165 and nobody else, so every other role in the account, including the one that created the policy, falls into the ELSE branch.

Worth knowing before you attach one

You can hide your own data from yourself, and nothing in the ALTER TABLE statement hints that you have just done it. If you want the owner to be able to read the column, the owner's role has to be in the body.

Now let's see what the mask does to a query

So far we have looked at grids. A mask also changes what a query means, and this is the part that catches people out.

Let's filter on a real card number, one we can read in the sample data at the top of this post.

Query
USE ROLE RHIDE_T165;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT COUNT(*) AS MATCHED
  FROM DEMO_DB.MASK_T165.PEOPLE_T165
 WHERE CARD_NUMBER = '4111-1111-1111-4444';
Result1 row · 1 column
MATCHED
0

Nought. That value is in the table and the filter did not find it.

Now let's filter on the mask instead.

Query
SELECT COUNT(*) AS MATCHED_THE_MASK
  FROM DEMO_DB.MASK_T165.PEOPLE_T165
 WHERE CARD_NUMBER LIKE '**** **** ****%';
Result1 row · 1 column
MATCHED_THE_MASK
6

All six rows. So the predicate is being compared against what the policy returned, not against what is stored.

Where the mask happens

The mask is applied before the WHERE clause. A WHERE clause is not a way round a masking policy, and it is not a way to confirm a value either. Note that the statement above matches the shape of the mask with LIKE, because the mask keeps the last four digits and so all six masked values still differ from each other.

The owner gets the same answer on the first of those two filters, for the same reason as the last section.

Query
SELECT COUNT(*) AS MATCHED
  FROM DEMO_DB.MASK_T165.PEOPLE_T165
 WHERE CARD_NUMBER = '4111-1111-1111-4444';
Result1 row · 1 column
MATCHED
0

And GROUP BY does the same thing

The demo went back to ACCOUNTADMIN between those two tests, so let's put the restricted role back on before grouping.

Query
USE ROLE RHIDE_T165;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT CARD_NUMBER, COUNT(*) AS HOW_MANY
  FROM DEMO_DB.MASK_T165.PEOPLE_T165
 GROUP BY CARD_NUMBER
 ORDER BY CARD_NUMBER;
Result6 rows · 2 columns
CARD_NUMBERHOW_MANY
**** **** **** 11111
**** **** **** 22221
**** **** **** 33331
**** **** **** 44441
**** **** **** 55551
**** **** **** 66661

Six groups of one, and every group label is a masked string. Grouping groups what the policy returned, the same way filtering filters it.

Now let's mask three columns at once

A mask does not have to be stars. Let's write one that keeps the domain of an email address and hides the rest.

Query
CREATE OR REPLACE MASKING POLICY DEMO_DB.MASK_T165.MASK_PART_T165
  AS (VAL VARCHAR) RETURNS VARCHAR ->
  CASE
    WHEN CURRENT_ROLE() = 'RSEE_T165' THEN VAL
    ELSE '*****' || SUBSTR(VAL, POSITION('@' IN VAL))
  END;
Result1 row · 1 column
status
Masking policy MASK_PART_T165 successfully created.
Query
ALTER TABLE DEMO_DB.MASK_T165.PEOPLE_T165
  MODIFY COLUMN EMAIL SET MASKING POLICY DEMO_DB.MASK_T165.MASK_PART_T165;
Result1 row · 1 column
status
Statement executed successfully.

And one for a number column, where the signature and the return type are both numbers.

Query
CREATE OR REPLACE MASKING POLICY DEMO_DB.MASK_T165.MASK_NUM_T165
  AS (VAL NUMBER(10,2)) RETURNS NUMBER(10,2) ->
  CASE
    WHEN CURRENT_ROLE() = 'RSEE_T165' THEN VAL
    ELSE 0
  END;
Result1 row · 1 column
status
Masking policy MASK_NUM_T165 successfully created.
Query
ALTER TABLE DEMO_DB.MASK_T165.PEOPLE_T165
  MODIFY COLUMN SALARY SET MASKING POLICY DEMO_DB.MASK_T165.MASK_NUM_T165;
Result1 row · 1 column
status
Statement executed successfully.

Now the same SELECT * as the restricted role, with three policies on three columns.

Query
USE ROLE RHIDE_T165;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT * FROM DEMO_DB.MASK_T165.PEOPLE_T165 ORDER BY PERSON_ID;
Result6 rows · 6 columns · scroll →
PERSON_IDFULL_NAMEEMAILCARD_NUMBERSALARYCITY
1Ayesha Khan*****@example.com**** **** **** 11110.00Karachi
2Bilal Ahmed*****@example.com**** **** **** 22220.00Lahore
3Clara Fernand*****@example.com**** **** **** 33330.00Toronto
4Danish Iqbal*****@example.com**** **** **** 44440.00Dubai
5Esha Malik*****@example.com**** **** **** 55550.00Karachi
6Farid Noor*****@example.com**** **** **** 66660.00Lahore

Three shapes of answer in one grid. The email keeps its domain, the card number keeps its last four digits, and because SALARY is a number the mask is a number too.

And the arithmetic still works. It just works on the masked value.

Query
SELECT PERSON_ID, SALARY, SALARY * 12 AS ANNUAL
  FROM DEMO_DB.MASK_T165.PEOPLE_T165
 ORDER BY PERSON_ID;
Result6 rows · 3 columns
PERSON_IDSALARYANNUAL
10.000.00
20.000.00
30.000.00
40.000.00
50.000.00
60.000.00

A control of mine that proves nothing

I wrote a total for the restricted role, and then the same total as the owner so there would be something to compare it with. Here is the restricted role's total.

Query
SELECT SUM(SALARY) AS TOTAL_SALARY, AVG(SALARY) AS AVERAGE_SALARY
  FROM DEMO_DB.MASK_T165.PEOPLE_T165;
Result1 row · 2 columns
TOTAL_SALARYAVERAGE_SALARY
0.000.00000000

And here is the one that was supposed to be the real number.

Query
SELECT SUM(SALARY) AS TOTAL_SALARY, AVG(SALARY) AS AVERAGE_SALARY
  FROM DEMO_DB.MASK_T165.PEOPLE_T165;
Result1 row · 2 columns
TOTAL_SALARYAVERAGE_SALARY
0.000.00000000

The same. By then the numeric policy applied to the owner as well, so the control grid is identical to the thing it was controlling for. Two zeroes agreeing about nothing. I would rather say that out loud than let the pair of them read as confirmation.

What happens when we copy a masked table?

This is the one I would most want somebody to know before they run it. Let's copy the table with CREATE TABLE AS SELECT, as the owner.

Query
CREATE OR REPLACE TABLE DEMO_DB.MASK_T165.COPIED_BY_OWNER_T165 AS
SELECT PERSON_ID, FULL_NAME, CARD_NUMBER
  FROM DEMO_DB.MASK_T165.PEOPLE_T165;
Result1 row · 1 column
status
Table COPIED_BY_OWNER_T165 successfully created.

successfully created, with no warning of any kind. And here is what landed in it.

Query
SELECT * FROM DEMO_DB.MASK_T165.COPIED_BY_OWNER_T165 ORDER BY PERSON_ID;
Result6 rows · 3 columns
PERSON_IDFULL_NAMECARD_NUMBER
1Ayesha Khan**** **** **** 1111
2Bilal Ahmed**** **** **** 2222
3Clara Fernand**** **** **** 3333
4Danish Iqbal**** **** **** 4444
5Esha Malik**** **** **** 5555
6Farid Noor**** **** **** 6666

The masked values, written in as ordinary text. Now look at the copy's columns.

Query
SELECT "name", "type", "policy name"
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result3 rows · 3 columns
nametypepolicy name
PERSON_IDNUMBER(38,0)NULL
FULL_NAMEVARCHAR(60)NULL
CARD_NUMBERVARCHAR(25)NULL

A real NULL under policy name on every one of them. That copy has no masking policy on it at all.

The copy keeps the mask and loses the policy

So the copy is not masked data any more. It is a table of permanently starred strings, the real card numbers are not in it, and nothing on it says they ever were. A CREATE TABLE AS SELECT copies what you can see, not what is there.

The restricted role made its own copy too, and got exactly the same thing.

Query
CREATE OR REPLACE TABLE DEMO_DB.MASK_T165.COPIED_BY_MASKED_T165 AS
SELECT PERSON_ID, FULL_NAME, CARD_NUMBER
  FROM DEMO_DB.MASK_T165.PEOPLE_T165;
Result1 row · 1 column
status
Table COPIED_BY_MASKED_T165 successfully created.
Query
SELECT * FROM DEMO_DB.MASK_T165.COPIED_BY_MASKED_T165 ORDER BY PERSON_ID;
Result6 rows · 3 columns
PERSON_IDFULL_NAMECARD_NUMBER
1Ayesha Khan**** **** **** 1111
2Bilal Ahmed**** **** **** 2222
3Clara Fernand**** **** **** 3333
4Danish Iqbal**** **** **** 4444
5Esha Malik**** **** **** 5555
6Farid Noor**** **** **** 6666

And then one of ours fell over

The next thing in the demo was to read that second copy back as ACCOUNTADMIN.

Query
SELECT * FROM DEMO_DB.MASK_T165.COPIED_BY_MASKED_T165 ORDER BY PERSON_ID;
Query failed — Snowflake returned an error
003001 (42501): SQL access control error:
Insufficient privileges to operate on table 'COPIED_BY_MASKED_T165'. Your primary role ACCOUNTADMIN must have SELECT granted on TABLE DEMO_DB.MASK_T165.COPIED_BY_MASKED_T165.

003001, insufficient privileges. With the secondary roles switched off, a table another role created is not ours to read, and that is the control from the first section doing its job. The answer survives anyway, because the restricted role read its own copy two grids above.

Can we change a policy while it is attached?

Yes, and the table is never touched. Here is the body as it stands.

Query
SELECT "name", "body"
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 2 columns
namebody
MASK_COND_T165CASE WHEN CURRENT_ROLE() = 'RSEE_T165' THEN VAL ELSE '**** **** **** ' || RIGHT(VAL, 4) END

Now let's replace the body with a different one.

Query
ALTER MASKING POLICY DEMO_DB.MASK_T165.MASK_COND_T165 SET BODY ->
  CASE
    WHEN CURRENT_ROLE() = 'RSEE_T165' THEN VAL
    ELSE 'REDACTED'
  END;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT "name", "body"
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 2 columns
namebody
MASK_COND_T165CASE WHEN CURRENT_ROLE() = 'RSEE_T165' THEN VAL ELSE 'REDACTED' END

And now the same select, as the same restricted role, with no ALTER TABLE anywhere in between.

Query
USE ROLE RHIDE_T165;
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT PERSON_ID, FULL_NAME, CARD_NUMBER
  FROM DEMO_DB.MASK_T165.PEOPLE_T165
 ORDER BY PERSON_ID;
Result6 rows · 3 columns
PERSON_IDFULL_NAMECARD_NUMBER
1Ayesha KhanREDACTED
2Bilal AhmedREDACTED
3Clara FernandREDACTED
4Danish IqbalREDACTED
5Esha MalikREDACTED
6Farid NoorREDACTED

REDACTED where the stars were. The column's mask changed because the policy changed. There was no re-attaching and no DDL on the table at all.

A policy can carry a comment as well, like most objects.

Query
ALTER MASKING POLICY DEMO_DB.MASK_T165.MASK_COND_T165
  SET COMMENT = 'episode 165 - body replaced in place';
Result1 row · 1 column
status
Statement executed successfully.
Query
SELECT "name", "kind", "comment"
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
 ORDER BY "name";
Result4 rows · 3 columns
namekindcomment
MASK_COND_T165MASKING_POLICYepisode 165 - body replaced in place
MASK_FULL_T165MASKING_POLICY
MASK_NUM_T165MASKING_POLICY
MASK_PART_T165MASKING_POLICY

Four policies now, and only one of them has a comment. The other three show an empty cell rather than a NULL, because that is what SHOW output puts in a comment nobody set.

Now five refusals, and one I got wrong

Let's try to attach the numeric policy to a text column.

Query
ALTER TABLE DEMO_DB.MASK_T165.PEOPLE_T165
  MODIFY COLUMN CITY SET MASKING POLICY DEMO_DB.MASK_T165.MASK_NUM_T165;
Query failed — Snowflake returned an error
003530 (42601): SQL compilation error: COLUMN data type VARCHAR(40) does not match with masking policy data type FIXED.

003530, and the message names both types. A policy's signature has to match the column it goes on.

Now a second policy on a column that already has one.

Query
ALTER TABLE DEMO_DB.MASK_T165.PEOPLE_T165
  MODIFY COLUMN CARD_NUMBER SET MASKING POLICY DEMO_DB.MASK_T165.MASK_FULL_T165;
Query failed — Snowflake returned an error
003529 (42601): Specified column already attached to another masking policy. A column cannot be attached to multiple masking policies. Please drop the current association in order to attach a new masking policy.

003529. One column holds one policy, and the message tells us to drop the current association first. That is a rule rather than a preference, which is why we had to unset before attaching the conditional policy earlier.

Now let's try to drop a policy that is attached to a column.

Query
DROP MASKING POLICY DEMO_DB.MASK_T165.MASK_COND_T165;
Query failed — Snowflake returned an error
003531 (23001): SQL compilation error: Policy MASK_COND_T165 cannot be dropped/replaced as it is associated with one or more entities.

003531. Refused, and here is the count afterwards.

Query
SELECT COUNT(*) AS MY_POLICIES
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 1 column
MY_POLICIES
4

Four. The drop genuinely did not happen.

Now a policy whose declared return type the body cannot produce.

Query
CREATE OR REPLACE MASKING POLICY DEMO_DB.MASK_T165.MASK_BAD_T165
  AS (VAL VARCHAR) RETURNS NUMBER ->
  'not a number';
Query failed — Snowflake returned an error
090207 (42601): Declared return type 'NUMBER(38,0)' is incompatible with actual return type 'VARCHAR(12)'

090207, at CREATE time. That one never became an object.

And describing a policy that is not there.

Query
DESCRIBE MASKING POLICY DEMO_DB.MASK_T165.NO_SUCH_POLICY_T165;
Query failed — Snowflake returned an error
002003 (02000): SQL compilation error:
Masking policy 'DEMO_DB.MASK_T165.NO_SUCH_POLICY_T165' does not exist or not authorized. Your primary role ACCOUNTADMIN must have at least one privilege granted on POLICY DEMO_DB.MASK_T165.NO_SUCH_POLICY_T165.

And the one I expected to fail

I had marked this statement as one that would be refused: unsetting a masking policy from a column that never had one.

Query
ALTER TABLE DEMO_DB.MASK_T165.PEOPLE_T165
  MODIFY COLUMN CITY UNSET MASKING POLICY;
Result1 row · 1 column
status
Statement executed successfully.

Statement executed successfully. It is not an error, and my prediction was simply wrong.

One last thing: let's take it all off again

Let's unset the three policies from the three columns.

Query
ALTER TABLE DEMO_DB.MASK_T165.PEOPLE_T165
  MODIFY COLUMN CARD_NUMBER UNSET MASKING POLICY;
Result1 row · 1 column
status
Statement executed successfully.
Query
ALTER TABLE DEMO_DB.MASK_T165.PEOPLE_T165
  MODIFY COLUMN EMAIL UNSET MASKING POLICY;
Result1 row · 1 column
status
Statement executed successfully.
Query
ALTER TABLE DEMO_DB.MASK_T165.PEOPLE_T165
  MODIFY COLUMN SALARY UNSET MASKING POLICY;
Result1 row · 1 column
status
Statement executed successfully.

And read the table one more time.

Query
SELECT * FROM DEMO_DB.MASK_T165.PEOPLE_T165 ORDER BY PERSON_ID;
Result6 rows · 6 columns · scroll →
PERSON_IDFULL_NAMEEMAILCARD_NUMBERSALARYCITY
1Ayesha Khanayesha@example.com4111-1111-1111-111192000.00Karachi
2Bilal Ahmedbilal@example.com4111-1111-1111-222278500.00Lahore
3Clara Fernandclara@example.com4111-1111-1111-333361000.00Toronto
4Danish Iqbaldanish@example.com4111-1111-1111-4444115000.00Dubai
5Esha Malikesha@example.com4111-1111-1111-555554000.00Karachi
6Farid Noorfarid@example.com4111-1111-1111-666688000.00Lahore

Back to where the first section left it. Nothing in the table ever changed. Only what we were shown did.

Query
SELECT COUNT(*) AS REFERENCES_LEFT
  FROM TABLE(DEMO_DB.INFORMATION_SCHEMA.POLICY_REFERENCES(
         REF_ENTITY_NAME   => 'DEMO_DB.MASK_T165.PEOPLE_T165',
         REF_ENTITY_DOMAIN => 'TABLE'));
Result1 row · 1 column
REFERENCES_LEFT
0

No references left, so now the drop that was refused a moment ago will go through.

Query
DROP MASKING POLICY DEMO_DB.MASK_T165.MASK_COND_T165;
Result1 row · 1 column
status
MASK_COND_T165 successfully dropped.
Query
SELECT "name", "kind"
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
 ORDER BY "name";
Result3 rows · 2 columns
namekind
MASK_FULL_T165MASKING_POLICY
MASK_NUM_T165MASKING_POLICY
MASK_PART_T165MASKING_POLICY

Three left, and those go too, along with the schema and the two roles. Here is the account at the end.

Query
SHOW MASKING POLICIES IN ACCOUNT;
Result0 rows · 9 columns · scroll →
created_onnamedatabase_nameschema_namekindownercommentowner_role_typeoptions
Query
SELECT COUNT(*) AS MY_POLICIES_LEFT
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()))
 WHERE "name" LIKE '%\\_T165' ESCAPE '\\';
Result1 row · 1 column
MY_POLICIES_LEFT
0
Query
SELECT COUNT(*) AS MY_ROLES_LEFT
  FROM TABLE(RESULT_SCAN(LAST_QUERY_ID()));
Result1 row · 1 column
MY_ROLES_LEFT
0

And the control from the first section is put back the way we found it.

Query
SELECT CURRENT_ROLE() AS THE_ROLE, CURRENT_SECONDARY_ROLES() AS THE_SECONDARY_ROLES;
Result1 row · 2 columns
THE_ROLETHE_SECONDARY_ROLES
ACCOUNTADMIN{"roles":"ORGADMIN","value":"ALL"}

Key points

  • A masking policy is a named object with a signature, a return type and a body. DESCRIBE MASKING POLICY shows you all three.
  • A policy is attached to a column, not granted to a role. Owning the table and the policy buys you nothing.
  • A column holds one masking policy. A second one is 003529, and the signature has to match the column type or you get 003530.
  • DESCRIBE TABLE grows a policy name column, and POLICY_REFERENCES answers from the policy's side and the table's side.
  • The mask is applied before the WHERE clause. Filtering on the real value matched nothing, and filtering on the shape of the mask matched every row.
  • GROUP BY groups the masked values, and a numeric mask returns a number, so sums and averages come out of the mask.
  • CREATE TABLE AS SELECT copies what you can see. The copy holds masked strings and carries no policy at all.
  • A policy body can be replaced while it is attached, with no DDL on the table and no re-attaching.
  • Dropping an attached policy is 003531. Unsetting a policy from a column that never had one just succeeds.
Next in this series

In the next post we move from what a value looks like to whether the row is there at all: row access policies. Including the grid where the owner of the table selected from it and got nothing back.

Every query and every result grid on this page was captured from a live Snowflake account (version 10.36.101) running the demo script for this episode. USE SECONDARY ROLES NONE was set and proved off before the first policy existed, which is what makes the role comparisons mean anything. Every person, email address and card number is invented and the card numbers are from the 4111 test range. The grants that name a user are written here with a stand-in name. Everything created here was dropped here and the closing counts are on the page. Nothing is timed and no performance claims are made anywhere in this series. Behaviour follows the Snowflake CREATE MASKING POLICY documentation.

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.