# Row- and column-level security

This guide explains how to configure declarative column-level security (CLS)
and row-level security (RLS) in Google Cloud Cortex Framework across
BigQuery tables built by Dataform. By defining global policy
tag aliases, reusable domain rules, and per-table overrides in YAML, security
teams can enforce consistent governance across SAP, Salesforce, and custom data
modules without editing SQL or JavaScript definitions.

## 3-tier security architecture

Cortex Framework resolves security policies across three
configuration tiers during
[`uv run cortex-build`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-build.md.txt):

- **Tier 1---Global governance (`data.security` in `config.yaml`)**: Enables or disables security workspace-wide, registers logical aliases for Data Catalog policy tag URIs, configures automatic Dataform pipeline service account access, and declares shared Tier 2 domain rules.
- **Tier 2---Domain rules (`data.security.domainRules[]` in `config.yaml`)** : Targets groups of data foundation and data product modules by `modulePaths` (case-sensitive `fnmatch` glob patterns) or exact `moduleIds`. Applies column policy tags by exact column name or suffix and attaches mandatory row filters whenever required columns exist on a materialized table.
- **Tier 3---Table overrides (`table_settings.yaml` or
  `inlineTableSettings`)** : Customizes CLS policy tags and RLS policies for individual materialized tables (`table` or `incremental` models only). Placement is strictly enforced by module type:
  - **Data foundations (`external: false` only)** : Place `security` strictly under `target.security` on each table entry. Placing `security` at the table entry root or under `source` fails validation.
  - **Data products** : Place `security` strictly at the table item root (as a sibling of `materializationType`, `assertions`, and `bigQueryLabels`). For versioned SAP data products, place the table entry under `common.<table_name>.security` or `<variant>.<table_name>.security` (`ecc` or `s4`). Placing `security` under `target` on a data product fails validation.

At build time, `security_resolver` evaluates all three tiers for every enabled
materialized table and serializes the resolved configuration into the generated
Dataform `.js` table definition. Any policy conflict, missing
metadata, or disallowed override fails the build immediately with a
`CortexConfigError`.

## Prerequisites and pre-flight validation

Before deploying CLS or RLS policies to Google Cloud, enable the required APIs
and grant Identity and Access Management (IAM) roles for both deployment pre-flight checks
and runtime execution.

### Required APIs

Enable the following APIs in the appropriate Google Cloud projects:

