From d00ae1d82613b0534a0d5f993c75f4b4270fa9f3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Pad=C5=82o?= Date: Fri, 4 Dec 2026 12:32:22 +0100 Subject: [PATCH 1/5] Fix tenantboard against current snowflake-next images The nightly run has failed in test setup since early November. - clone_database: a cloned table now arrives with its row access policy still referencing the source database's policy, so the plain ADD failed with 003549. Swap the stale reference for the clone's own policy in one ALTER TABLE (DROP ..., ADD ...). - TENANTBOARD_SVC: disable default secondary roles. The user holds every tenant's roles, and Snowflake activates all granted roles as secondary roles by default, which made IS_ROLE_IN_SESSION true for every tenant. Co-Authored-By: Claude Fable 5.2 --- tenantboard/app/provisioning.py | 10 +++++++++- tenantboard/init/01_platform.sf.sql | 4 ++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/tenantboard/app/provisioning.py b/tenantboard/app/provisioning.py index c346b9d..aaf3e30 100644 --- a/tenantboard/app/provisioning.py +++ b/tenantboard/app/provisioning.py @@ -193,7 +193,15 @@ def clone_database(conn: SnowflakeConnection, source: str, target: str) -> None: fqtn = f"{target}.{SCHEMA}.{table}" if ref.kind == "ROW_ACCESS_POLICY": cols = ", ".join(_identifier(c) for c in ref.arg_columns) - statements.append(f"ALTER TABLE {fqtn} ADD ROW ACCESS POLICY {policy} ON ({cols})") + 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): diff --git a/tenantboard/init/01_platform.sf.sql b/tenantboard/init/01_platform.sf.sql index 131944c..1f1c17d 100644 --- a/tenantboard/init/01_platform.sf.sql +++ b/tenantboard/init/01_platform.sf.sql @@ -29,6 +29,10 @@ GRANT ROLE PLATFORM_ADMIN TO ROLE SYSADMIN; CREATE USER IF NOT EXISTS TENANTBOARD_SVC DEFAULT_WAREHOUSE = TB_WH COMMENT = 'Tenantboard API service user (key-pair auth)'; +-- Snowflake activates all of a user's granted roles as secondary roles by +-- default. This user holds every tenant's roles, so each session must run +-- with its primary role only, or IS_ROLE_IN_SESSION is true for every tenant. +ALTER USER TENANTBOARD_SVC SET DEFAULT_SECONDARY_ROLES = (); GRANT ROLE PLATFORM_ADMIN TO USER TENANTBOARD_SVC; GRANT USAGE ON WAREHOUSE TB_WH TO ROLE TENANT_READER; GRANT USAGE ON WAREHOUSE TB_WH TO ROLE PLATFORM_ADMIN; From 00f9642d5183563e28ef78c5af94fd972a9f7625 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Pad=C5=82o?= Date: Fri, 4 Dec 2026 16:03:28 +0100 Subject: [PATCH 2/5] glue-snowflake-integration: download the connector jars with retries and a visible error deploy.sh fetched the two jars with 'wget -q', so a failed download ended the run with no message. Use curl with retries, and print the failing URL. Co-Authored-By: Claude Fable 5.2 --- glue-snowflake-integration/README.md | 2 +- glue-snowflake-integration/deploy.sh | 13 +++++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/glue-snowflake-integration/README.md b/glue-snowflake-integration/README.md index e3aff7e..8357ed9 100644 --- a/glue-snowflake-integration/README.md +++ b/glue-snowflake-integration/README.md @@ -27,7 +27,7 @@ glue-snowflake-integration/ - Docker with Docker Compose - Terraform, [`tflocal`](https://github.com/localstack/terraform-local) and [`awslocal`](https://github.com/localstack/awscli-local) - [Snowflake CLI](https://docs.snowflake.com/en/developer-guide/snowflake-cli/installation/installation) (`snow`) and `jq`, for `make test` -- Make and `wget` +- Make and `curl` Run `make install` to install `tflocal`, `awslocal` and the Snowflake CLI with pip. diff --git a/glue-snowflake-integration/deploy.sh b/glue-snowflake-integration/deploy.sh index d0ac77a..55e32f5 100755 --- a/glue-snowflake-integration/deploy.sh +++ b/glue-snowflake-integration/deploy.sh @@ -24,8 +24,17 @@ echo "📥 Downloading dependencies..." rm -rf jars && mkdir jars # Glue 4.0 runs Spark 3.3, so use the connector build for Spark 3.3 -wget -q "https://repo1.maven.org/maven2/net/snowflake/snowflake-jdbc/3.20.0/snowflake-jdbc-3.20.0.jar" -P jars -wget -q "https://repo1.maven.org/maven2/net/snowflake/spark-snowflake_2.12/2.16.0-spark_3.3/spark-snowflake_2.12-2.16.0-spark_3.3.jar" -P jars +MAVEN_REPO=${MAVEN_REPO:-https://repo1.maven.org/maven2} +for jar in \ + net/snowflake/snowflake-jdbc/3.20.0/snowflake-jdbc-3.20.0.jar \ + net/snowflake/spark-snowflake_2.12/2.16.0-spark_3.3/spark-snowflake_2.12-2.16.0-spark_3.3.jar; do + # -f fails on an HTTP error, -sS hides the progress bar but prints the error + if ! curl -fsSL --retry 5 --retry-all-errors --retry-delay 3 \ + -o "jars/$(basename "$jar")" "$MAVEN_REPO/$jar"; then + echo "❌ Could not download $MAVEN_REPO/$jar" + exit 1 + fi +done # Upload jars to S3 echo "☁️ Uploading JARs to S3..." From 110bfc5c5226bf4b01a202b485f3aaa254201b45 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Pad=C5=82o?= Date: Fri, 4 Dec 2026 16:05:33 +0100 Subject: [PATCH 3/5] order-to-cash-cdc: reach Kafka on 127.0.0.1 instead of localhost The broker's host port is published on 127.0.0.1 only, but the EXTERNAL listener was advertised as localhost and the clients bootstrapped from localhost. On the CI runner localhost also resolves to ::1, so librdkafka kept trying [::1]:19092 (connection refused) and intermittently failed topic creation with _DESTROY_BROKER, in make up or in the tests. Advertise and bootstrap from 127.0.0.1 so every connection uses the published address. Co-Authored-By: Claude Fable 5.2 --- order-to-cash-cdc/docker-compose.yml | 7 +++++-- order-to-cash-cdc/pipeline/settings.py | 3 ++- order-to-cash-cdc/producer/produce.py | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/order-to-cash-cdc/docker-compose.yml b/order-to-cash-cdc/docker-compose.yml index 6e56fec..cffbddf 100644 --- a/order-to-cash-cdc/docker-compose.yml +++ b/order-to-cash-cdc/docker-compose.yml @@ -30,8 +30,11 @@ services: KAFKA_CONTROLLER_QUORUM_VOTERS: 1@localhost:9093 KAFKA_LISTENERS: INTERNAL://:29092,EXTERNAL://:19092,CONTROLLER://:9093 # INTERNAL is for Kafka Connect on the compose network, EXTERNAL for the - # producer and tests on the host. - KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:29092,EXTERNAL://localhost:${KAFKA_PORT:-19092} + # producer and tests on the host. EXTERNAL is advertised as 127.0.0.1, + # not localhost: the port is published on 127.0.0.1 only, and where + # localhost also resolves to ::1 librdkafka tries the IPv6 address, gets + # connection refused and can fail the request. + KAFKA_ADVERTISED_LISTENERS: INTERNAL://kafka:29092,EXTERNAL://127.0.0.1:${KAFKA_PORT:-19092} KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT,CONTROLLER:PLAINTEXT KAFKA_INTER_BROKER_LISTENER_NAME: INTERNAL KAFKA_CONTROLLER_LISTENER_NAMES: CONTROLLER diff --git a/order-to-cash-cdc/pipeline/settings.py b/order-to-cash-cdc/pipeline/settings.py index 1eb5312..0bcdfcb 100644 --- a/order-to-cash-cdc/pipeline/settings.py +++ b/order-to-cash-cdc/pipeline/settings.py @@ -66,7 +66,8 @@ def load() -> Settings: "warehouse": _env("SNOWFLAKE_WAREHOUSE", "O2C_WH"), "database": _env("O2C_DATABASE", "O2C"), "connector_role": _env("O2C_CONNECTOR_ROLE", "O2C_INGEST"), - "kafka_bootstrap": f"localhost:{_env('KAFKA_PORT', '19092')}", + # 127.0.0.1, as published and advertised by docker-compose.yml (not localhost). + "kafka_bootstrap": f"127.0.0.1:{_env('KAFKA_PORT', '19092')}", "connect_url": f"http://127.0.0.1:{_env('CONNECT_PORT', '18083')}", } diff --git a/order-to-cash-cdc/producer/produce.py b/order-to-cash-cdc/producer/produce.py index d0117ee..cea6c26 100644 --- a/order-to-cash-cdc/producer/produce.py +++ b/order-to-cash-cdc/producer/produce.py @@ -344,7 +344,7 @@ def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) parser.add_argument("--topic", default="orders.cdc") parser.add_argument("--seed", type=int, default=42) - parser.add_argument("--bootstrap", default=f"localhost:{os.getenv('KAFKA_PORT', '19092')}") + parser.add_argument("--bootstrap", default=f"127.0.0.1:{os.getenv('KAFKA_PORT', '19092')}") args = parser.parse_args() scenario = initial_scenario(args.seed) count = publish(scenario.events, args.topic, args.bootstrap) From 89f1b7090e1a806fe4f9ae69f5837c099b301097 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Pad=C5=82o?= Date: Fri, 4 Dec 2026 16:20:31 +0100 Subject: [PATCH 4/5] Pin the airflow-dbt-transformation requirements to the environment's Airflow version The unpinned requirements let pip upgrade Airflow inside the MWAA container from 3.0.6 to the newest release while installing dbt. After the restart the Airflow services refused to start, because the metadata database was created by 3.0.6 ("Database migration required"). Pin apache-airflow, the Snowflake provider and the Snowflake connector to the versions the Airflow 3.0.6 image ships, pin Cosmos and dbt to releases that work with them, and create the environment with an explicit Airflow version. Co-Authored-By: Claude Fable 5.2 --- airflow-dbt-transformation/Makefile | 3 +++ airflow-dbt-transformation/README.md | 2 ++ airflow-dbt-transformation/requirements.txt | 19 +++++++++++++++---- airflow-dbt-transformation/test.sh | 2 +- 4 files changed, 21 insertions(+), 5 deletions(-) diff --git a/airflow-dbt-transformation/Makefile b/airflow-dbt-transformation/Makefile index 6a1cbe5..b3bfaef 100644 --- a/airflow-dbt-transformation/Makefile +++ b/airflow-dbt-transformation/Makefile @@ -1,4 +1,6 @@ AIRFLOW_CONTAINER = localstack-mwaa-000000000000-us-east-1-my-mwaa-env +# the versions in requirements.txt are pinned to match this Airflow version +AIRFLOW_VERSION = 3.0.6 usage: ## Shows usage for this Makefile @cat Makefile | grep -E '^[a-zA-Z_-]+:.*?## .*$$' | sort | awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-15s\033[0m %s\n", $$1, $$2}' @@ -22,6 +24,7 @@ init: ## Initialize the Airflow environment in LocalStack MWAA awslocal s3 cp requirements.txt s3://snowflake-airflow/ -docker rm -f $(AIRFLOW_CONTAINER) awslocal mwaa create-environment --dag-s3-path /dags \ + --airflow-version $(AIRFLOW_VERSION) \ --requirements-s3-path /requirements.txt \ --execution-role-arn arn:aws:iam::000000000000:role/airflow-role \ --network-configuration {} \ diff --git a/airflow-dbt-transformation/README.md b/airflow-dbt-transformation/README.md index 97bc201..85c178e 100644 --- a/airflow-dbt-transformation/README.md +++ b/airflow-dbt-transformation/README.md @@ -43,6 +43,8 @@ Run the following command to initialize the Airflow environment in LocalStack (t make init ``` +The environment runs Airflow 3.0.6 (`AIRFLOW_VERSION` in the `Makefile`), and `requirements.txt` pins `apache-airflow` and the other packages to versions that match it. Keep the two in sync: without the pins, `pip` upgrades Airflow itself while installing dbt, and the Airflow services then fail to start with `Database migration required`. To use another Airflow version, change `AIRFLOW_VERSION` and take the pins from the [constraints file](https://airflow.apache.org/docs/apache-airflow/stable/installation/installing-from-pypi.html#constraints-files) of that version. + After deploying the Airflow environment, you should be able to request its details, and extract the webserver URL: ``` awslocal mwaa get-environment --name my-mwaa-env diff --git a/airflow-dbt-transformation/requirements.txt b/airflow-dbt-transformation/requirements.txt index b8c42f7..76af33b 100644 --- a/airflow-dbt-transformation/requirements.txt +++ b/airflow-dbt-transformation/requirements.txt @@ -1,4 +1,15 @@ -apache-airflow-providers-snowflake -astronomer-cosmos -dbt-snowflake -snowflake-connector-python +# The environment runs Airflow 3.0.6 on Python 3.12 (`--airflow-version` in the +# Makefile). Pin Airflow and the packages its image already ships, so that +# installing dbt cannot upgrade Airflow itself: an upgraded Airflow no longer +# matches the environment's metadata database and fails to start. +# The first three versions are the ones in the Airflow constraints file: +# https://raw.githubusercontent.com/apache/airflow/constraints-3.0.6/constraints-3.12.txt +# That file cannot be used as `--constraint` here, because dbt needs newer +# protobuf and isodate versions than it allows. +apache-airflow==3.0.6 +apache-airflow-providers-snowflake==6.4.0 +snowflake-connector-python==3.17.2 +astronomer-cosmos==1.16.0 +# the newest dbt releases that work with snowflake-connector-python 3.x +dbt-core==1.10.23 +dbt-snowflake==1.10.5 diff --git a/airflow-dbt-transformation/test.sh b/airflow-dbt-transformation/test.sh index ade83d1..73a2943 100755 --- a/airflow-dbt-transformation/test.sh +++ b/airflow-dbt-transformation/test.sh @@ -25,7 +25,7 @@ poll() { airflow() { docker exec "$CONTAINER" airflow "$@" 2>/dev/null; } diagnostics() { docker inspect "$CONTAINER" --format '{{json .NetworkSettings.Networks}}' | jq -c 'keys' || true - docker exec "$CONTAINER" bash -c 'ls -la /opt/airflow/dags; pip show astronomer-cosmos dbt-snowflake 2>&1 | grep -E "^(Name|Version)"' || true + docker exec "$CONTAINER" bash -c 'ls -la /opt/airflow/dags; pip show apache-airflow astronomer-cosmos dbt-snowflake 2>&1 | grep -E "^(Name|Version)"' || true docker exec "$CONTAINER" airflow dags list-import-errors || true docker exec "$CONTAINER" bash -c 'tail -n 40 $(find /opt/airflow/logs -path "*query_result_data*" -name "*.log" | head -1)' || true docker logs --tail 80 "$CONTAINER" 2>&1 | grep -v SyntaxWarning || true From 4e9cebb6c05216e18661e580626a051a974da5be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Wojciech=20Pad=C5=82o?= Date: Fri, 4 Dec 2026 16:43:50 +0100 Subject: [PATCH 5/5] tenantboard: remove the clone-policy workaround from clone_database CREATE DATABASE ... CLONE now copies row access and masking policies and points the cloned tables at the clone's own copies, so clone_database no longer re-creates the policies or rewrites the references. It is the clone plus apply_grants. Add a test asserting that every tenant table of a clone references the clone's own policies, so an emulator regression fails the sample instead of being repaired silently. Co-Authored-By: Claude Fable 5.2 --- tenantboard/app/provisioning.py | 49 +++++------------------------ tenantboard/docs/architecture.md | 4 +-- tenantboard/tests/test_isolation.py | 14 +++++++++ 3 files changed, 23 insertions(+), 44 deletions(-) diff --git a/tenantboard/app/provisioning.py b/tenantboard/app/provisioning.py index aaf3e30..fbf5f30 100644 --- a/tenantboard/app/provisioning.py +++ b/tenantboard/app/provisioning.py @@ -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}$") @@ -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) diff --git a/tenantboard/docs/architecture.md b/tenantboard/docs/architecture.md index 222e8aa..d6108dd 100644 --- a/tenantboard/docs/architecture.md +++ b/tenantboard/docs/architecture.md @@ -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. diff --git a/tenantboard/tests/test_isolation.py b/tenantboard/tests/test_isolation.py index c4a3f2f..e31f795 100644 --- a/tenantboard/tests/test_isolation.py +++ b/tenantboard/tests/test_isolation.py @@ -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"