๐ŸŽ‰ 75% of content is free forever โ€” Unlock Premium from $10/mo โ†’
CW
NEWSLIVESearch All Content
๐Ÿ’ผ Servicesโ„น๏ธ Aboutโœ‰๏ธ ContactView Pricing Plansfrom $10

Topic: Security, RBAC & Data Masking

Snowflake AdvancedSecurityโญ Premium

Snowflake Advanced ยท Interview Prep

Security, RBAC & Data Masking

Difficulty: Hard ยท Commonly asked at Google, Apple, Amazon

Interview Question

"Design a security model for a multi-tenant data platform where different departments can only see their own data, and sensitive columns like SSN and salary are masked for non-privileged users."

โ„น๏ธ

Companies Asking This: Google (Senior Cloud Security Engineer), Apple (Staff Data Engineer), Amazon (L6 Data Engineer), Microsoft (Principal Data Architect)


Role-Based Access Control (RBAC)

Snowflake uses a hierarchical RBAC model where privileges are granted to roles, and roles are granted to users or other roles.

The shipped system roles divide ownership cleanly: ACCOUNTADMIN holds account-level objects and can see everything, SECURITYADMIN creates roles and issues grants, SYSADMIN owns warehouses and databases, USERADMIN owns role creation only, and PUBLIC is a role every user implicitly holds. The direction of inheritance is the interview point. Privileges flow down the hierarchy, a child role never lends its grants back up, and a user activates one role at a time, so a developer with five roles still behaves as one of them per session. Ownership is a separate axis from privilege: the owner of an object may always grant on it, which is why a table owned by ACCOUNTADMIN forces you back into that role just to delegate access. Create custom roles under USERADMIN, place the databases they touch under SYSADMIN, and grant each role only what its workload uses. Any grant written to PUBLIC is effectively a grant to every current and future user of the account, and it is the most common finding in a security review of a hastily built pipeline.

Role Hierarchy

SECURITYADMINACCOUNTADMINSYSADMINUSERADMINPUBLICDATAADMINANALYTICSADMINETLADMINDATAENGINEERANALYSTROLEETLDEVELOPER

Creating RBAC Structure

-- 1. Create custom roles
CREATE ROLE data_admin;
CREATE ROLE data_engineer;
CREATE ROLE analyst;
CREATE ROLE etl_developer;
CREATE ROLE read_only;

-- 2. Grant roles to users
GRANT ROLE data_admin TO USER john_doe;
GRANT ROLE analyst TO USER jane_smith;

-- 3. Create role hierarchy
GRANT ROLE data_engineer TO ROLE data_admin;
GRANT ROLE analyst TO ROLE data_admin;
GRANT ROLE etl_developer TO ROLE data_engineer;
GRANT ROLE read_only TO ROLE analyst;

-- 4. Grant database privileges
GRANT USAGE ON DATABASE company_db TO ROLE data_engineer;
GRANT USAGE ON DATABASE company_db TO ROLE analyst;
GRANT CREATE SCHEMA ON DATABASE company_db TO ROLE data_engineer;

-- 5. Grant schema privileges
GRANT USAGE ON SCHEMA company_db.public TO ROLE data_engineer;
GRANT CREATE TABLE ON SCHEMA company_db.public TO ROLE data_engineer;
GRANT SELECT ON ALL TABLES IN SCHEMA company_db.public TO ROLE analyst;

-- 6. Grant table privileges
GRANT SELECT, INSERT, UPDATE, DELETE ON TABLE company_db.public.orders TO ROLE data_engineer;
GRANT SELECT ON TABLE company_db.public.orders TO ROLE analyst;

-- 7. Grant future grants (auto-apply to new objects)
GRANT SELECT ON FUTURE TABLES IN SCHEMA company_db.public TO ROLE analyst;
GRANT USAGE ON FUTURE SCHEMAS IN DATABASE company_db TO ROLE analyst;

-- 8. Check role hierarchy
SELECT 
    grantee_name,
    granted_role,
    granted_by,
    created_on
FROM snowflake.account_usage.grants_to_roles
WHERE granted_role IN ('DATA_ENGINEER', 'ANALYST', 'ETL_DEVELOPER')
ORDER BY granted_role, grantee_name;

Dynamic Data Masking

Data masking transforms sensitive data at query time based on the user's role.

