Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 7 additions & 42 deletions tenantboard/app/provisioning.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,6 @@
DEPLOY_MARKER = "-- @deploy:"
SCHEMA = "APP"
GRANTS_FILE = "04_grants.sf.sql"
# Load order matters only for readability; there are no enforced foreign keys.
TENANT_TABLES = ("MERCHANTS", "CUSTOMERS", "ORDERS", "LINE_ITEMS")

IDENTIFIER_PATTERN = re.compile(r"^[A-Z][A-Z0-9_]{0,254}$")

Expand Down Expand Up @@ -166,49 +164,16 @@ def policy_refs(conn: SnowflakeConnection, database: str, table: str) -> list[Po


def clone_database(conn: SnowflakeConnection, source: str, target: str) -> None:
"""CREATE DATABASE target CLONE source, provisioned with the source's policies and grants.
"""CREATE DATABASE target CLONE source, plus the grants.

Every policy reference the source's tables carry (POLICY_REFERENCES) is
ensured on the clone, pointing at the clone's own copy of the policy, and
the grants are applied (a clone never copies grants on the database
itself). Each test database therefore matches production exactly.
The clone carries the source's policies itself: CLONE copies the policy
objects, and the cloned tables reference the clone's own copies
(tests/test_isolation.py asserts it). Only the grants are applied here,
because a clone never copies grants on the database itself.

The step is driven by the *source's* references, not by a list in code: a
source table without a policy yields a clone without one, so the leak test
fails when the policy is removed from init/.
A source table without a policy yields a clone without one, so the leak
test fails when the policy is removed from init/.
"""
source, target = _identifier(source), _identifier(target)
query(conn, f"CREATE OR REPLACE DATABASE {target} CLONE {source}")
query(conn, f"USE DATABASE {target}")
# The clone's own copy of every policy (CREATE ... IF NOT EXISTS).
run_script(conn, deployable_sql(only="02_policies.sf.sql"))
statements: list[str] = []
for table in TENANT_TABLES:
have = policy_refs(conn, target, table)
for ref in policy_refs(conn, source, table):
own = PolicyRef(ref.kind, target, ref.schema, ref.name, ref.column, ref.arg_columns)
if own in have:
continue
policy = f"{target}.{_identifier(ref.schema)}.{_identifier(ref.name)}"
fqtn = f"{target}.{SCHEMA}.{table}"
if ref.kind == "ROW_ACCESS_POLICY":
cols = ", ".join(_identifier(c) for c in ref.arg_columns)
add = f"ADD ROW ACCESS POLICY {policy} ON ({cols})"
# A table carries at most one row access policy. If the clone still
# references the source's, swap it in one statement so the table is
# never unprotected.
stale = next((h for h in have if h.kind == ref.kind), None)
if stale:
old = ".".join(_identifier(part) for part in (stale.database, stale.schema, stale.name))
add = f"DROP ROW ACCESS POLICY {old}, {add}"
statements.append(f"ALTER TABLE {fqtn} {add}")
elif ref.kind == "MASKING_POLICY" and ref.column:
column = _identifier(ref.column)
if any(h.kind == ref.kind and h.column == ref.column for h in have):
statements.append(f"ALTER TABLE {fqtn} MODIFY COLUMN {column} UNSET MASKING POLICY")
statements.append(f"ALTER TABLE {fqtn} MODIFY COLUMN {column} SET MASKING POLICY {policy}")
else:
raise RuntimeError(f"unexpected policy reference {ref}")
for statement in statements:
query(conn, statement)
apply_grants(conn, target)
4 changes: 2 additions & 2 deletions tenantboard/docs/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,13 +90,13 @@ sequenceDiagram
C->>S: CREATE DATABASE TB_TEMPLATE from init/*.sf.sql, load the seed
C->>W: start 4 workers
W->>S: CREATE DATABASE TB_TEST_GWn CLONE TB_TEMPLATE
W->>S: apply the template's policy references and grants
W->>S: apply the grants
W->>S: tests (API, raw role sessions, scratch clones)
W->>S: DROP DATABASE TB_TEST_GWn
C->>S: DROP DATABASE TB_TEMPLATE
```

Each worker database is provisioned from the template's `POLICY_REFERENCES` and grants file, so every test database carries exactly the protection production has. The step is driven by the template, not by a list in code: a policy missing from `init/` is missing from every clone, and the leak test fails.
`CLONE` copies the template's policies into each worker database and points the cloned tables at those copies; the grants file is then applied, because a clone never copies grants on the database itself. Every test database therefore carries exactly the protection production has, and `tests/test_isolation.py` asserts that each clone's `POLICY_REFERENCES` name the clone's own policies. Nothing is repaired in code: a policy missing from `init/` is missing from every clone, and the leak test fails.

Uploads write only to tenant `INITECH` with order ids unique per test, so tests are order-independent within a worker. Tests that modify policies work on their own scratch clones.

Expand Down
14 changes: 14 additions & 0 deletions tenantboard/tests/test_isolation.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,20 @@ async def run():
assert summary.revenue == expected_summary(dataset, "ACME")["revenue"]


@pytest.mark.parametrize("table", TENANT_TABLES)
def test_a_clone_references_its_own_policies(admin, worker_db, table):
"""CLONE must leave each table on the clone's copy of every policy, never on the template's.

provisioning.clone_database repairs nothing, so a clone whose references
point at another database (or are missing) fails here.
"""
expected = {provisioning.PolicyRef("ROW_ACCESS_POLICY", worker_db, "APP", "TENANT_ISOLATION", None, ("TENANT_ID",))}
if table == "CUSTOMERS":
expected.add(provisioning.PolicyRef("MASKING_POLICY", worker_db, "APP", "EMAIL_MASK", "EMAIL", ()))

assert set(provisioning.policy_refs(admin, worker_db, table)) == expected


def test_detaching_the_policy_exposes_every_tenant(settings: Settings, dataset, worker_db):
"""The control for the leak test: on a scratch clone, drop the policy and the same raw SELECT leaks."""
scratch = f"{worker_db}_LEAK"
Expand Down
Loading