| API | Project | Purpose |
|---|---|---|
| BigQuery API (`bigquery.googleapis.com`) | Every **source and target project** | Materializes governed tables, creates and drops row access policies, and patches column policy tags. |
| Dataform API (`dataform.googleapis.com`) | Repository project (for `type: dataform` targets) | Uploads and runs compiled Dataform workflows. |
| Data Catalog API (`datacatalog.googleapis.com`) | Every **taxonomy project** referenced in policy tag URIs **and** every **target project** hosting CLS-governed tables | Validates policy tag existence, location, and taxonomy access-control enforcement during pre-flight checks, and supports BigQuery policy tag attachment. |
| Service Usage API (`serviceusage.googleapis.com`) | Build, target, and taxonomy projects | Checks enabled APIs during pre-flight validation. |
| BigQuery Data Policy API (`bigquerydatapolicy.googleapis.com`) *(optional)* | Every **taxonomy project** hosting data policies **and** every **target project** hosting CLS-governed tables using dynamic data masking | Manages and enforces optional BigQuery data policies attached to Data Catalog policy tags for [dynamic data masking](https://docs.cloud.google.com/bigquery/docs/column-data-masking-intro.md.txt). |

You can enable these APIs by using the Google Cloud CLI (or pass
`--enable-apis` to `uv run cortex-deploy` or `uv run cortex-apply-security` to
enable `bigquery.googleapis.com` and `datacatalog.googleapis.com`
automatically):

```bash
gcloud services enable \
    bigquery.googleapis.com \
    datacatalog.googleapis.com \
    bigquerydatapolicy.googleapis.com \
    dataform.googleapis.com \
    --project=PROJECT_ID
```

Replace `PROJECT_ID` with the ID of the target or governance Google Cloud
project. If policy tags live in a dedicated central governance project separate
from your BigQuery target project, enable
`datacatalog.googleapis.com` (and `bigquerydatapolicy.googleapis.com` when using
dynamic data masking) on both the governance project and every CLS-governed
target project.

### Create policy tag taxonomies

Cortex Framework references existing Data Catalog
policy tags and BigQuery data policies instead of creating
taxonomies during deployment. Complete these steps before enabling
`data.security`:

1. Create a policy tag taxonomy and policy tags by following [Restrict column access with BigQuery column-level security](https://docs.cloud.google.com/bigquery/docs/column-level-security.md.txt) in the Google Cloud console (**BigQuery** \> **Governance** \> **Policy tags** ):
   - Select the exact same location configured in `data.bigQueryLocation` in `config.yaml` (for example, `US`, `EU`, or `us-central1`).
   - When hosting taxonomies in a central governance project separate from your BigQuery target projects, verify that both projects belong to the **same Google Cloud organization** (BigQuery rejects cross-organization policy tag attachments).
   - Turn on **Enforce access control** (`FINE_GRAINED_ACCESS_CONTROL`) on the taxonomy.
   - Copy each policy tag's resource name (`projects/TAXONOMY_PROJECT_ID/locations/LOCATION/taxonomies/TAXONOMY_ID/policyTags/POLICY_TAG_ID`) into `data.security.policyTags` in `config.yaml`.
2. Optional: Attach dynamic data masking policies. To return masked values (such as `SHA-256`, default masking values, or email masks) instead of `403 Access Denied` errors for analysts without unmasked access, attach masking rules to your policy tags (**BigQuery** \> **Governance** \> **Policy tags** \> **Manage data policies** ). For details, see [Introduction to dynamic data masking](https://docs.cloud.google.com/bigquery/docs/column-data-masking-intro.md.txt) and [Mask column data](https://docs.cloud.google.com/bigquery/docs/column-data-masking.md.txt).

### Required IAM roles

Grant the required IAM roles for pre-flight validation, schema
reconciliation, runtime execution, and querying protected tables.

#### Pre-flight validation and schema reconciliation

During deployment (`uv run cortex-deploy`, `uv run cortex-build-and-deploy` for
`type: dataform`, and `uv run cortex-demo`) and during
[`uv run cortex-apply-security`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-apply-security.md.txt)
(for both `type: dataform` and `type: git`, including `--dry-run`),
Cortex Framework verifies enabled APIs and confirms that every
referenced policy tag exists and belongs to a taxonomy with **Enforce access
control** enabled.

After your Dataform workflow materializes the tables,
`uv run cortex-apply-security` attaches column policy tags and removes stale
row access policies in BigQuery. Grant the deploying and
security-reconciliation principal the following roles:

- **Build and target projects** : [BigQuery Job User](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.jobUser) (`roles/bigquery.jobUser`) on the build project and on target projects.
- **Checked projects (API validation)** : [Service Usage Consumer](https://docs.cloud.google.com/iam/docs/roles-permissions/serviceusage.md.txt#serviceusage.serviceUsageConsumer) (`roles/serviceusage.serviceUsageConsumer`) or [Service Usage Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/serviceusage.md.txt#serviceusage.serviceUsageViewer) (`roles/serviceusage.serviceUsageViewer`) on the checked target and taxonomy projects, or [Service Usage Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/serviceusage.md.txt#serviceusage.serviceUsageAdmin) (`roles/serviceusage.serviceUsageAdmin`) if you pass `--enable-apis`.
- **Source datasets** : [BigQuery Metadata Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.metadataViewer) (`roles/bigquery.metadataViewer`).
- **Target datasets** : [BigQuery Data Owner](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.dataOwner) (`roles/bigquery.dataOwner`) (or [BigQuery Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.admin) (`roles/bigquery.admin`), or a custom role combining `roles/bigquery.dataEditor` with `bigquery.tables.setCategory` and `bigquery.rowAccessPolicies.{create,delete,list,setIamPolicy}`). These permissions let `SecuritySchemaReconciler` patch column `policyTags` (`bigquery.tables.update` and `bigquery.tables.setCategory`), list live row access policies (`bigquery.rowAccessPolicies.list`), and drop stale or disabled row access policies (`bigquery.rowAccessPolicies.*`).
- **Dataform repository (`type: dataform` targets)** : [Dataform Editor](https://docs.cloud.google.com/iam/docs/roles-permissions/dataform.md.txt#dataform.editor) (`roles/dataform.editor`) on the repository and [Service Account User](https://docs.cloud.google.com/iam/docs/roles-permissions/iam.md.txt#iam.serviceAccountUser) (`roles/iam.serviceAccountUser`) on the custom Dataform execution service account.
- **Taxonomy projects and policy tags** : [Data Catalog Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/datacatalog.md.txt#datacatalog.viewer) (`roles/datacatalog.viewer`) or [Policy Tag Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/datacatalog.md.txt#datacatalog.categoryAdmin) (`roles/datacatalog.categoryAdmin`) on every taxonomy project referenced in your policy tag URIs (`datacatalog.taxonomies.get`), plus [Fine-Grained Reader](https://docs.cloud.google.com/iam/docs/roles-permissions/datacatalog.md.txt#datacatalog.categoryFineGrainedReader) (`roles/datacatalog.categoryFineGrainedReader`) on referenced policy tags.

#### Runtime execution and data consumption

Grant the following roles to the Dataform execution service
account (either the custom `targetSettings.serviceAccount` or the default
Dataform service agent
`service-PROJECT_NUMBER@gcp-sa-dataform.iam.gserviceaccount.com`)
and to query principals:

- **Dataform execution service account** :
  - **Source and entitlement lookup datasets** : [BigQuery Data Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.dataViewer) (`roles/bigquery.dataViewer`).
  - **Target datasets** : [BigQuery Data Owner](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.dataOwner) (`roles/bigquery.dataOwner`) (or [BigQuery Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.admin) (`roles/bigquery.admin`), or a custom role combining `roles/bigquery.dataEditor` with `bigquery.tables.setCategory` and `bigquery.rowAccessPolicies.{create,update,delete,list,setIamPolicy}`) to run zero-fail-open table refreshes, `CREATE OR REPLACE ROW ACCESS POLICY`, `DROP ROW ACCESS POLICY`, and `DROP ALL ROW ACCESS POLICIES ON` (which require `bigquery.rowAccessPolicies.setIamPolicy` and `bigquery.tables.getData`).
  - **Execution project** : [BigQuery Job User](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.jobUser) (`roles/bigquery.jobUser`).
  - **Taxonomy projects and policy tags** : [Data Catalog Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/datacatalog.md.txt#datacatalog.viewer) (`roles/datacatalog.viewer`) or [Policy Tag Admin](https://docs.cloud.google.com/iam/docs/roles-permissions/datacatalog.md.txt#datacatalog.categoryAdmin) (`roles/datacatalog.categoryAdmin`) on taxonomy projects, plus [Fine-Grained Reader](https://docs.cloud.google.com/iam/docs/roles-permissions/datacatalog.md.txt#datacatalog.categoryFineGrainedReader) (`roles/datacatalog.categoryFineGrainedReader`) on every referenced policy tag to read upstream CLS-protected tables during transformations.
  - **Custom service account impersonation (`targetSettings.serviceAccount`)** : Grant the default Dataform service agent (`service-PROJECT_NUMBER@gcp-sa-dataform.iam.gserviceaccount.com`) both [Service Account Token Creator](https://docs.cloud.google.com/iam/docs/roles-permissions/iam.md.txt#iam.serviceAccountTokenCreator) (`roles/iam.serviceAccountTokenCreator`) and [Service Account User](https://docs.cloud.google.com/iam/docs/roles-permissions/iam.md.txt#iam.serviceAccountUser) (`roles/iam.serviceAccountUser`) on your custom execution service account so Dataform can impersonate it during workflow runs. When triggering Dataform runs manually in the Google Cloud console on RLS-governed tables, always execute as this configured service account rather than **Run with my user credentials** (which fails with `Access Denied: User does not have full access to table ...
    due to row access policies` because `cortex_pipeline_sa_bypass` applies only to the pipeline service account).
- **End users and service accounts querying protected tables** : For every reader persona, grant [BigQuery Job User](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.jobUser) (`roles/bigquery.jobUser`) on the query project, [BigQuery Data Viewer](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquery.md.txt#bigquery.dataViewer) (`roles/bigquery.dataViewer`) on the target dataset or table, and `roles/bigquery.dataViewer` on any `${ref(...)}` entitlement lookup table or dataset referenced by an RLS policy subquery. Include the principal in the row access policy's `grantees` list so BigQuery implicitly grants the system-managed `roles/bigquery.filteredDataViewer` role on that specific policy. For CLS-tagged columns, grant one of the following based on access level:
  - **Unmasked scoped reader** : Grant [Fine-Grained Reader](https://docs.cloud.google.com/iam/docs/roles-permissions/datacatalog.md.txt#datacatalog.categoryFineGrainedReader) (`roles/datacatalog.categoryFineGrainedReader`) on the required policy tags to read unmasked column values for permitted rows.
  - **Masked reader (dynamic data masking)** : Attach a BigQuery data policy to the policy tag by using the BigQuery Data Policy API (`bigquerydatapolicy.googleapis.com`) and grant [Masked Reader](https://docs.cloud.google.com/iam/docs/roles-permissions/bigquerydatapolicy.md.txt#bigquerydatapolicy.maskedReader) (`roles/bigquerydatapolicy.maskedReader`) on that data policy. Readers receive dynamically masked values (such as `SHA-256` or default masking values) for permitted rows instead of `403 Access Denied` errors. For role precedence, see [How Masked Reader and Fine-Grained Reader roles interact](https://docs.cloud.google.com/bigquery/docs/column-data-masking-intro.md.txt#role-interaction).
  - **Unauthorized column reader** : Principals who hold neither Fine-Grained Reader nor Masked Reader can query tables when their `SELECT` clause excludes CLS-tagged columns; querying a CLS-tagged column returns `403 Access Denied`.

> [!CAUTION]
> **Caution:** Don't grant `roles/bigquery.filteredDataViewer` directly on a project, dataset, or table IAM policy. This system-managed role grants `bigquery.rowAccessPolicies.getFilteredData` implicitly per row access policy to principals listed in `grantees` (`GRANT TO`). Granting it directly inherits access across **every** row access policy in that scope---including `cortex_pipeline_sa_bypass` (`FILTER USING (TRUE)`)---which bypasses row-level filtering.

## Configuration schema reference

All security configuration keys use strict `camelCase` naming; unknown or
misspelled keys are rejected at schema validation time.

### Tier 1: Global security (`data.security`)

Configure global security settings under `data.security` in `config.yaml`:

| Field | Type | Default | Description |
| `enabled` | `boolean` | `true` | Global switch for declarative security. When `false`, skips Tier 2 and Tier 3 resolution workspace-wide and skips Data Catalog pre-flight checks during `cortex-deploy`, `cortex-build-and-deploy` (`type: dataform`), `cortex-demo`, and `cortex-apply-security` (`cortex-build` doesn't run Data Catalog pre-flight checks, and still rejects explicit Tier 3 `security` blocks on `view` models even when `data.security` is omitted or `enabled: false`). Running `uv run cortex-apply-security` with `data.security.enabled: false` tears down previously applied Cortex Framework column policy tags and managed row access policies in BigQuery; deleting the `data.security` block instead exits as a no-op and leaves existing tags and policies attached. |
| `autoGrantDataformServiceAccount` | `boolean` | `true` | Automatically appends the `cortex_pipeline_sa_bypass` row access policy on tables with active RLS so the Dataform execution service account can read and transform upstream tables. |
| `pipelineServiceAccount` | `string` or `null` | `null` | Fallback service account email used for `cortex_pipeline_sa_bypass` when a `type: dataform` target omits `targetSettings.serviceAccount` (for example, the default Dataform service agent `service-PROJECT_NUMBER@gcp-sa-dataform.iam.gserviceaccount.com`), or when no enabled `type: dataform` target exists (for example, `type: git`-only GitOps configurations) while any table has active RLS policies and `autoGrantDataformServiceAccount` is `true`. Accepts a bare email or an optional `serviceAccount:` prefix (stripped automatically, matching `targetSettings.serviceAccount`). Schema validation rejects `allAuthenticatedUsers` and other IAM member prefixes such as `user:` or `group:`. |
| `policyTags` | `map<string, string>` | `{}` | Logical alias-to-URI map for Data Catalog policy tags. Alias keys can't be empty or start with `projects/`. Each value must match `projects/<project>/locations/<location>/taxonomies/<taxonomy>/policyTags/<policy_tag>`. |
| `domainRules` | `list<object>` | `[]` | Ordered list of Tier 2 domain security rules. Each rule must have a unique `name` (case-insensitive). |
|---|---|---|---|

### Tier 2: Domain rules (`data.security.domainRules[]`)

Each entry in `data.security.domainRules` defines module targeting and
associated CLS or RLS rules:

| Field | Type | Default | Description |
| `name` | `string` | Required | Unique identifier for the domain rule (case-insensitive across `domainRules`). |
| `enabled` | `boolean` | `true` | Enables or disables this domain rule. Set to `false` on Day 2 to tear down column policy tags and row filters managed by this rule across matching tables (unless kept active by another rule or Tier 3 override). |
| `modulePaths` | `list<string>` or `null` | `null` | Non-empty list of unique, case-sensitive `fnmatch` glob patterns matched against each module's dot-separated `modulePath` (for example, `cortex.sap.*` or `cortex.sfdc.products.*`). |
| `moduleIds` | `list<string>` or `null` | `null` | Non-empty list of unique exact `moduleId` values (for example, `sap_accounts_payable` or `erp`). |
| `columnTags` | `list<object>` | `[]` | Column-level policy tag matching rules. |
| `mandatoryRowFilters` | `list<object>` | `[]` | Row-level access filters applied when required columns exist on a table. |
|---|---|---|---|

At least one of `modulePaths` or `moduleIds` must be specified on every domain
rule. If you specify **both** `modulePaths` and `moduleIds`, they are combined
with logical **AND**---a module must satisfy both filters to match the rule.

#### `columnTags[]` fields

| Field | Type | Default | Description |
| `policyTag` | `string` | Required | Alias defined in `data.security.policyTags` or a full Data Catalog policy tag URI. Validated against `policyTags` whenever the rule is enabled. |
| `enabled` | `boolean` | `true` | Enables or disables this column tag rule. Set to `false` on Day 2 to clear policy tags managed by this rule on matching columns (unless kept active by another rule or Tier 3 override). |
| `allowTableOverride` | `boolean` | `false` | When `false`, Tier 3 table configurations can't clear or replace this policy tag, and can't opt the table out with `security.enabled: false`. |
| `matchExact` | `list<string>` | `[]` | Unique (case-insensitive) BigQuery column identifiers (`^[a-zA-Z_][a-zA-Z0-9_]{0,299}$`), matched case-insensitively. |
| `matchSuffix` | `list<string>` | `[]` | Unique (case-insensitive) non-empty column name suffixes (for example, `_stcd1` or `_telf1`), matched case-insensitively. |
|---|---|---|---|

At least one of `matchExact` or `matchSuffix` must be non-empty.

#### `mandatoryRowFilters[]` fields

| Field | Type | Default | Description |
| `name` | `string` | Required | BigQuery row access policy identifier (`^[a-zA-Z_][a-zA-Z0-9_]{0,255}$`), unique case-insensitively within the domain rule. Can't be `cortex_pipeline_sa_bypass`. |
| `enabled` | `boolean` | `true` | Enables or disables this row filter. Set to `false` on Day 2 to drop this policy across matching tables. |
| `allowTableOverride` | `boolean` | `false` | When `false`, the filter is always conjoined (`AND`) into every Tier 3 row access policy on matching tables regardless of `inheritDomainFilter`, and blocks table-level opt-out (`security.enabled: false`). |
| `filterPredicate` | `string` or `null` | `null` | BigQuery SQL boolean expression (supports `${ref(...)}` lookup-table tokens). Required and non-empty when `enabled: true`. |
| `applyIfColumnsExist` | `list<string>` | Required | Non-empty list of unique (case-insensitive) column identifiers. The filter applies to a table only when **all** listed columns exist in the table's schema (matched case-insensitively). |
| `defaultGrantees` | `list<string>` | `[]` | Non-empty list of unique BigQuery RLS grantees required when `enabled: true`. Accepted formats: `user:`, `group:`, `serviceAccount:`, `domain:`, `principal://`, `principalSet://`, or `allAuthenticatedUsers`. Email and domain principals (`user:`, `group:`, `serviceAccount:`, and `domain:`) are compared case-insensitively for duplicate detection and Tier 2 `defaultGrantees` intersection; `principal://`, `principalSet://`, and the literal `allAuthenticatedUsers` are case-sensitive. |
|---|---|---|---|

### Tier 3: Table overrides (`table_settings.yaml` or `inlineTableSettings`)

Configure table-level security under `target.security` (for foundations with
`external: false`) or root-level `security` (for data products):

| Field | Type | Default | Description |
| `enabled` | `boolean` | `true` | When `false`, opts the table out of security if permitted by Tier 2 `allowTableOverride` rules and serializes `{"enabled": false}` (along with any `clearedColumnTags`) to trigger Day-2 teardown---dropping row access policies and clearing Cortex Framework-managed column policy tags. Rejected on `view` models. |
| `columnTags` | `map<string, object>` | `{}` | Map of unique (case-insensitive) `<column_name>: { policyTag: <alias | uri | null> }`. Use explicit `null` to clear an overridable Tier 2 policy tag or remove a previously attached Tier 3 tag on Day 2 (blank strings are rejected). Columns are validated against the table's known schema. |
| `rowAccessPolicies` | `list<object>` | `[]` | Table-specific row access policies. Policy names must be unique (case-insensitive) per table. |
|---|---|---|---|

#### `rowAccessPolicies[]` fields

| Field | Type | Default | Description |
| `name` | `string` | Required | Valid BigQuery RLS policy identifier (`^[a-zA-Z_][a-zA-Z0-9_]{0,255}$`). Can't be `cortex_pipeline_sa_bypass`. |
| `enabled` | `boolean` | `true` | Enables or disables this table-level policy. Set to `false` on Day 2 to drop the policy without opening a fail-open window on sibling policies (and use `enabled: false` tombstones instead of deleting the YAML entry when coexisting with external row access policies under `autoGrantDataformServiceAccount: false`). |
| `inheritDomainFilter` | `boolean` | `true` | When `true`, conjoins (`AND`) applicable overridable Tier 2 filters into this policy. When `false`, omits overridable Tier 2 filters (fails with `CortexConfigError` if no overridable Tier 2 filters are in scope). Non-overridable Tier 2 filters (`allowTableOverride: false`) are **always** conjoined regardless of this setting. |
| `grantees` | `list<string>` | `[]` | Non-empty list of unique valid BigQuery RLS grantees required when `enabled: true`. Email and domain principals (`user:`, `group:`, `serviceAccount:`, and `domain:`) are compared case-insensitively for duplicate detection; `principal://`, `principalSet://`, and the literal `allAuthenticatedUsers` are case-sensitive. |
| `filterPredicate` | `string` or `null` | `null` | BigQuery SQL boolean expression (supports `${ref(...)}` tokens). Required and non-empty when `enabled: true`. |
|---|---|---|---|

## Configuration examples

The following examples show how to combine Tier 1 global policy tags, Tier 2
domain rules, and Tier 3 table overrides for SAP and Salesforce workloads.

### SAP company-code RLS and vendor PII CLS

This example applies mandatory company-code (`BUKRS`) row filtering across SAP
finance modules using a dynamic entitlement lookup table, tags SAP vendor tax
and telephone columns with a Data Catalog policy tag, and
demonstrates Tier 3 configuration on both a foundation table (`bkpf`) and a data
product table (`accounts_payable`).

#### Configure Tiers 1 and 2 in `config.yaml`

```yaml
data:
  bigQueryLocation: US
  datasets:
    - id: security_entitlements
      projectId: GOVERNANCE_PROJECT_ID
      datasetId: sap_entitlements
  security:
    enabled: true
    autoGrantDataformServiceAccount: true
    pipelineServiceAccount: dataform-runner@TARGET_PROJECT_ID.iam.gserviceaccount.com
    policyTags:
      pii_tax_id: projects/TAXONOMY_PROJECT_ID/locations/us/taxonomies/TAXONOMY_ID/policyTags/TAX_ID_TAG_ID
      pii_contact: projects/TAXONOMY_PROJECT_ID/locations/us/taxonomies/TAXONOMY_ID/policyTags/CONTACT_TAG_ID
    domainRules:
      - name: sap_vendor_pii_cls
        modulePaths:
          - "cortex.sap.foundations.*"
          - "cortex.sap.products.vendors"
        columnTags:
          - policyTag: pii_tax_id
            allowTableOverride: false
            matchExact:
              - stcd1
              - stcd2
            matchSuffix:
              - _stcd1
              - _stcd2
          - policyTag: pii_contact
            allowTableOverride: true
            matchExact:
              - telf1
            matchSuffix:
              - _telf1
      - name: sap_finance_company_code_rls
        modulePaths:
          - "cortex.sap.foundations.*"
          - "cortex.sap.products.accounting_documents"
        mandatoryRowFilters:
          - name: sap_bukrs_entitlement
            allowTableOverride: false
            applyIfColumnsExist:
              - bukrs
            defaultGrantees:
              - group:sap-finance-analysts@DOMAIN
            filterPredicate: >-
              bukrs IN (
                SELECT company_code
                FROM ${ref("security_entitlements", "user_company_codes")}
                WHERE user_email = SESSION_USER()
              )
          - name: sap_product_bukrs_entitlement
            allowTableOverride: false
            applyIfColumnsExist:
              - company_code_bukrs
            defaultGrantees:
              - group:sap-finance-analysts@DOMAIN
            filterPredicate: >-
              company_code_bukrs IN (
                SELECT company_code
                FROM ${ref("security_entitlements", "user_company_codes")}
                WHERE user_email = SESSION_USER()
              )
```

Replace the following:

- `GOVERNANCE_PROJECT_ID`: Google Cloud project ID hosting the `sap_entitlements` lookup dataset.
- `TARGET_PROJECT_ID`: Google Cloud project ID for the Dataform execution service account.
- `TAXONOMY_PROJECT_ID`: Google Cloud project ID containing the Data Catalog policy tag taxonomy.
- `TAXONOMY_ID`: ID of your Data Catalog policy tag taxonomy.
- `TAX_ID_TAG_ID`: Policy tag ID for vendor tax identifier columns.
- `CONTACT_TAG_ID`: Policy tag ID for vendor contact columns.
- `DOMAIN`: Google Workspace or Cloud Identity domain for the grantee group.

#### Add a Tier 3 foundation override (`table_settings.yaml`)

For data foundations (`cortex.sap.foundations.sap`), place `security` strictly
under `target.security`. Because a custom foundation `table_settings.yaml` file
replaces `table_settings.default.yaml` instead of merging per table, copy
`table_settings.default.yaml` and edit the existing `bkpf` entry under
`common:`:

```yaml
common:
  - source:
      tableName: bkpf
    target:
      security:
        rowAccessPolicies:
          - name: bkpf_regional_controllers
            inheritDomainFilter: true
            grantees:
              - group:emea-controllers@DOMAIN
            filterPredicate: "gjahr >= '2025'"
```

Replace `DOMAIN` with your Google Workspace or Cloud Identity domain.

Because `sap_bukrs_entitlement` sets `allowTableOverride: false`, the resolved
predicate for `bkpf_regional_controllers` automatically conjoins the mandatory
company-code entitlement check with `gjahr >= '2025'`.

#### Add a Tier 3 data product override (`table_settings.yaml`)

For data products (such as `cortex.sap.products.accounts_payable` on S/4HANA),
place `security` strictly at the table item root:

```yaml
s4:
  accounts_payable:
    materializationType: incremental
    security:
      columnTags:
        vendor_lifnr:
          policyTag: pii_contact
      rowAccessPolicies:
        - name: ap_s4_company_code_access
          grantees:
            - group:ap-team@DOMAIN
          filterPredicate: >-
            company_code_rbukrs IN (
              SELECT company_code
              FROM ${ref("security_entitlements", "user_company_codes")}
              WHERE user_email = SESSION_USER()
            )
```

Replace `DOMAIN` with your Google Workspace or Cloud Identity domain.

### Salesforce contact PII CLS and regional RLS

This example protects contact email and phone columns across Salesforce
foundation and product tables and restricts Salesforce `contacts` product rows
by mailing country.

#### Configure Tiers 1 and 2 in `config.yaml`

```yaml
data:
  bigQueryLocation: US
  security:
    enabled: true
    autoGrantDataformServiceAccount: true
    policyTags:
      sfdc_pii: projects/TAXONOMY_PROJECT_ID/locations/us/taxonomies/TAXONOMY_ID/policyTags/SFDC_PII_TAG_ID
    domainRules:
      - name: sfdc_contact_pii_cls
        modulePaths:
          - "cortex.sfdc.foundations.*"
          - "cortex.sfdc.products.contacts"
        columnTags:
          - policyTag: sfdc_pii
            allowTableOverride: false
            matchExact:
              - email
              - phone
              - mobilephone
              - mobile_phone
              - homephone
              - home_phone
```

Replace the following:

- `TAXONOMY_PROJECT_ID`: Google Cloud project ID containing the Data Catalog policy tag taxonomy.
- `TAXONOMY_ID`: ID of your Data Catalog policy tag taxonomy.
- `SFDC_PII_TAG_ID`: Policy tag ID for Salesforce contact PII columns.

#### Add a Tier 3 data product override (`table_settings.yaml`)

For `cortex.sfdc.products.contacts`, place `security` at the table item root:

```yaml
contacts:
  materializationType: incremental
  security:
    rowAccessPolicies:
      - name: sfdc_contacts_emea_sales
        grantees:
          - group:emea-sales@DOMAIN
        filterPredicate: "mailing_country IN ('DE', 'FR', 'GB', 'NL')"
```

Replace `DOMAIN` with your Google Workspace or Cloud Identity domain.

## Precedence rules and governance guardrails

`security_resolver` enforces strict governance invariants during
`uv run cortex-build` so misconfigurations fail early rather than leaving data
unprotected.

### RLS composition and override precedence

- **Multiple Tier 2 filters without Tier 3 policies** : When two or more Tier 2 `mandatoryRowFilters` apply to the same table and no enabled Tier 3 `rowAccessPolicies` exist, Cortex Framework conjoins them with `AND` into a single row access policy named `<name1>_and_<name2>` (truncated with an 8-character SHA-256 suffix if the combined name exceeds 200 characters) granting the **intersection** of `defaultGrantees` across all matched filters. If the matched filters declare disjoint `defaultGrantees`, the build fails with `CortexConfigError` until you align `defaultGrantees` or define explicit Tier 3 `rowAccessPolicies` on that table.
- **Combining Tier 2 and Tier 3 policies** : When at least one enabled Tier 3 `rowAccessPolicies` entry is defined on a table, standalone Tier 2 policy emission is suppressed and each Tier 3 policy is evaluated as follows:
  - **Non-overridable Tier 2 filters (`allowTableOverride: false`)** : Always conjoined (`AND`) into every emitted Tier 3 policy, regardless of `inheritDomainFilter`.
  - **Overridable Tier 2 filters (`allowTableOverride: true`)** : Conjoined (`AND`) when `inheritDomainFilter: true`, or omitted when `inheritDomainFilter: false`. Setting `inheritDomainFilter: false` when no overridable Tier 2 filters are in scope raises `CortexConfigError`.
- **Multiple Tier 3 policies on the same table** : BigQuery evaluates multiple row access policies on the same table using logical `OR` per principal. Adding a second permissive or `inheritDomainFilter: false` Tier 3 policy widens row visibility for any overlapping grantees.

### CLS override and conflict resolution

- **Adding new tags**: Tier 3 can always attach a policy tag to a column that isn't matched by any Tier 2 rule.
- **Replacing or clearing Tier 2 tags** : Replacing a Tier 2 policy tag or clearing it with `policyTag: null` succeeds only if **every** matching Tier 2 `columnTags` rule for that column sets `allowTableOverride: true`. Otherwise, the build fails with `CortexConfigError`.
- **Conflicting Tier 2 tags** : If multiple enabled Tier 2 rules match the same column with different policy tag URIs, the build fails with `CortexConfigError` unless an allowed Tier 3 override explicitly selects the winning tag.

### Coarse table opt-out (`security.enabled: false`)

Setting `security.enabled: false` on a table opts that table out of all
overridable security policies and serializes `{"enabled": false}` (along with
any `clearedColumnTags`) to trigger Day-2 teardown---dropping all row access
policies and clearing Cortex Framework-managed column policy tags
on that table. If any active non-overridable (`allowTableOverride: false`) Tier
2 CLS or RLS rule is in scope for that table, the build fails with
`CortexConfigError`.

### Zero-match Tier 2 build error

To prevent silent security gaps caused by typos in `modulePaths`, `moduleIds`,
`matchExact`, `matchSuffix`, or `applyIfColumnsExist`,
`SecurityResolutionTracker.validate_tier2_matches()` verifies at the end of
`uv run cortex-build` that **every** enabled Tier 2 `domainRules` entry---and
every enabled `columnTags` and `mandatoryRowFilters` rule inside it---matched at
least one enabled materialized table or column across the workspace. Any
unmatched enabled Tier 2 rule (or an enabled `domainRules` entry with empty
`columnTags` and `mandatoryRowFilters` lists) fails the build with
`CortexConfigError`. An enabled `domainRules` entry whose declared `columnTags`
and `mandatoryRowFilters` entries all set `enabled: false` passes validation to
support Day-2 teardown.

### Downstream propagation warnings

At the end of `uv run cortex-build`,
`SecurityResolutionTracker.validate_downstream_propagation()` inspects
materialized (`table` and `incremental`) data product tables and logs build-time
warnings when an ungoverned or partially governed table reads from a CLS- or
RLS-governed upstream table. Propagation analysis traces dependencies
transitively through intermediate `view` models and intra-module `ctx.ref`
references so you can spot downstream tables that copy governed data without
matching policies.

### Fail-closed metadata and materialization checks

- **Missing column metadata** : When column metadata for a table is unavailable or empty, the resolver fails closed with `CortexConfigError` for:
  - Any active Tier 2 rule targeting a data foundation table.
  - Any mandatory (`allowTableOverride: false`) Tier 2 rule targeting a data product table.
  - Any Tier 3 RLS policy with `inheritDomainFilter: true` when Tier 2 row filters are in scope for the module.
- **Unknown `materializationType`** : If a table's `materializationType` can't be determined while Tier 2 or Tier 3 security is in scope, the build fails closed with `CortexConfigError`.
- **BigQuery `view` models** : BigQuery doesn't support CLS policy tags or RLS policies directly on standard views. Tier 2 domain rules automatically skip `view`-materialized tables, while any explicit Tier 3 `security` block (including `enabled: false`, `columnTags`, or `rowAccessPolicies`) on a `view` raises `CortexConfigError`. Views automatically enforce upstream table RLS and dynamic data masking for querying principals, whereas downstream materialized (`table` or `incremental`) models don't automatically inherit upstream policies.

## Dataform pipeline service account bypass

When a table has active row access policies, BigQuery filters
rows for all readers---including downstream Dataform
transformations---unless a row access policy grants the pipeline service account
access.

When `data.security.autoGrantDataformServiceAccount` is `true` (the default)
and at least one active RLS policy resolves on a table,
Cortex Framework automatically appends a reserved row access
policy:

- **Policy name** : `cortex_pipeline_sa_bypass` (reserved; user-defined Tier 2 and Tier 3 policies can't use this name, case-insensitive)
- **Predicate** : `TRUE`
- **Grantees** : `["serviceAccount:<sa>", ...]`

Cortex Framework resolves the execution service account per
enabled `type: dataform` deployment target using the following precedence:

1. `deployment.targets[].targetSettings.serviceAccount` (accepts a bare email or an optional `serviceAccount:` prefix, which validation strips)
2. `data.security.pipelineServiceAccount` (global fallback; also accepts a bare email or an optional `serviceAccount:` prefix, which validation strips)

When `deployment.targets[].targetSettings.serviceAccount` is omitted on a
Dataform target, Dataform runs workflows as the
default service agent
`service-PROJECT_NUMBER@gcp-sa-dataform.iam.gserviceaccount.com`.
Set `data.security.pipelineServiceAccount` to that service agent email (or to
your CI/CD Dataform runner service account for `type: git`-only
targets) so `uv run cortex-build` can populate `cortex_pipeline_sa_bypass`.

If no enabled `type: dataform` deployment target exists (for example, in a
`type: git`-only GitOps configuration), Cortex Framework uses
`data.security.pipelineServiceAccount`. Whenever any table resolves active RLS
policies and `autoGrantDataformServiceAccount` is `true`, `uv run cortex-build`
fails with `CortexConfigError` if no service account can be resolved (either for
an enabled `type: dataform` target or because no enabled `type: dataform` target
exists and `pipelineServiceAccount` is unset), unless you set
`autoGrantDataformServiceAccount: false`.

## Dynamic entitlement lookup tables

Row filter predicates can reference BigQuery entitlement lookup
tables using `${ref(...)}` syntax instead of hardcoding physical project and
dataset names.

### Syntax and resolution order

Quote all `${ref(...)}` arguments as identifier literals matching
`[A-Za-z0-9_.:-]+`:

- **2-argument form** : `${ref("binding_or_dataset", "table")}`
  1. First checks the module `dependencyBindings` key and resolves against the bound foundation (using `dataSourceId` if external, or `dataTargetId` for managed foundations), bound data product, or bound catalog.
  2. Falls back to the logical dataset ID in `data.datasets` and resolves to that dataset's configured `projectId` and `datasetId`.
- **3-argument form** : `${ref("project_id", "dataset_id", "table")}` --- resolves directly to the specified fully qualified table coordinates.

All resolved references are rewritten into canonical 3-argument
`${ref("project", "dataset", "table")}` form for Dataform.

### View rejection, DAG retention, and `declare()` generation

- **Materialized, non-self-referencing tables only** : BigQuery prohibits referencing views, external tables, wildcard tables, or the protected table itself inside row access policy subqueries, and requires both the policy creator (Dataform execution service account) and every querying end-user principal to hold `bigquery.tables.getData` (`roles/bigquery.dataViewer`) on the referenced lookup table or dataset. During `uv run cortex-build`, pointing `${ref(...)}` at a `view`-materialized product table, a pruned foundation table, or the protected table itself fails the build with `CortexConfigError`.
- **Foundation lattice-pruning retention** : `WorkspaceResolver` scans active Tier 2 and Tier 3 RLS predicates and retains any referenced foundation tables in `required_tables` so they aren't pruned from the Dataform DAG even if no SQL transformation selects from them directly.
- **External source declarations** : Entitlement tables outside the generated DAG (such as tables in a dedicated governance dataset) are automatically added to `ctx.sources` and emitted as `declare({ database, schema, name })` entries under `definitions/sources/*_sources.js` so Dataform resolves `${ref(...)}` cleanly at compile time.

### Subquery row access policy limitations

When authoring row access policy `filterPredicate` expressions that reference
entitlement lookup tables by using `${ref(...)}`, keep these
BigQuery platform constraints in mind:

- **BigQuery Storage Read API limitation** : Tables governed by row access policies whose predicates contain subqueries (`IN (SELECT ...)` or `EXISTS (SELECT ...)`) can't be read directly through the Storage Read API (used by Spark or Managed Service for Apache Spark connectors, Dataflow `DIRECT_READ`, and high-throughput Arrow or Avro readers) unless the caller holds unconditional `TRUE` row access. Otherwise, queries must run as standard BigQuery SQL jobs.
- **Partition and cluster pruning bypass** : BigQuery evaluates subquery-based row access policies dynamically at query runtime and can't use the subquery result to prune partitions or clusters on the governed base table. Include explicit `WHERE` filters on partition and cluster columns in end-user queries and dashboards for partitioned tables (such as `universal_journal_entry_line_items` partitioned by `posting_date_in_the_document_budat`) to control bytes scanned.

## Custom foundation builder SDK hooks

Custom foundation builder plugins that subclass `FoundationBuilder` from
`common.sdk` must opt in explicitly to support declarative table security:

1. Declare `supports_table_security: ClassVar[bool] = True` on the builder subclass. `__init_subclass__` validates that `render_table_js()` accepts a `security` parameter (or `**kwargs`) and raises `TypeError` at class definition time if it doesn't.
2. Override `get_table_columns(self, *, node, table_config, provider)` if your metadata provider doesn't expose a standard mapping keyed by the resolved source table name. Return a `Sequence[str]` of column names (or `None` when unavailable).
3. Accept `security=None` in `render_table_js(...)` and serialize **every** key of the received `security` dictionary into the generated JavaScript output.

The `FoundationBuilder` base class enforces fail-closed invariants for plugins:

- If security resolves on a table (either active CLS or RLS policies, or an explicit `target.security` override such as `enabled: false`) and the builder sets `supports_table_security = False`, the build fails with `CortexConfigError`.
- The `security` argument passed to `render_table_js()` is tracked using `_TrackedSecurityDict`. If `render_table_js()` returns JavaScript without reading all keys of `security`, the build fails with `CortexConfigError`.

## Runtime enforcement, reconciliation, and Day-2 teardown

Cortex Framework enforces resolved security configurations across
two coordinated layers: generated Dataform runtime helpers that
run zero-fail-open refreshes and RLS DDL during workflow runs, and
`SecuritySchemaReconciler`, which reconciles BigQuery column
policy tags and stale row access policies through BigQuery APIs.

### Runtime helpers and zero-fail-open refreshes

Standard BigQuery `CREATE OR REPLACE TABLE` statements drop
attached row access policies and column policy tags, which can expose protected
rows or columns between table replacement and policy re-attachment. To prevent
this fail-open window, Cortex Framework wraps active governed
foundation and data product tables (`table` and `incremental`) in
zero-fail-open Dataform `operate(...).hasOutput(true)` scripts
that update data in place:

- **Day-0 cold start** : Drops any legacy `VIEW` or `MATERIALIZED VIEW` at the target name, creates an empty table (`WHERE FALSE`) with configured partitioning, clustering, and options, attaches active row access policies while zero rows exist, and then runs `INSERT INTO`.
- **Day-2 full refresh** : Stages the query in a session-private `TEMP` table, synchronizes schema changes against `INFORMATION_SCHEMA.COLUMNS` using a zero-row probe (`ADD COLUMN IF NOT EXISTS` and coercible `SET DATA TYPE` before RLS DDL, and `DROP COLUMN IF EXISTS` after stale RLS teardown), runs RLS DDL, and swaps table contents inside a transaction (`BEGIN TRANSACTION; DELETE ...; INSERT INTO ...; COMMIT TRANSACTION;`).
- **Day-2 incremental refresh** : Runs pre-DML schema synchronization and applies or updates active row access policies before `MERGE` or `INSERT`, preserving existing row access policies and column policy tags in place. Level-2 `STRUCT` and `ARRAY<STRUCT>` subfield evolution runs in place without `CREATE OR REPLACE TABLE` under `onSchemaChange: EXTEND` (which rejects subfield removals) and `SYNCHRONIZE`, with automatic recovery of stranded `_cortex_evol_%` backup columns. Subfield changes at nesting depth 3 or deeper, incompatible subfield type narrowing, and `STRUCT` changes on CLS-tagged or key/partition/cluster columns fail closed with explicit recovery guidance.
- **Forced governed full rebuild** : Because governed incremental models and SAP foundation CDC models compile as Dataform `operations`, Dataform's native `--full-refresh` flag alone doesn't switch them out of incremental `MERGE` mode. When running the Dataform CLI directly (or compiling manually in the Google Cloud console or GitOps CI/CD), pass `--full-refresh --vars=cortex_full_refresh=true` (or `1`, `all`, `*`, or a shell-quoted semicolon-, pipe-, or space-separated list of table identifiers such as `--vars='cortex_full_refresh=TABLE_1;DATASET_ID.TABLE_2'`) to rebuild governed incremental models without `CREATE OR REPLACE TABLE`. Avoid commas inside `--vars` on the CLI because Dataform splits separate variable pairs on commas. Programmatic `DataformClient.create_compilation_result()` and `create_workflow_invocation()` calls with `fully_refresh_incremental_tables_enabled=True` inject `cortex_full_refresh=true` automatically.
- **Compiled Dataform action type in unit tests** : Active RLS- or CLS-governed `table` and `incremental` models compile in `compilation_graph.json` under `operations` (`hasOutput: true`) rather than `tables`. Custom `pytest` compilation tests that inspect governed models should check both `tables` and `operations` entries.

### Row access policy DDL order and Day-2 teardown

During `uv run cortex-build`, `security_resolver` emits `clearedColumnTags` and
`droppedRowAccessPolicies` alongside active `columnTags` and
`rowAccessPolicies` in each table's serialized `security` payload so Day-2
teardown stays driven by your YAML configuration.

At runtime, `security_helper.buildSecurityPostOpsStatements()` emits RLS DDL in
strict zero-fail-open order:

1. Create or replace active policies first. Emits `CREATE OR REPLACE ROW ACCESS POLICY` for every active policy (including `cortex_pipeline_sa_bypass` when `autoGrantDataformServiceAccount` is `true`) before dropping any superseded policy.
2. Drop disabled or superseded policies. Drops each policy listed in `droppedRowAccessPolicies` using `DROP ROW ACCESS POLICY IF EXISTS`, wrapped in an exception handler that falls back to `DROP ALL ROW ACCESS POLICIES ON` if BigQuery rejects dropping the last remaining policy on the table.
3. Drop all policies on full opt-out. On non-cold-start runs, when `security.enabled: false` is set or when no active policies remain alongside `droppedRowAccessPolicies`, emits `DROP ALL ROW ACCESS POLICIES ON` directly regardless of `autoGrantDataformServiceAccount`. If you coexist with out-of-band external row access policies under `autoGrantDataformServiceAccount: false`, running the Dataform workflow with `security.enabled: false` or with the last Cortex Framework row access policy disabled drops those external policies too.

### BigQuery schema and policy reconciliation

BigQuery SQL `ALTER COLUMN ... SET OPTIONS` doesn't accept
Data Catalog `policy_tags`, Dataform skips
`setMetadata` on `operations` actions (used by zero-fail-open adapters and SAP
CDC scripts), and Dataform ignores empty
`bigqueryPolicyTags: []` arrays when clearing previously attached policy tags.
To cover these gaps, `SecuritySchemaReconciler`
(`src/common/services/security_reconciler.py`) reconciles live table schemas
and row access policies directly through BigQuery APIs when you
run [`uv run cortex-apply-security`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-apply-security.md.txt):

- **Selective column policy tag patching** : Patches `TableFieldSchema.policyTags` by using the BigQuery `tables.patch` API to attach or update Cortex Framework-managed policy tag URIs and clear tags removed through `enabled: false` or `policyTag: null`, while leaving external, non-Cortex Framework policy tags untouched. If a Tier 3 `columnTags` entry specifies a raw policy tag URI that isn't also declared in `data.security.policyTags` or a Tier 2 rule, clear it with `policyTag: null` before deleting the YAML entry; deleting the entry directly removes that URI from the managed tag set and leaves the tag attached in BigQuery.
- **Availability-safe row access policy cleanup** : Lists live policies by using `rowAccessPolicies.list` and reconciles them against your configured policy set:
  - If `uv run cortex-apply-security` runs before Dataform has materialized a table or created a replacement policy, it logs a warning and defers dropping stale policies on that table until all configured policies are confirmed live in BigQuery.
  - All BigQuery API failures during reconciliation (`get_table`, `update_table`, `query`, and `rowAccessPolicies.list`---including authentication, `NotFound`, `BadRequest`, `Forbidden`, and transient or network errors) fail closed with `CortexGcpError` and remediation hints instead of silently skipping teardown.
  - When `cortex_pipeline_sa_bypass` is **present** (`autoGrantDataformServiceAccount: true`, or during a transition run where `cortex_pipeline_sa_bypass` is still live on the table alongside remaining configured policies), Cortex Framework owns the table's row access policy set and drops live policies outside the configured set. When zero configured policies remain on a table carrying `cortex_pipeline_sa_bypass`, reconciliation runs `DROP ALL ROW ACCESS POLICIES ON` so no orphaned bypass policy locks out end-user readers.
  - When `cortex_pipeline_sa_bypass` is **absent** (`autoGrantDataformServiceAccount: false`), `SecuritySchemaReconciler` drops **only known Cortex Framework-managed policy IDs** , even while other Cortex Framework policies remain active, leaving out-of-band external policies untouched and logging a `WARNING` that lists the preserved unrecognized live policies. Because BigQuery `RowAccessPolicy` resources don't carry labels or descriptions, retire obsolete Cortex Framework policies by setting `enabled: false` in YAML (tombstones) instead of deleting the YAML entry when coexisting with external row access policies.

> [!CAUTION]
> **Caution:** Don't delete the top-level `data.security` block from `config.yaml` before tearing down previously applied governance. When `data.security` is omitted, `uv run cortex-apply-security` exits with status `0` as a no-op and leaves existing column `policyTags` and row access policies (including `cortex_pipeline_sa_bypass`) attached in BigQuery. Set `data.security.enabled: false`, run your Dataform workflow and `uv run cortex-apply-security`, and then remove the block.

#### End-to-end deployment and reconciliation sequence

`uv run cortex-deploy` and `uv run cortex-build-and-deploy` stage compiled
Dataform definitions to Dataform or Git without
modifying live BigQuery table schemas or row access policies.
When the workspace includes security reconciliation candidates, both commands
log a `WARNING` reminding you that column `policyTags` on tables materialized
for the first time and on added columns remain unattached until
`uv run cortex-apply-security` runs after the Dataform workflow.
Follow this sequence for **both** `type: dataform` and `type: git` targets:

1. Build and deploy workspace definitions:

   ```bash
   uv run cortex-build --config config/config.yaml
   uv run cortex-deploy --config config/config.yaml
   ```

   Alternatively, run
   `uv run cortex-build-and-deploy --config config/config.yaml`.
2. Run the Dataform workflow:

   - For **`type: dataform` targets**, trigger the workflow from the Google Cloud console, the Dataform API, or your orchestration schedule.
   - For **`type: git` targets**, merge and push the generated repository changes, then run the Dataform pipeline by using your CI/CD runner or a Dataform release configuration.

   During workflow execution, zero-fail-open `operate(...).hasOutput(true)`
   scripts create Day-0 tables empty (`WHERE FALSE`), attach active
   `CREATE OR REPLACE ROW ACCESS POLICY` statements while zero rows exist, and
   then insert or merge rows.
3. Apply column policy tags and clean up stale row access policies:

   ```bash
   # Optional: preview planned BigQuery updates in read-only mode
   uv run cortex-apply-security --config config/config.yaml --dry-run

   # Apply column policy tags and drop stale or disabled row access policies
   uv run cortex-apply-security --config config/config.yaml
   ```
4. On initial deployments (and before exposing added CLS-governed columns),
   grant end-user read access to target datasets only after step 3 attaches
   column `policyTags`.

After column policy tags are attached, steady-state scheduled
Dataform refreshes (`table` and `incremental`) preserve existing
`policyTags` in place by using transactional `DELETE` and `INSERT` or `MERGE`
operations. Re-run `uv run cortex-apply-security` whenever governed tables or
columns are added or when `data.security` or table `security` rules change.

## Scope boundaries

The declarative security implementation has the following scope boundaries in
Cortex Framework version 7.1:

- **Top-level columns and Data Catalog policy tags** : Declarative `columnTags` rules (`matchExact`, `matchSuffix`, and Tier 3 `security.columnTags`) target top-level BigQuery columns (`^[a-zA-Z_][a-zA-Z0-9_]{0,299}$`) on materialized `table` and `incremental` models by using Data Catalog policy tag URIs (`projects/*/locations/*/taxonomies/*/policyTags/*`). Nested `STRUCT` and `ARRAY<STRUCT>` leaf column selectors and IAM data governance tags aren't configured through `data.security`.
- **External data foundations (`external: true`)** : When a data foundation module sets `external: true` in `config.yaml`, Cortex Framework skips target dataset creation and CDC model generation and rewires downstream data products directly to `dataSourceId`. Manage RLS and CLS on external source tables at their producer.

## What's next

- [Deployment guide](https://docs.cloud.google.com/cortex/docs/deployment.md.txt)
- [Data quality assertions](https://docs.cloud.google.com/cortex/docs/data-quality-assertions.md.txt)
- [Build workspace with `uv run cortex-build`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-build.md.txt)
- [Deploy workspace with `uv run cortex-deploy`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-deploy.md.txt)
- [Apply security policies with `uv run cortex-apply-security`](https://docs.cloud.google.com/cortex/docs/uv-run-cortex-apply-security.md.txt)