Policies attach to columns and run on read, so the stored value never changes and every downstream query inherits the mask automatically. A column carries one masking policy at a time; when different audiences need different treatments you either branch inside that policy on CURRENT_ROLE() or use a polymorphic policy that keeps several related policies on the same column and activates one per query, which is how HR sees a full salary while finance sees a rounded figure from the same column. Aggregation policies go further and let a manager see a sum while an analyst sees nothing above the group level. Two costs are worth naming: every evaluation adds per-row work, which is measurable on a wide scan of a hot column, and the policy travels with the column โ€” a view over a masked table cannot unmask it, but a CREATE TABLE AS SELECT copy does not carry the policy, so exports and clones need their own controls.

Column-Level Masking

-- 1. Create masking policy for email
CREATE OR REPLACE MASKING POLICY email_mask 
AS (val VARCHAR) RETURNS VARCHAR ->
    CASE
        WHEN CURRENT_ROLE() IN ('DATA_ADMIN', 'SECURITY_ADMIN') THEN val
        WHEN CURRENT_ROLE() = 'ANALYST' THEN REGEXP_REPLACE(val, '.', '*', 2)
        ELSE '***MASKED***'
    END;

-- 2. Apply masking policy to column
ALTER TABLE customers MODIFY COLUMN email SET MASKING POLICY email_mask;

-- 3. Create masking policy for SSN
CREATE OR REPLACE MASKING POLICY ssn_mask 
AS (val VARCHAR) RETURNS VARCHAR ->
    CASE
        WHEN CURRENT_ROLE() IN ('DATA_ADMIN', 'HR_ADMIN') THEN val
        ELSE CONCAT('XXX-XX-', RIGHT(val, 4))
    END;

-- 4. Apply SSN masking
ALTER TABLE employees MODIFY COLUMN ssn SET MASKING POLICY ssn_mask;

-- 5. Create masking policy for salary
CREATE OR REPLACE MASKING POLICY salary_mask 
AS (val NUMBER) RETURNS NUMBER ->
    CASE
        WHEN CURRENT_ROLE() IN ('DATA_ADMIN', 'HR_ADMIN') THEN val
        WHEN CURRENT_ROLE() = 'MANAGER' THEN ROUND(val, -3)  -- Round to nearest 1000
        ELSE NULL
    END;

-- 6. Apply salary masking
ALTER TABLE employees MODIFY COLUMN salary SET MASKING POLICY salary_mask;

-- Test masking
-- As DATA_ADMIN (sees full data)
SET ROLE DATA_ADMIN;
SELECT email, ssn, salary FROM customers LIMIT 5;

-- As ANALYST (sees masked data)
SET ROLE ANALYST;
SELECT email, ssn, salary FROM customers LIMIT 5;
-- email: j**@example.com
-- ssn: XXX-XX-1234
-- salary: NULL

Row-Level Security (Row Access Policies)

A row access policy returns true or false per row and is re-evaluated on every query, so one table legitimately returns different row counts to different users. Because filtering happens before aggregation, a COUNT or SUM already excludes the invisible rows and totals never leak what a user cannot see. The usual design is a small mapping table keyed on CURRENT_USER() with an explicit admin bypass, exactly as in the script below. Two constraints surface in interviews: a column cannot carry both a masking policy and an aggregation policy at once, and the policy filter runs through metadata rather than a stored index, so a very selective policy on a very large mapping table adds work to each query. Keep the mapping table narrow, grant read on it only to the roles that need it, and test with SET ROLE before you declare the design finished.

-- 1. Create a mapping table for department access
CREATE TABLE user_department_access (
    user_name VARCHAR(100),
    department VARCHAR(50),
    access_level VARCHAR(20)
);

INSERT INTO user_department_access VALUES
('john_doe', 'SALES', 'FULL'),
('jane_smith', 'MARKETING', 'FULL'),
('bob_jones', 'ENGINEERING', 'READ_ONLY');

-- 2. Create row access policy
CREATE OR REPLACE ROW ACCESS POLICY department_policy 
AS (department VARCHAR) RETURNS BOOLEAN ->
    CASE
        WHEN CURRENT_ROLE() IN ('DATA_ADMIN', 'SECURITY_ADMIN') THEN TRUE
        WHEN EXISTS (
            SELECT 1 FROM user_department_access 
            WHERE user_name = CURRENT_USER() 
              AND department = department
        ) THEN TRUE
        ELSE FALSE
    END;

-- 3. Apply row access policy to table
ALTER TABLE sales_data ADD ROW ACCESS POLICY department_policy ON (department);

-- 4. Test row-level security
-- As DATA_ADMIN (sees all rows)
SET ROLE DATA_ADMIN;
SELECT COUNT(*) FROM sales_data;  -- Returns all rows

-- As analyst with SALES access
SET ROLE ANALYST;
SELECT COUNT(*) FROM sales_data WHERE department = 'SALES';  -- Returns only SALES rows
SELECT COUNT(*) FROM sales_data WHERE department = 'ENGINEERING';  -- Returns 0 rows

Real-World Scenario: Google

Question: "How do you implement column-level security for a table that has PII data, and different users need different levels of access to the same column?"

The first decision is physical isolation versus policy-based isolation. Separate databases per sensitivity tier give hard boundaries and simple auditing, but force cross-tier joins through external copies. One table with layered policies keeps joins cheap, at the cost of requiring a policy decision for every new column before it ships. Teams that pick the policy route usually maintain a small metadata table listing sensitive columns and generate an audit query from it, so a column added without a policy fails review rather than production.

Multi-Level Column Security

-- Create table with PII data
CREATE TABLE customer_pii (
    customer_id VARCHAR(100),
    name VARCHAR(200),
    email VARCHAR(200),
    phone VARCHAR(20),
    ssn VARCHAR(11),
    birth_date DATE,
    address VARCHAR(500),
    credit_score NUMBER
);

-- Create multiple masking policies for different sensitivity levels

-- Policy 1: Full masking for unauthorized users
CREATE OR REPLACE MASKING POLICY pii_full_mask 
AS (val VARCHAR) RETURNS VARCHAR ->
    CASE
        WHEN CURRENT_ROLE() IN ('DATA_ADMIN', 'PII_ADMIN') THEN val
        ELSE '***REDACTED***'
    END;

-- Policy 2: Partial masking for authorized analysts
CREATE OR REPLACE MASKING POLICY pii_partial_mask 
AS (val VARCHAR) RETURNS VARCHAR ->
    CASE
        WHEN CURRENT_ROLE() IN ('DATA_ADMIN', 'PII_ADMIN') THEN val
        WHEN CURRENT_ROLE() = 'PII_ANALYST' THEN 
            CONCAT(LEFT(val, 2), REPEAT('*', LENGTH(val) - 4), RIGHT(val, 2))
        ELSE '***REDACTED***'
    END;

-- Policy 3: Numeric masking for credit score
CREATE OR REPLACE MASKING POLICY credit_score_mask 
AS (val NUMBER) RETURNS NUMBER ->
    CASE
        WHEN CURRENT_ROLE() IN ('DATA_ADMIN', 'PII_ADMIN') THEN val
        WHEN CURRENT_ROLE() = 'PII_ANALYST' THEN ROUND(val, -1)  -- Round to nearest 10
        ELSE NULL
    END;

-- Apply policies
ALTER TABLE customer_pii MODIFY COLUMN name SET MASKING POLICY pii_partial_mask;
ALTER TABLE customer_pii MODIFY COLUMN email SET MASKING POLICY pii_partial_mask;
ALTER TABLE customer_pii MODIFY COLUMN phone SET MASKING POLICY pii_full_mask;
ALTER TABLE customer_pii MODIFY COLUMN ssn SET MASKING POLICY pii_full_mask;
ALTER TABLE customer_pii MODIFY COLUMN credit_score SET MASKING POLICY credit_score_mask;

-- Test different access levels
-- PII_ADMIN: sees everything
-- PII_ANALYST: sees partial data
-- Regular ANALYST: sees only redacted data

Encryption & Network Security

Snowflake encrypts every micro-partition at rest with AES-256 and manages the key lifecycle itself, which removes a class of compliance questions but does not remove access control: encryption protects against storage-level compromise, not against a role that is entitled to SELECT. Tri-Secret Secure layers a customer-managed key from a cloud KMS onto that chain, and it is what a contract usually means when it asks you to be able to revoke the vendor's access to your own data. Network policies bind at login and can be applied at account, user or role scope, so the practical pattern is one broad allow list for humans plus a narrow policy per service user. Block lists alone are weak because IP ranges rotate; allow lists are the control that actually holds.

-- 1. Check encryption settings
SELECT 
    database_name,
    schema_name,
    table_name,
    encryption_algorithm,
    key_version
FROM information_schema.tables
WHERE table_catalog = 'COMPANY_DB';

-- 2. Network policies
CREATE OR REPLACE NETWORK POLICY corporate_policy
    ALLOWED_IP_LIST = ('203.0.113.0/24', '198.51.100.0/24')
    BLOCKED_IP_LIST = ('192.0.2.0/24')
    COMMENT = 'Corporate office IP ranges';

-- 3. Apply network policy to account
ALTER ACCOUNT SET NETWORK_POLICY = corporate_policy;

-- 4. Create network policy for specific users
CREATE OR REPLACE NETWORK POLICY analytics_policy
    ALLOWED_IP_LIST = ('10.0.0.0/8');

-- 5. Check network policy usage
SELECT 
    policy_name,
    comment,
    created_on
FROM information_schema.network_policies;

-- 6. Audit network access
SELECT 
    user_name,
    client_ip,
    event_timestamp,
    event_type
FROM snowflake.account_usage.login_history
WHERE event_timestamp >= DATEADD(day, -7, CURRENT_TIMESTAMP())
ORDER BY event_timestamp DESC;

Service Accounts, Key-Pair Auth and the Audit Trail

Password authentication is the weakest link in an otherwise strict model. Move automation to key-pair authentication: generate an RSA key pair, set the public key on the service user, and keep the private key in a secret manager rather than in a repository or a scheduler variable. Then scope a network policy to the runner's egress range so that a leaked key is only useful from one place, and attach a resource monitor so a compromised key cannot quietly drain the account overnight. Audit data arrives on two clocks. The account_usage views lag by minutes but keep months of history, while information_schema history is near real time and short lived. Alerting should therefore read both: immediate detection from information_schema, forensic reconstruction from account_usage, and a weekly diff of new grants so that privilege creep shows up as a change rather than as an incident.

-- Users still able to authenticate with a password
SELECT name, has_password, has_rsa_public_key, default_role, disabled
FROM snowflake.account_usage.users
WHERE disabled = 'FALSE'
  AND has_password = 'TRUE'
  AND deleted_on IS NULL
ORDER BY name;

-- Privileges that are effectively world-readable
SELECT grantee_name, privilege, name
FROM snowflake.account_usage.grants_to_roles
WHERE grantee_name = 'PUBLIC'
ORDER BY privilege;

Best Practices

Turn the table below into an operating routine rather than a poster. Review custom role grants on a fixed cadence, alert on any new grant, and require an expiry date on exceptions. A masking policy nobody tests is a policy that will surprise you during the first export, so schedule a quarterly role-switch drill that reads the sensitive table as an analyst and archives the output for review.

Security LayerImplementation
AuthenticationUse SSO/SAML, enforce MFA
AuthorizationImplement RBAC with least privilege
Data MaskingUse dynamic masking policies per role
Row SecurityUse row access policies for multi-tenant
EncryptionSnowflake encrypts at rest by default
NetworkUse network policies for IP whitelisting
AuditingMonitor ACCOUNT_USAGE for security events

โš ๏ธ

Security Anti-Patterns:

  1. Using ACCOUNTADMIN for daily work โ€” Use least-privilege roles
  2. Granting privileges to PUBLIC โ€” Everyone sees the data
  3. Hardcoding credentials โ€” Use secrets and external functions
  4. Ignoring audit logs โ€” Monitor for unauthorized access

Key Takeaways

  • Privileges flow down the role hierarchy and a user activates one role at a time; ownership, not privilege, is what lets someone re-grant access.
  • Masking policies transform column values on read while row access policies filter whole rows, and filtering happens before aggregation so totals never leak.
  • Copies and exports do not carry policies, so any CREATE TABLE AS SELECT of a sensitive table needs its own controls.
  • Automate with key-pair users, allow-list network policies and alerting that reads both information_schema and account_usage.
๐Ÿ”’

Premium Content

Topic: Security, RBAC & Data Masking

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

๐ŸŽฏEnd-to-end Projects
๐Ÿ’ผInterview Prep
๐Ÿ“œCertificates
๐ŸคCommunity Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-15

โ€”
โ˜†โ˜†โ˜†โ˜†โ˜†
0 ratings

Rate & Feedback

Advertisement