kaxil commented on code in PR #77776:
URL: https://github.com/apache/airflow/pull/77776#discussion_r4748130767


##########
providers/common/ai/src/airflow/providers/common/ai/toolsets/sql.py:
##########
@@ -848,3 +940,96 @@ def _enforce_allowed_tables(self, statements: list[Any]) 
-> None:
                 f"Query references tables that are not in the allowed tables 
list: "
                 f"{', '.join(sorted(set(disallowed)))}. Use 
{self._build_tool_name('list_tables')} to see the allowed tables."
             )
+
+    def _enforce_allowed_columns(self, statements: list[Any], *, dialect: str 
| None) -> None:

Review Comment:
   Have you considered rewriting each restricted table reference to `(SELECT 
id, name, region FROM customers) AS customers` before running the query? The 
database would then refuse `email` on its own wherever it appears, and most of 
my other comments go away, since `*`, `#3` or an alias list can only reach the 
allowed columns. The catch is that we'd run sqlglot's generated SQL rather than 
the agent's, and `TABLESAMPLE` or `public.customers.id` would need care. Writes 
would still need this check.



##########
providers/common/ai/src/airflow/providers/common/ai/utils/sql_validation.py:
##########
@@ -412,6 +416,416 @@ def collect_table_references(
     return TableScan(tables=tables, unverifiable_sources=unverifiable)
 
 
+#: ``(catalog, schema, table)``, each part case-folded, ``None`` when absent.
+_TableKey = tuple[str | None, str | None, str]
+
+# Stands in for "no default schema" when handing tables to sqlglot, which 
wants every
+# table in its schema mapping at the same depth. The qualified SQL never 
leaves this module.
+_DEFAULT_SCHEMA_PLACEHOLDER = "__airflow_default_schema__"
+
+
+class ColumnScan(NamedTuple):
+    """Result of :func:`find_column_violations`."""
+
+    #: ``table.column`` for every column read of a restricted table that is 
not allowed, or
+    #: not found on it. Sorted and unique.
+    denied: list[str]
+    #: Bare column names that match no source, or more than one, so no table 
can be named.
+    ambiguous: list[str]
+    #: Constructs whose column reads cannot be traced (``SELECT *`` on a 
restricted table, a
+    #: quoted column identifier, a statement that is not a query).
+    unverifiable: list[str]
+    #: Names in ``denied`` or ``ambiguous`` that are an output alias of their 
SELECT, read as a
+    #: column outside a bare ORDER BY. Whether the name is a column of any 
table plays no part.
+    output_aliases: list[str]
+
+
+def _get_table_key(table: exp.Table, default_schema: str | None) -> _TableKey:
+    """Return the case-folded key of ``table``, filling in ``default_schema`` 
for an unqualified one."""
+    schema = table.db or default_schema
+    return (
+        table.catalog.casefold() if table.catalog else None,
+        schema.casefold() if schema else None,
+        table.name.casefold(),
+    )
+
+
+def _find_restricted_tables(
+    statement: exp.Expr, column_policy: Mapping[_TableKey, frozenset[str]], 
default_schema: str | None
+) -> list[str]:
+    """
+    List the tables in ``statement`` that have a column policy.
+
+    A table is matched by name only, so a CTE that shares a restricted table's 
name is
+    counted too. Over-matching just means the full column check runs on a 
query that did
+    not need it.
+    """
+    return sorted(
+        {
+            ".".join(part for part in (table.catalog, table.db, table.name) if 
part)
+            for table in statement.find_all(exp.Table)
+            if table.name and _get_table_key(table, default_schema) in 
column_policy
+        }
+    )
+
+
+def _has_quoted_column_identifier(statement: exp.Expr) -> bool:
+    """Report whether a column reference or ``USING`` list in ``statement`` 
has a quoted identifier."""
+    for column in statement.find_all(exp.Column):
+        parts = (column.args.get(part) for part in ("this", "table", "db", 
"catalog"))
+        if any(isinstance(part, exp.Identifier) and part.args.get("quoted") 
for part in parts):
+            return True
+    return any(
+        identifier.args.get("quoted")
+        for join in statement.find_all(exp.Join)
+        for using in join.args.get("using") or []
+        for identifier in using.find_all(exp.Identifier)
+    )
+
+
+def _find_source(scope: Scope, name: str) -> exp.Table | Scope | None:
+    """Resolve a table alias in ``scope``, then in the enclosing scopes (a 
correlated subquery)."""
+    current: Scope | None = scope
+    while current is not None:
+        if name in current.sources:
+            return current.sources[name]
+        current = current.parent
+    return None
+
+
+def _find_enclosing_scope(node: exp.Expr, scope_by_node: Mapping[int, Scope]) 
-> Scope | None:
+    """Return the scope of the nearest query that contains ``node``."""
+    current: exp.Expr | None = node.parent
+    while current is not None and id(current) not in scope_by_node:
+        current = current.parent
+    return scope_by_node[id(current)] if current is not None else None
+
+
+def _get_output_names(scope: Scope) -> set[str]:
+    """Return the case-folded names of the columns a query scope produces."""
+    expression = scope.expression
+    return (
+        {name.casefold() for name in expression.named_selects} if 
isinstance(expression, exp.Query) else set()
+    )
+
+
+def _find_star_reads(
+    statement: exp.Expr, column_policy: Mapping[_TableKey, frozenset[str]], 
default_schema: str | None
+) -> list[str]:
+    """
+    Describe every wildcard that expands to the columns of a restricted table.
+
+    Any ``*`` counts, wherever it sits, because a function can take it 
(Snowflake
+    ``OBJECT_CONSTRUCT(*)``) and a filter can read through it. The one 
exception is the
+    argument of a plain ``COUNT(*)``, which reads no column. A DuckDB 
``COLUMNS(...)``
+    expression is refused whatever it matches.
+    """
+    found: set[str] = set()
+    copy = statement.copy()
+    scopes = traverse_scope(copy)
+    scope_by_node = {id(scope.expression): scope for scope in scopes}
+
+    def list_restricted(sources: Sequence[exp.Table | Scope | None]) -> 
list[str]:
+        return [
+            source.name
+            for source in sources
+            if isinstance(source, exp.Table) and _get_table_key(source, 
default_schema) in column_policy
+        ]
+
+    for node in copy.find_all(exp.Star, exp.Columns):
+        scope = _find_enclosing_scope(node, scope_by_node)
+        if isinstance(node, exp.Columns):
+            found.add("a COLUMNS(...) expression")
+            continue
+        parent = node.parent
+        if isinstance(parent, exp.Count) and parent.this is node:
+            continue
+        if isinstance(parent, exp.Column):
+            sources = [_find_source(scope, parent.table)] if scope is not None 
else []
+        else:
+            sources = [source for _, source in 
scope.selected_sources.values()] if scope is not None else []
+        found.update(f"SELECT * on {name}" for name in 
list_restricted(sources))
+        if scope is None:
+            found.add("a * wildcard outside any query")
+    return sorted(found)
+
+
+def _get_qualified_key(table: exp.Table) -> _TableKey:
+    """Return the key of a table in qualified SQL, where "no default schema" 
is the placeholder."""
+    catalog, schema, name = _get_table_key(table, None)
+    return (catalog, None if schema == _DEFAULT_SCHEMA_PLACEHOLDER else 
schema, name)
+
+
+# Dialects where a bare name in ORDER BY is the output column of that name, 
not an input column.
+# PostgreSQL and MySQL document it; SQLite and DuckDB were run against a table 
with a same-named
+# column. The sqlglot name of an unresolved dialect is ``None``, which is not 
in the set: the
+# name is then read as a column, so a restricted table's column is not hidden 
behind an alias.
+_ORDER_BY_OUTPUT_NAME_DIALECTS: frozenset[str] = frozenset({"postgres", 
"mysql", "sqlite", "duckdb"})
+
+
+class _ColumnReadFinder:
+    """Settles, for one qualified statement, which column reads a restricted 
table does not allow."""
+
+    def __init__(
+        self,
+        column_policy: Mapping[_TableKey, frozenset[str]],
+        mapped_names: Mapping[_TableKey, set[str]],
+        scope_by_node: Mapping[int, Scope],
+        dialect: str | None,
+    ) -> None:
+        self._orders_by_output_name = dialect in _ORDER_BY_OUTPUT_NAME_DIALECTS
+        self._column_policy = column_policy
+        self._mapped_names = mapped_names
+        self._scope_by_node = scope_by_node
+        self.denied: set[str] = set()
+        self.ambiguous: set[str] = set()
+        self.unverifiable: set[str] = set()
+
+    def _is_restricted(self, source: exp.Table | Scope) -> bool:
+        return isinstance(source, exp.Table) and _get_qualified_key(source) in 
self._column_policy
+
+    def check_table_column(self, table: exp.Table, column: str) -> bool:

Review Comment:
   This checks the column name as written, but a column alias list on the table 
renames columns by position. With `customers(id, name, email)`, `SELECT id FROM 
customers AS t(x, y, id)` reads `email` under the name `id`: it passes here and 
returns the email on Postgres and DuckDB, and `WHERE id LIKE 'ann@%'` filters 
on it the same way. Nothing reads the alias's column list. Could a column alias 
list on a restricted table be refused?



##########
providers/common/ai/src/airflow/providers/common/ai/utils/sql_validation.py:
##########
@@ -412,6 +416,416 @@ def collect_table_references(
     return TableScan(tables=tables, unverifiable_sources=unverifiable)
 
 
+#: ``(catalog, schema, table)``, each part case-folded, ``None`` when absent.
+_TableKey = tuple[str | None, str | None, str]
+
+# Stands in for "no default schema" when handing tables to sqlglot, which 
wants every
+# table in its schema mapping at the same depth. The qualified SQL never 
leaves this module.
+_DEFAULT_SCHEMA_PLACEHOLDER = "__airflow_default_schema__"
+
+
+class ColumnScan(NamedTuple):
+    """Result of :func:`find_column_violations`."""
+
+    #: ``table.column`` for every column read of a restricted table that is 
not allowed, or
+    #: not found on it. Sorted and unique.
+    denied: list[str]
+    #: Bare column names that match no source, or more than one, so no table 
can be named.
+    ambiguous: list[str]
+    #: Constructs whose column reads cannot be traced (``SELECT *`` on a 
restricted table, a
+    #: quoted column identifier, a statement that is not a query).
+    unverifiable: list[str]
+    #: Names in ``denied`` or ``ambiguous`` that are an output alias of their 
SELECT, read as a
+    #: column outside a bare ORDER BY. Whether the name is a column of any 
table plays no part.
+    output_aliases: list[str]
+
+
+def _get_table_key(table: exp.Table, default_schema: str | None) -> _TableKey:
+    """Return the case-folded key of ``table``, filling in ``default_schema`` 
for an unqualified one."""
+    schema = table.db or default_schema
+    return (
+        table.catalog.casefold() if table.catalog else None,
+        schema.casefold() if schema else None,
+        table.name.casefold(),
+    )
+
+
+def _find_restricted_tables(
+    statement: exp.Expr, column_policy: Mapping[_TableKey, frozenset[str]], 
default_schema: str | None
+) -> list[str]:
+    """
+    List the tables in ``statement`` that have a column policy.
+
+    A table is matched by name only, so a CTE that shares a restricted table's 
name is
+    counted too. Over-matching just means the full column check runs on a 
query that did
+    not need it.
+    """
+    return sorted(
+        {
+            ".".join(part for part in (table.catalog, table.db, table.name) if 
part)
+            for table in statement.find_all(exp.Table)
+            if table.name and _get_table_key(table, default_schema) in 
column_policy
+        }
+    )
+
+
+def _has_quoted_column_identifier(statement: exp.Expr) -> bool:
+    """Report whether a column reference or ``USING`` list in ``statement`` 
has a quoted identifier."""
+    for column in statement.find_all(exp.Column):
+        parts = (column.args.get(part) for part in ("this", "table", "db", 
"catalog"))
+        if any(isinstance(part, exp.Identifier) and part.args.get("quoted") 
for part in parts):
+            return True
+    return any(
+        identifier.args.get("quoted")
+        for join in statement.find_all(exp.Join)
+        for using in join.args.get("using") or []
+        for identifier in using.find_all(exp.Identifier)
+    )
+
+
+def _find_source(scope: Scope, name: str) -> exp.Table | Scope | None:
+    """Resolve a table alias in ``scope``, then in the enclosing scopes (a 
correlated subquery)."""
+    current: Scope | None = scope
+    while current is not None:
+        if name in current.sources:
+            return current.sources[name]
+        current = current.parent
+    return None
+
+
+def _find_enclosing_scope(node: exp.Expr, scope_by_node: Mapping[int, Scope]) 
-> Scope | None:
+    """Return the scope of the nearest query that contains ``node``."""
+    current: exp.Expr | None = node.parent
+    while current is not None and id(current) not in scope_by_node:
+        current = current.parent
+    return scope_by_node[id(current)] if current is not None else None
+
+
+def _get_output_names(scope: Scope) -> set[str]:
+    """Return the case-folded names of the columns a query scope produces."""
+    expression = scope.expression
+    return (
+        {name.casefold() for name in expression.named_selects} if 
isinstance(expression, exp.Query) else set()
+    )
+
+
+def _find_star_reads(
+    statement: exp.Expr, column_policy: Mapping[_TableKey, frozenset[str]], 
default_schema: str | None
+) -> list[str]:
+    """
+    Describe every wildcard that expands to the columns of a restricted table.
+
+    Any ``*`` counts, wherever it sits, because a function can take it 
(Snowflake
+    ``OBJECT_CONSTRUCT(*)``) and a filter can read through it. The one 
exception is the
+    argument of a plain ``COUNT(*)``, which reads no column. A DuckDB 
``COLUMNS(...)``
+    expression is refused whatever it matches.
+    """
+    found: set[str] = set()
+    copy = statement.copy()
+    scopes = traverse_scope(copy)
+    scope_by_node = {id(scope.expression): scope for scope in scopes}
+
+    def list_restricted(sources: Sequence[exp.Table | Scope | None]) -> 
list[str]:
+        return [
+            source.name
+            for source in sources
+            if isinstance(source, exp.Table) and _get_table_key(source, 
default_schema) in column_policy
+        ]
+
+    for node in copy.find_all(exp.Star, exp.Columns):
+        scope = _find_enclosing_scope(node, scope_by_node)
+        if isinstance(node, exp.Columns):
+            found.add("a COLUMNS(...) expression")
+            continue
+        parent = node.parent
+        if isinstance(parent, exp.Count) and parent.this is node:
+            continue
+        if isinstance(parent, exp.Column):
+            sources = [_find_source(scope, parent.table)] if scope is not None 
else []
+        else:
+            sources = [source for _, source in 
scope.selected_sources.values()] if scope is not None else []
+        found.update(f"SELECT * on {name}" for name in 
list_restricted(sources))
+        if scope is None:
+            found.add("a * wildcard outside any query")
+    return sorted(found)
+
+
+def _get_qualified_key(table: exp.Table) -> _TableKey:
+    """Return the key of a table in qualified SQL, where "no default schema" 
is the placeholder."""
+    catalog, schema, name = _get_table_key(table, None)
+    return (catalog, None if schema == _DEFAULT_SCHEMA_PLACEHOLDER else 
schema, name)
+
+
+# Dialects where a bare name in ORDER BY is the output column of that name, 
not an input column.
+# PostgreSQL and MySQL document it; SQLite and DuckDB were run against a table 
with a same-named
+# column. The sqlglot name of an unresolved dialect is ``None``, which is not 
in the set: the
+# name is then read as a column, so a restricted table's column is not hidden 
behind an alias.
+_ORDER_BY_OUTPUT_NAME_DIALECTS: frozenset[str] = frozenset({"postgres", 
"mysql", "sqlite", "duckdb"})
+
+
+class _ColumnReadFinder:
+    """Settles, for one qualified statement, which column reads a restricted 
table does not allow."""
+
+    def __init__(
+        self,
+        column_policy: Mapping[_TableKey, frozenset[str]],
+        mapped_names: Mapping[_TableKey, set[str]],
+        scope_by_node: Mapping[int, Scope],
+        dialect: str | None,
+    ) -> None:
+        self._orders_by_output_name = dialect in _ORDER_BY_OUTPUT_NAME_DIALECTS
+        self._column_policy = column_policy
+        self._mapped_names = mapped_names
+        self._scope_by_node = scope_by_node
+        self.denied: set[str] = set()
+        self.ambiguous: set[str] = set()
+        self.unverifiable: set[str] = set()
+
+    def _is_restricted(self, source: exp.Table | Scope) -> bool:
+        return isinstance(source, exp.Table) and _get_qualified_key(source) in 
self._column_policy
+
+    def check_table_column(self, table: exp.Table, column: str) -> bool:
+        """Record a read of ``column`` on ``table`` that is not allowed or not 
found; return whether it was."""
+        key = _get_qualified_key(table)
+        name = column.casefold()
+        if key in self._column_policy and (
+            name not in self._column_policy[key] or name not in 
self._mapped_names[key]
+        ):
+            self.denied.add(f"{table.name.casefold()}.{name}")
+            return True
+        return False
+
+    def _has_column(self, source: exp.Table | Scope, name: str) -> bool:
+        if isinstance(source, exp.Table):
+            return name in self._mapped_names.get(_get_qualified_key(source), 
())
+        return name in _get_output_names(source)
+
+    def check_resolved_columns(self, scopes: Sequence[Scope]) -> set[int]:
+        """Check every column qualified with a table alias; return the ``id`` 
of each one it settled."""
+        settled: set[int] = set()
+        for scope in scopes:
+            for column in scope.columns:
+                if isinstance(column.this, exp.Star) or not column.table:
+                    continue
+                source = _find_source(scope, column.table)
+                if source is None:
+                    continue
+                settled.add(id(column))
+                if isinstance(source, exp.Table):
+                    self.check_table_column(source, column.name)
+        return settled
+
+    def check_whole_row_references(self, qualified: exp.Expr) -> None:
+        """Refuse a bare table alias (``SELECT c FROM t c``, 
``row_to_json(c)``), which is the whole row."""
+        for whole_row in qualified.find_all(exp.TableColumn):
+            enclosing = _find_enclosing_scope(whole_row, self._scope_by_node)
+            source = _find_source(enclosing, whole_row.name) if enclosing is 
not None else None
+            if isinstance(source, exp.Table) and self._is_restricted(source):
+                self.unverifiable.add(f"a whole-row reference to 
{source.name}")
+
+    def check_unsettled_columns(self, qualified: exp.Expr, settled: set[int]) 
-> None:
+        """
+        Resolve what ``check_resolved_columns`` left.
+
+        ``Scope.columns`` leaves out an unqualified column under HAVING or 
QUALIFY, and
+        qualification leaves an ambiguous or unknown one unqualified.
+        """
+        for column in qualified.find_all(exp.Column):
+            if isinstance(column.this, exp.Star) or id(column) in settled:
+                continue
+            name = column.name.casefold()
+            scope = _find_enclosing_scope(column, self._scope_by_node)
+            if column.table or scope is None:
+                self.denied.add(f"{column.table.casefold()}.{name}" if 
column.table else name)
+            elif isinstance(scope.expression, exp.Select):
+                self.resolve_bare_column(column, name, scope)
+
+    def resolve_bare_column(self, column: exp.Column, name: str, scope: Scope) 
-> None:
+        """
+        Resolve an unqualified column the way the database does: the innermost 
query that has it.
+
+        A subquery sees its own sources first and then those of every 
enclosing query, so a
+        correlated ``HAVING email`` over an unrelated table still reads the 
outer
+        ``customers.email``. A name that no query has, or that is only an 
output alias of the
+        select, is reported whenever a restricted table is in scope: a 
database may read the
+        name as a column the cached column list does not know, and whether an 
alias were
+        accepted would show whether the restricted table has a column of that 
name. The one
+        exception is a bare name in ORDER BY on a dialect known to read it as 
the output column.
+        """
+        select = scope.expression
+        output_names = _get_output_names(scope)
+        is_alias = name in output_names and not _is_projection(column, select)
+        ordered = column.parent
+        if (
+            self._orders_by_output_name
+            and isinstance(ordered, exp.Ordered)
+            and isinstance(ordered.parent, exp.Order)
+            and ordered.parent.parent is select
+            and name in output_names
+        ):
+            return
+        self._report_unresolved_column(name, scope, is_alias=is_alias)
+
+    def _report_unresolved_column(self, name: str, scope: Scope, *, is_alias: 
bool) -> None:
+        """Record what a bare ``name`` reads when it is denied, ambiguous or 
unknown."""
+        restricted: list[exp.Table] = []
+        level: Scope | None = scope
+        while level is not None:
+            sources = [source for _, source in level.selected_sources.values()]
+            restricted.extend(s for s in sources if isinstance(s, exp.Table) 
and self._is_restricted(s))
+            matches = [source for source in sources if 
self._has_column(source, name)]
+            if matches:
+                # A denied column is reported even when another table also has 
the name, so the
+                # answer does not depend on whether the name exists elsewhere.
+                visible = [
+                    source
+                    for source in matches
+                    if not (isinstance(source, exp.Table) and 
self.check_table_column(source, name))
+                ]
+                if len(visible) > 1 and len(visible) == len(matches):
+                    self.ambiguous.add(name)
+                return
+            level = level.parent
+        if is_alias and not restricted:
+            return
+        if restricted:
+            for table in restricted:
+                self.denied.add(f"{table.name.casefold()}.{name}")
+            return
+        sources = [source for _, source in scope.selected_sources.values()]
+        if len(sources) > 1:
+            self.ambiguous.add(name)
+        elif not (len(sources) == 1 and isinstance(sources[0], exp.Table)):
+            self.denied.add(name)
+
+    def find_output_aliases(self, qualified: exp.Expr) -> set[str]:
+        """
+        Return the reported names that are also an output alias where they are 
used.
+
+        Decided by the name and its position alone, never by whether a table 
has such a column,
+        and over every column whichever way it was resolved, so that it cannot 
tell the two apart.
+        """
+        reported = {entry.rsplit(".", 1)[-1] for entry in (*self.denied, 
*self.ambiguous)}
+        aliases: set[str] = set()
+        for column in qualified.find_all(exp.Column):
+            name = column.name.casefold()
+            scope = _find_enclosing_scope(column, self._scope_by_node)
+            if (
+                name in reported
+                and scope is not None
+                and isinstance(scope.expression, exp.Select)
+                and name in _get_output_names(scope)
+                and not _is_projection(column, scope.expression)
+            ):
+                aliases.add(name)
+        return aliases
+
+
+def _describe_statement(statement: exp.Expr, where: str) -> str:
+    """Name a statement type for a message, with the article that fits it."""
+    name = type(statement).__name__
+    return f"{'an' if name[0] in 'AEIOU' else 'a'} {name} statement on {where}"
+
+
+def _is_projection(column: exp.Column, select: exp.Expr) -> bool:
+    """Report whether ``column`` sits in the select list of ``select`` rather 
than a clause."""
+    node: exp.Expr = column
+    while node.parent is not None and node.parent is not select:
+        node = node.parent
+    return node.arg_key == "expressions"
+
+
+def find_column_violations(

Review Comment:
   Only `exp.Column` and `*` get checked here, so a read sqlglot parses as some 
other node goes through. DuckDB `SELECT #3 FROM customers` (`PositionalColumn`) 
and SQLite `SELECT 'c'.'email' FROM customers c` both return the emails. I'd 
expect Snowflake `$3` and `COUNT(* EXCLUDE (id, name))` to do the same but 
haven't tried them on Snowflake (on sqlglot 30.29 the `EXCLUDE`/`ILIKE` sits on 
the star, so the `COUNT(*)` exemption lets it through). Would an allowlist of 
node types known to be safe work better here when a restricted table is in 
scope?



##########
providers/common/ai/src/airflow/providers/common/ai/toolsets/sql.py:
##########
@@ -848,3 +940,96 @@ def _enforce_allowed_tables(self, statements: list[Any]) 
-> None:
                 f"Query references tables that are not in the allowed tables 
list: "
                 f"{', '.join(sorted(set(disallowed)))}. Use 
{self._build_tool_name('list_tables')} to see the allowed tables."
             )
+
+    def _enforce_allowed_columns(self, statements: list[Any], *, dialect: str 
| None) -> None:
+        """
+        Reject a parsed query that reads a column ``allowed_columns`` does not 
allow.
+
+        No-op when ``allowed_columns`` is unset, and for a query that reaches 
no table it
+        narrows: nothing is read from the database for those. Otherwise the 
columns of every
+        table the query reaches are resolved (see 
:func:`find_column_violations`) and any read of
+        a denied column, or any construct that cannot be traced to a column, 
is refused with
+        :class:`SQLSafetyError`. ``call_tool`` turns that into a 
``ModelRetry`` and
+        ``check_query`` reports it invalid.
+        """
+        if not self._column_policy:
+            return
+        scan = collect_table_references(statements, 
allowed_functions=self._allowed_functions)
+        keys = {
+            self._canonical_ref(catalog, schema or self._schema, table)
+            for catalog, schema, table in scan.tables
+        }
+        if keys.isdisjoint(self._column_policy):
+            return
+        table_columns = {key: self._get_table_column_names(key) for key in 
keys}
+        denied: set[str] = set()
+        ambiguous: set[str] = set()
+        unverifiable: set[str] = set()
+        output_aliases: set[str] = set()
+        for statement in statements:
+            found = find_column_violations(
+                statement,
+                column_policy=self._column_policy,
+                table_columns=table_columns,
+                default_schema=self._schema,
+                dialect=dialect,
+            )
+            denied.update(found.denied)
+            ambiguous.update(found.ambiguous)
+            unverifiable.update(found.unverifiable)
+            output_aliases.update(found.output_aliases)
+        get_schema = self._build_tool_name("get_schema")
+        # Only whether the name is an output alias decides this, never whether 
a column of that
+        # name exists, so the hint cannot be used to tell.
+        alias_hint = (
+            f" {', '.join(sorted(output_aliases))} is an output alias, which 
outside a bare ORDER BY "
+            "may be read as a column: write the expression itself or its 
position (for example "
+            "GROUP BY 1) instead."
+            if output_aliases
+            else ""
+        )
+        if unverifiable:
+            raise SQLSafetyError(
+                f"Query uses a construct that cannot be checked against 
allowed_columns: "
+                f"{'; '.join(sorted(unverifiable))}. List the allowed columns 
explicitly: "
+                f"use {get_schema} to see them."
+            )
+        if ambiguous:
+            raise SQLSafetyError(
+                f"Query has columns that cannot be resolved to exactly one 
table: "
+                f"{', '.join(sorted(ambiguous))}. Qualify each column with its 
table or alias, e.g. c.name.{alias_hint}"
+            )
+        if denied:
+            raise SQLSafetyError(
+                f"Query reads columns that are not allowed or do not exist: "
+                f"{', '.join(sorted(denied))}. Use {get_schema} to see the 
columns you may query.{alias_hint}"
+            )
+
+    def _get_table_column_names(self, key: tuple[str | None, str | None, str]) 
-> tuple[str, ...]:
+        """Return the columns of the table with canonical ``key``, read from 
the database once."""
+        if key in self._table_column_names:
+            return self._table_column_names[key]
+        if self._reflected_tables is None:
+            self._reflected_tables = {
+                self._canonical_ref("", schema, name): (schema, name)
+                for schema, name, _ in self._find_allowed_tables()
+            }
+        display = ".".join(part for part in key if part)
+        if key not in self._reflected_tables:
+            raise SQLSafetyError(
+                f"Table {display} was not found in the database, so its 
columns cannot be checked "
+                "against allowed_columns."
+            )
+        schema, name = self._reflected_tables[key]
+        # Called for its side effect, as in get_schema: setup failures surface 
as SQLToolsetConnectionError.
+        self._get_inspector()
+        try:
+            columns = 
self._get_db_hook().get_table_columns_with_comments(name, schema=schema)
+        except Exception as e:
+            if _is_lost_connection(e):
+                raise
+            raise SQLSafetyError(
+                f"Could not read the columns of table {display} to check 
allowed_columns: {e}"
+            ) from e
+        self._table_column_names[key] = tuple(column["name"] for column in 
columns)

Review Comment:
   `AgentOperator` gives each run a `copy.copy` of the toolset, and the copies 
share this dict because it's mutated in place. Under `dag.test()`, where runs 
share a process, the second run then checks queries against the column list 
read from the first run's connection, which together with the climb in 
`_report_unresolved_column` let a denied value through. Rebinding the dict here 
instead of mutating it would keep runs apart.



##########
providers/common/ai/src/airflow/providers/common/ai/utils/sql_validation.py:
##########
@@ -412,6 +416,416 @@ def collect_table_references(
     return TableScan(tables=tables, unverifiable_sources=unverifiable)
 
 
+#: ``(catalog, schema, table)``, each part case-folded, ``None`` when absent.
+_TableKey = tuple[str | None, str | None, str]
+
+# Stands in for "no default schema" when handing tables to sqlglot, which 
wants every
+# table in its schema mapping at the same depth. The qualified SQL never 
leaves this module.
+_DEFAULT_SCHEMA_PLACEHOLDER = "__airflow_default_schema__"
+
+
+class ColumnScan(NamedTuple):
+    """Result of :func:`find_column_violations`."""
+
+    #: ``table.column`` for every column read of a restricted table that is 
not allowed, or
+    #: not found on it. Sorted and unique.
+    denied: list[str]
+    #: Bare column names that match no source, or more than one, so no table 
can be named.
+    ambiguous: list[str]
+    #: Constructs whose column reads cannot be traced (``SELECT *`` on a 
restricted table, a
+    #: quoted column identifier, a statement that is not a query).
+    unverifiable: list[str]
+    #: Names in ``denied`` or ``ambiguous`` that are an output alias of their 
SELECT, read as a
+    #: column outside a bare ORDER BY. Whether the name is a column of any 
table plays no part.
+    output_aliases: list[str]
+
+
+def _get_table_key(table: exp.Table, default_schema: str | None) -> _TableKey:
+    """Return the case-folded key of ``table``, filling in ``default_schema`` 
for an unqualified one."""
+    schema = table.db or default_schema
+    return (
+        table.catalog.casefold() if table.catalog else None,
+        schema.casefold() if schema else None,
+        table.name.casefold(),
+    )
+
+
+def _find_restricted_tables(
+    statement: exp.Expr, column_policy: Mapping[_TableKey, frozenset[str]], 
default_schema: str | None
+) -> list[str]:
+    """
+    List the tables in ``statement`` that have a column policy.
+
+    A table is matched by name only, so a CTE that shares a restricted table's 
name is
+    counted too. Over-matching just means the full column check runs on a 
query that did
+    not need it.
+    """
+    return sorted(
+        {
+            ".".join(part for part in (table.catalog, table.db, table.name) if 
part)
+            for table in statement.find_all(exp.Table)
+            if table.name and _get_table_key(table, default_schema) in 
column_policy
+        }
+    )
+
+
+def _has_quoted_column_identifier(statement: exp.Expr) -> bool:
+    """Report whether a column reference or ``USING`` list in ``statement`` 
has a quoted identifier."""
+    for column in statement.find_all(exp.Column):
+        parts = (column.args.get(part) for part in ("this", "table", "db", 
"catalog"))
+        if any(isinstance(part, exp.Identifier) and part.args.get("quoted") 
for part in parts):
+            return True
+    return any(
+        identifier.args.get("quoted")
+        for join in statement.find_all(exp.Join)
+        for using in join.args.get("using") or []
+        for identifier in using.find_all(exp.Identifier)
+    )
+
+
+def _find_source(scope: Scope, name: str) -> exp.Table | Scope | None:
+    """Resolve a table alias in ``scope``, then in the enclosing scopes (a 
correlated subquery)."""
+    current: Scope | None = scope
+    while current is not None:
+        if name in current.sources:
+            return current.sources[name]
+        current = current.parent
+    return None
+
+
+def _find_enclosing_scope(node: exp.Expr, scope_by_node: Mapping[int, Scope]) 
-> Scope | None:
+    """Return the scope of the nearest query that contains ``node``."""
+    current: exp.Expr | None = node.parent
+    while current is not None and id(current) not in scope_by_node:
+        current = current.parent
+    return scope_by_node[id(current)] if current is not None else None
+
+
+def _get_output_names(scope: Scope) -> set[str]:
+    """Return the case-folded names of the columns a query scope produces."""
+    expression = scope.expression
+    return (
+        {name.casefold() for name in expression.named_selects} if 
isinstance(expression, exp.Query) else set()
+    )
+
+
+def _find_star_reads(
+    statement: exp.Expr, column_policy: Mapping[_TableKey, frozenset[str]], 
default_schema: str | None
+) -> list[str]:
+    """
+    Describe every wildcard that expands to the columns of a restricted table.
+
+    Any ``*`` counts, wherever it sits, because a function can take it 
(Snowflake
+    ``OBJECT_CONSTRUCT(*)``) and a filter can read through it. The one 
exception is the
+    argument of a plain ``COUNT(*)``, which reads no column. A DuckDB 
``COLUMNS(...)``
+    expression is refused whatever it matches.
+    """
+    found: set[str] = set()
+    copy = statement.copy()
+    scopes = traverse_scope(copy)
+    scope_by_node = {id(scope.expression): scope for scope in scopes}
+
+    def list_restricted(sources: Sequence[exp.Table | Scope | None]) -> 
list[str]:
+        return [
+            source.name
+            for source in sources
+            if isinstance(source, exp.Table) and _get_table_key(source, 
default_schema) in column_policy
+        ]
+
+    for node in copy.find_all(exp.Star, exp.Columns):
+        scope = _find_enclosing_scope(node, scope_by_node)
+        if isinstance(node, exp.Columns):
+            found.add("a COLUMNS(...) expression")
+            continue
+        parent = node.parent
+        if isinstance(parent, exp.Count) and parent.this is node:
+            continue
+        if isinstance(parent, exp.Column):
+            sources = [_find_source(scope, parent.table)] if scope is not None 
else []
+        else:
+            sources = [source for _, source in 
scope.selected_sources.values()] if scope is not None else []
+        found.update(f"SELECT * on {name}" for name in 
list_restricted(sources))
+        if scope is None:
+            found.add("a * wildcard outside any query")
+    return sorted(found)
+
+
+def _get_qualified_key(table: exp.Table) -> _TableKey:
+    """Return the key of a table in qualified SQL, where "no default schema" 
is the placeholder."""
+    catalog, schema, name = _get_table_key(table, None)
+    return (catalog, None if schema == _DEFAULT_SCHEMA_PLACEHOLDER else 
schema, name)
+
+
+# Dialects where a bare name in ORDER BY is the output column of that name, 
not an input column.
+# PostgreSQL and MySQL document it; SQLite and DuckDB were run against a table 
with a same-named
+# column. The sqlglot name of an unresolved dialect is ``None``, which is not 
in the set: the
+# name is then read as a column, so a restricted table's column is not hidden 
behind an alias.
+_ORDER_BY_OUTPUT_NAME_DIALECTS: frozenset[str] = frozenset({"postgres", 
"mysql", "sqlite", "duckdb"})
+
+
+class _ColumnReadFinder:
+    """Settles, for one qualified statement, which column reads a restricted 
table does not allow."""
+
+    def __init__(
+        self,
+        column_policy: Mapping[_TableKey, frozenset[str]],
+        mapped_names: Mapping[_TableKey, set[str]],
+        scope_by_node: Mapping[int, Scope],
+        dialect: str | None,
+    ) -> None:
+        self._orders_by_output_name = dialect in _ORDER_BY_OUTPUT_NAME_DIALECTS
+        self._column_policy = column_policy
+        self._mapped_names = mapped_names
+        self._scope_by_node = scope_by_node
+        self.denied: set[str] = set()
+        self.ambiguous: set[str] = set()
+        self.unverifiable: set[str] = set()
+
+    def _is_restricted(self, source: exp.Table | Scope) -> bool:
+        return isinstance(source, exp.Table) and _get_qualified_key(source) in 
self._column_policy
+
+    def check_table_column(self, table: exp.Table, column: str) -> bool:
+        """Record a read of ``column`` on ``table`` that is not allowed or not 
found; return whether it was."""
+        key = _get_qualified_key(table)
+        name = column.casefold()
+        if key in self._column_policy and (
+            name not in self._column_policy[key] or name not in 
self._mapped_names[key]
+        ):
+            self.denied.add(f"{table.name.casefold()}.{name}")
+            return True
+        return False
+
+    def _has_column(self, source: exp.Table | Scope, name: str) -> bool:
+        if isinstance(source, exp.Table):
+            return name in self._mapped_names.get(_get_qualified_key(source), 
())
+        return name in _get_output_names(source)
+
+    def check_resolved_columns(self, scopes: Sequence[Scope]) -> set[int]:
+        """Check every column qualified with a table alias; return the ``id`` 
of each one it settled."""
+        settled: set[int] = set()
+        for scope in scopes:
+            for column in scope.columns:
+                if isinstance(column.this, exp.Star) or not column.table:
+                    continue
+                source = _find_source(scope, column.table)
+                if source is None:
+                    continue
+                settled.add(id(column))
+                if isinstance(source, exp.Table):
+                    self.check_table_column(source, column.name)
+        return settled
+
+    def check_whole_row_references(self, qualified: exp.Expr) -> None:
+        """Refuse a bare table alias (``SELECT c FROM t c``, 
``row_to_json(c)``), which is the whole row."""
+        for whole_row in qualified.find_all(exp.TableColumn):
+            enclosing = _find_enclosing_scope(whole_row, self._scope_by_node)
+            source = _find_source(enclosing, whole_row.name) if enclosing is 
not None else None
+            if isinstance(source, exp.Table) and self._is_restricted(source):
+                self.unverifiable.add(f"a whole-row reference to 
{source.name}")
+
+    def check_unsettled_columns(self, qualified: exp.Expr, settled: set[int]) 
-> None:
+        """
+        Resolve what ``check_resolved_columns`` left.
+
+        ``Scope.columns`` leaves out an unqualified column under HAVING or 
QUALIFY, and
+        qualification leaves an ambiguous or unknown one unqualified.
+        """
+        for column in qualified.find_all(exp.Column):
+            if isinstance(column.this, exp.Star) or id(column) in settled:
+                continue
+            name = column.name.casefold()
+            scope = _find_enclosing_scope(column, self._scope_by_node)
+            if column.table or scope is None:
+                self.denied.add(f"{column.table.casefold()}.{name}" if 
column.table else name)
+            elif isinstance(scope.expression, exp.Select):
+                self.resolve_bare_column(column, name, scope)
+
+    def resolve_bare_column(self, column: exp.Column, name: str, scope: Scope) 
-> None:
+        """
+        Resolve an unqualified column the way the database does: the innermost 
query that has it.
+
+        A subquery sees its own sources first and then those of every 
enclosing query, so a
+        correlated ``HAVING email`` over an unrelated table still reads the 
outer
+        ``customers.email``. A name that no query has, or that is only an 
output alias of the
+        select, is reported whenever a restricted table is in scope: a 
database may read the
+        name as a column the cached column list does not know, and whether an 
alias were
+        accepted would show whether the restricted table has a column of that 
name. The one
+        exception is a bare name in ORDER BY on a dialect known to read it as 
the output column.
+        """
+        select = scope.expression
+        output_names = _get_output_names(scope)
+        is_alias = name in output_names and not _is_projection(column, select)
+        ordered = column.parent
+        if (
+            self._orders_by_output_name
+            and isinstance(ordered, exp.Ordered)
+            and isinstance(ordered.parent, exp.Order)
+            and ordered.parent.parent is select
+            and name in output_names
+        ):
+            return
+        self._report_unresolved_column(name, scope, is_alias=is_alias)
+
+    def _report_unresolved_column(self, name: str, scope: Scope, *, is_alias: 
bool) -> None:
+        """Record what a bare ``name`` reads when it is denied, ambiguous or 
unknown."""
+        restricted: list[exp.Table] = []
+        level: Scope | None = scope
+        while level is not None:
+            sources = [source for _, source in level.selected_sources.values()]
+            restricted.extend(s for s in sources if isinstance(s, exp.Table) 
and self._is_restricted(s))
+            matches = [source for source in sources if 
self._has_column(source, name)]
+            if matches:
+                # A denied column is reported even when another table also has 
the name, so the
+                # answer does not depend on whether the name exists elsewhere.
+                visible = [
+                    source
+                    for source in matches
+                    if not (isinstance(source, exp.Table) and 
self.check_table_column(source, name))
+                ]
+                if len(visible) > 1 and len(visible) == len(matches):
+                    self.ambiguous.add(name)
+                return
+            level = level.parent

Review Comment:
   For a name that's not in the cached column list, this walks up out of a CTE 
or derived-table body and finds the body's own output name at the outer level. 
So if `phone` was added to `customers` after the columns were cached, `WITH c 
AS (SELECT phone FROM customers) SELECT * FROM c` passes and SQLite returns it, 
even though the docs warning says it's refused. A correlated subquery can land 
on an unrestricted outer table the same way. Should a miss on a restricted 
table at the innermost level just be refused? Bare outer columns inside such a 
subquery would then need qualifying, which seems fine.



##########
providers/common/ai/src/airflow/providers/common/ai/utils/sql_validation.py:
##########
@@ -412,6 +416,416 @@ def collect_table_references(
     return TableScan(tables=tables, unverifiable_sources=unverifiable)
 
 
+#: ``(catalog, schema, table)``, each part case-folded, ``None`` when absent.
+_TableKey = tuple[str | None, str | None, str]
+
+# Stands in for "no default schema" when handing tables to sqlglot, which 
wants every
+# table in its schema mapping at the same depth. The qualified SQL never 
leaves this module.
+_DEFAULT_SCHEMA_PLACEHOLDER = "__airflow_default_schema__"
+
+
+class ColumnScan(NamedTuple):
+    """Result of :func:`find_column_violations`."""
+
+    #: ``table.column`` for every column read of a restricted table that is 
not allowed, or
+    #: not found on it. Sorted and unique.
+    denied: list[str]
+    #: Bare column names that match no source, or more than one, so no table 
can be named.
+    ambiguous: list[str]
+    #: Constructs whose column reads cannot be traced (``SELECT *`` on a 
restricted table, a
+    #: quoted column identifier, a statement that is not a query).
+    unverifiable: list[str]
+    #: Names in ``denied`` or ``ambiguous`` that are an output alias of their 
SELECT, read as a
+    #: column outside a bare ORDER BY. Whether the name is a column of any 
table plays no part.
+    output_aliases: list[str]
+
+
+def _get_table_key(table: exp.Table, default_schema: str | None) -> _TableKey:
+    """Return the case-folded key of ``table``, filling in ``default_schema`` 
for an unqualified one."""
+    schema = table.db or default_schema
+    return (
+        table.catalog.casefold() if table.catalog else None,
+        schema.casefold() if schema else None,
+        table.name.casefold(),
+    )
+
+
+def _find_restricted_tables(
+    statement: exp.Expr, column_policy: Mapping[_TableKey, frozenset[str]], 
default_schema: str | None
+) -> list[str]:
+    """
+    List the tables in ``statement`` that have a column policy.
+
+    A table is matched by name only, so a CTE that shares a restricted table's 
name is
+    counted too. Over-matching just means the full column check runs on a 
query that did
+    not need it.
+    """
+    return sorted(
+        {
+            ".".join(part for part in (table.catalog, table.db, table.name) if 
part)
+            for table in statement.find_all(exp.Table)
+            if table.name and _get_table_key(table, default_schema) in 
column_policy
+        }
+    )
+
+
+def _has_quoted_column_identifier(statement: exp.Expr) -> bool:
+    """Report whether a column reference or ``USING`` list in ``statement`` 
has a quoted identifier."""
+    for column in statement.find_all(exp.Column):
+        parts = (column.args.get(part) for part in ("this", "table", "db", 
"catalog"))
+        if any(isinstance(part, exp.Identifier) and part.args.get("quoted") 
for part in parts):
+            return True
+    return any(
+        identifier.args.get("quoted")
+        for join in statement.find_all(exp.Join)
+        for using in join.args.get("using") or []
+        for identifier in using.find_all(exp.Identifier)
+    )
+
+
+def _find_source(scope: Scope, name: str) -> exp.Table | Scope | None:
+    """Resolve a table alias in ``scope``, then in the enclosing scopes (a 
correlated subquery)."""
+    current: Scope | None = scope
+    while current is not None:
+        if name in current.sources:
+            return current.sources[name]
+        current = current.parent
+    return None
+
+
+def _find_enclosing_scope(node: exp.Expr, scope_by_node: Mapping[int, Scope]) 
-> Scope | None:
+    """Return the scope of the nearest query that contains ``node``."""
+    current: exp.Expr | None = node.parent
+    while current is not None and id(current) not in scope_by_node:
+        current = current.parent
+    return scope_by_node[id(current)] if current is not None else None
+
+
+def _get_output_names(scope: Scope) -> set[str]:
+    """Return the case-folded names of the columns a query scope produces."""
+    expression = scope.expression
+    return (
+        {name.casefold() for name in expression.named_selects} if 
isinstance(expression, exp.Query) else set()
+    )
+
+
+def _find_star_reads(
+    statement: exp.Expr, column_policy: Mapping[_TableKey, frozenset[str]], 
default_schema: str | None
+) -> list[str]:
+    """
+    Describe every wildcard that expands to the columns of a restricted table.
+
+    Any ``*`` counts, wherever it sits, because a function can take it 
(Snowflake
+    ``OBJECT_CONSTRUCT(*)``) and a filter can read through it. The one 
exception is the
+    argument of a plain ``COUNT(*)``, which reads no column. A DuckDB 
``COLUMNS(...)``
+    expression is refused whatever it matches.
+    """
+    found: set[str] = set()
+    copy = statement.copy()
+    scopes = traverse_scope(copy)
+    scope_by_node = {id(scope.expression): scope for scope in scopes}
+
+    def list_restricted(sources: Sequence[exp.Table | Scope | None]) -> 
list[str]:
+        return [
+            source.name
+            for source in sources
+            if isinstance(source, exp.Table) and _get_table_key(source, 
default_schema) in column_policy
+        ]
+
+    for node in copy.find_all(exp.Star, exp.Columns):
+        scope = _find_enclosing_scope(node, scope_by_node)
+        if isinstance(node, exp.Columns):
+            found.add("a COLUMNS(...) expression")
+            continue
+        parent = node.parent
+        if isinstance(parent, exp.Count) and parent.this is node:
+            continue
+        if isinstance(parent, exp.Column):
+            sources = [_find_source(scope, parent.table)] if scope is not None 
else []
+        else:
+            sources = [source for _, source in 
scope.selected_sources.values()] if scope is not None else []
+        found.update(f"SELECT * on {name}" for name in 
list_restricted(sources))
+        if scope is None:
+            found.add("a * wildcard outside any query")
+    return sorted(found)
+
+
+def _get_qualified_key(table: exp.Table) -> _TableKey:
+    """Return the key of a table in qualified SQL, where "no default schema" 
is the placeholder."""
+    catalog, schema, name = _get_table_key(table, None)
+    return (catalog, None if schema == _DEFAULT_SCHEMA_PLACEHOLDER else 
schema, name)
+
+
+# Dialects where a bare name in ORDER BY is the output column of that name, 
not an input column.
+# PostgreSQL and MySQL document it; SQLite and DuckDB were run against a table 
with a same-named
+# column. The sqlglot name of an unresolved dialect is ``None``, which is not 
in the set: the
+# name is then read as a column, so a restricted table's column is not hidden 
behind an alias.
+_ORDER_BY_OUTPUT_NAME_DIALECTS: frozenset[str] = frozenset({"postgres", 
"mysql", "sqlite", "duckdb"})
+
+
+class _ColumnReadFinder:
+    """Settles, for one qualified statement, which column reads a restricted 
table does not allow."""
+
+    def __init__(
+        self,
+        column_policy: Mapping[_TableKey, frozenset[str]],
+        mapped_names: Mapping[_TableKey, set[str]],
+        scope_by_node: Mapping[int, Scope],
+        dialect: str | None,
+    ) -> None:
+        self._orders_by_output_name = dialect in _ORDER_BY_OUTPUT_NAME_DIALECTS
+        self._column_policy = column_policy
+        self._mapped_names = mapped_names
+        self._scope_by_node = scope_by_node
+        self.denied: set[str] = set()
+        self.ambiguous: set[str] = set()
+        self.unverifiable: set[str] = set()
+
+    def _is_restricted(self, source: exp.Table | Scope) -> bool:
+        return isinstance(source, exp.Table) and _get_qualified_key(source) in 
self._column_policy
+
+    def check_table_column(self, table: exp.Table, column: str) -> bool:
+        """Record a read of ``column`` on ``table`` that is not allowed or not 
found; return whether it was."""
+        key = _get_qualified_key(table)
+        name = column.casefold()
+        if key in self._column_policy and (
+            name not in self._column_policy[key] or name not in 
self._mapped_names[key]
+        ):
+            self.denied.add(f"{table.name.casefold()}.{name}")
+            return True
+        return False
+
+    def _has_column(self, source: exp.Table | Scope, name: str) -> bool:
+        if isinstance(source, exp.Table):
+            return name in self._mapped_names.get(_get_qualified_key(source), 
())
+        return name in _get_output_names(source)
+
+    def check_resolved_columns(self, scopes: Sequence[Scope]) -> set[int]:
+        """Check every column qualified with a table alias; return the ``id`` 
of each one it settled."""
+        settled: set[int] = set()
+        for scope in scopes:
+            for column in scope.columns:
+                if isinstance(column.this, exp.Star) or not column.table:
+                    continue
+                source = _find_source(scope, column.table)
+                if source is None:
+                    continue
+                settled.add(id(column))
+                if isinstance(source, exp.Table):
+                    self.check_table_column(source, column.name)
+        return settled
+
+    def check_whole_row_references(self, qualified: exp.Expr) -> None:
+        """Refuse a bare table alias (``SELECT c FROM t c``, 
``row_to_json(c)``), which is the whole row."""
+        for whole_row in qualified.find_all(exp.TableColumn):
+            enclosing = _find_enclosing_scope(whole_row, self._scope_by_node)
+            source = _find_source(enclosing, whole_row.name) if enclosing is 
not None else None
+            if isinstance(source, exp.Table) and self._is_restricted(source):
+                self.unverifiable.add(f"a whole-row reference to 
{source.name}")
+
+    def check_unsettled_columns(self, qualified: exp.Expr, settled: set[int]) 
-> None:
+        """
+        Resolve what ``check_resolved_columns`` left.
+
+        ``Scope.columns`` leaves out an unqualified column under HAVING or 
QUALIFY, and
+        qualification leaves an ambiguous or unknown one unqualified.
+        """
+        for column in qualified.find_all(exp.Column):
+            if isinstance(column.this, exp.Star) or id(column) in settled:
+                continue
+            name = column.name.casefold()
+            scope = _find_enclosing_scope(column, self._scope_by_node)
+            if column.table or scope is None:
+                self.denied.add(f"{column.table.casefold()}.{name}" if 
column.table else name)
+            elif isinstance(scope.expression, exp.Select):
+                self.resolve_bare_column(column, name, scope)
+
+    def resolve_bare_column(self, column: exp.Column, name: str, scope: Scope) 
-> None:
+        """
+        Resolve an unqualified column the way the database does: the innermost 
query that has it.
+
+        A subquery sees its own sources first and then those of every 
enclosing query, so a
+        correlated ``HAVING email`` over an unrelated table still reads the 
outer
+        ``customers.email``. A name that no query has, or that is only an 
output alias of the
+        select, is reported whenever a restricted table is in scope: a 
database may read the
+        name as a column the cached column list does not know, and whether an 
alias were
+        accepted would show whether the restricted table has a column of that 
name. The one
+        exception is a bare name in ORDER BY on a dialect known to read it as 
the output column.
+        """
+        select = scope.expression
+        output_names = _get_output_names(scope)
+        is_alias = name in output_names and not _is_projection(column, select)
+        ordered = column.parent
+        if (
+            self._orders_by_output_name
+            and isinstance(ordered, exp.Ordered)
+            and isinstance(ordered.parent, exp.Order)
+            and ordered.parent.parent is select
+            and name in output_names

Review Comment:
   `named_selects` also gives an unaliased literal a name, so `SELECT id, 
'email' FROM customers ORDER BY email` takes this early return. Postgres, 
SQLite and DuckDB all read that `email` as the table column and sort by it, and 
with `LIMIT 1` that returns the row with the smallest email. Should this only 
exempt names that are an explicit `AS` alias in the agent's query? It has to 
look at the original statement, since after `qualify` every projection is an 
`exp.Alias`.



##########
providers/common/ai/src/airflow/providers/common/ai/utils/sql_validation.py:
##########
@@ -412,6 +416,416 @@ def collect_table_references(
     return TableScan(tables=tables, unverifiable_sources=unverifiable)
 
 
+#: ``(catalog, schema, table)``, each part case-folded, ``None`` when absent.
+_TableKey = tuple[str | None, str | None, str]
+
+# Stands in for "no default schema" when handing tables to sqlglot, which 
wants every
+# table in its schema mapping at the same depth. The qualified SQL never 
leaves this module.
+_DEFAULT_SCHEMA_PLACEHOLDER = "__airflow_default_schema__"
+
+
+class ColumnScan(NamedTuple):
+    """Result of :func:`find_column_violations`."""
+
+    #: ``table.column`` for every column read of a restricted table that is 
not allowed, or
+    #: not found on it. Sorted and unique.
+    denied: list[str]
+    #: Bare column names that match no source, or more than one, so no table 
can be named.
+    ambiguous: list[str]
+    #: Constructs whose column reads cannot be traced (``SELECT *`` on a 
restricted table, a
+    #: quoted column identifier, a statement that is not a query).
+    unverifiable: list[str]
+    #: Names in ``denied`` or ``ambiguous`` that are an output alias of their 
SELECT, read as a
+    #: column outside a bare ORDER BY. Whether the name is a column of any 
table plays no part.
+    output_aliases: list[str]
+
+
+def _get_table_key(table: exp.Table, default_schema: str | None) -> _TableKey:

Review Comment:
   This repeats `SQLToolset._canonical_ref`. If the two ever disagree, 
`_enforce_allowed_columns` sees a restricted table while 
`_find_restricted_tables` sees none, and the check passes everything. Could 
they share one helper?



##########
providers/common/ai/tests/unit/common/ai/toolsets/test_sql.py:
##########
@@ -1928,3 +1928,426 @@ def 
test_dml_with_cte_source_over_allowed_table_runs(self):
         _run_query(ts, sql)
 
         _assert_executed(ts._hook, sql)
+
+
+_CUSTOMER_COLUMNS = [
+    {"name": "id", "type": "INTEGER"},
+    {"name": "name", "type": "VARCHAR"},
+    {"name": "email", "type": "VARCHAR", "comment": "contact SENTINEL-EMAIL"},
+    {"name": "region", "type": "VARCHAR"},
+]
+_ORDER_COLUMNS = [
+    {"name": "id", "type": "INTEGER"},
+    {"name": "customer_id", "type": "INTEGER"},
+    {"name": "amount", "type": "NUMERIC"},
+    {"name": "email", "type": "VARCHAR"},
+]
+
+
+def _make_column_toolset(**kwargs) -> SQLToolset:
+    """A toolset that may read every column of ``orders`` but not 
``customers.email``."""
+    kwargs.setdefault("allowed_tables", ["customers", "orders"])
+    kwargs.setdefault("allowed_columns", {"customers": ["id", "name", 
"region"]})
+    ts = SQLToolset("pg_default", **kwargs)
+    ts._hook = _make_mock_db_hook(
+        table_names=["customers", "orders"], records=[(1,)], 
last_description=[("id",)]
+    )
+    ts._hook.dialect_name = "postgresql"
+    columns = {"customers": _CUSTOMER_COLUMNS, "orders": _ORDER_COLUMNS}
+    ts._hook.get_table_columns_with_comments.side_effect = lambda table, 
schema=None: columns[table]
+    return ts
+
+
+# One query per way a denied read is reported; the full matrix is in 
test_sql_validation.py.
+_DENIED_QUERIES = pytest.mark.parametrize(
+    ("sql", "expected"),
+    [
+        ("SELECT email FROM customers", "customers.email"),
+        ("SELECT id FROM customers WHERE email IS NOT NULL", 
"customers.email"),
+        (
+            "WITH c AS (SELECT email AS e FROM customers) SELECT 1 FROM c 
WHERE e IS NOT NULL",
+            "customers.email",
+        ),
+        ("SELECT * FROM customers", "SELECT * on customers"),
+        ("SELECT email FROM customers JOIN orders ON customers.id = 
orders.customer_id", "email"),

Review Comment:
   This `ambiguous` case is reported as denied `customers.email`, so the 
"cannot be resolved to exactly one table" refusal has no toolset test. `SELECT 
id FROM customers JOIN orders ON customers.id = orders.customer_id` reaches it, 
and also shows the output-alias hint firing for `customers.id` in the `ON` 
clause, which can't be an alias. Could the hint skip columns the agent 
qualified? That needs the original statement, because `qualify` also qualifies 
an alias name that matches a table column.



##########
providers/common/ai/src/airflow/providers/common/ai/toolsets/sql.py:
##########
@@ -848,3 +940,96 @@ def _enforce_allowed_tables(self, statements: list[Any]) 
-> None:
                 f"Query references tables that are not in the allowed tables 
list: "
                 f"{', '.join(sorted(set(disallowed)))}. Use 
{self._build_tool_name('list_tables')} to see the allowed tables."
             )
+
+    def _enforce_allowed_columns(self, statements: list[Any], *, dialect: str 
| None) -> None:
+        """
+        Reject a parsed query that reads a column ``allowed_columns`` does not 
allow.
+
+        No-op when ``allowed_columns`` is unset, and for a query that reaches 
no table it
+        narrows: nothing is read from the database for those. Otherwise the 
columns of every
+        table the query reaches are resolved (see 
:func:`find_column_violations`) and any read of
+        a denied column, or any construct that cannot be traced to a column, 
is refused with
+        :class:`SQLSafetyError`. ``call_tool`` turns that into a 
``ModelRetry`` and
+        ``check_query`` reports it invalid.
+        """
+        if not self._column_policy:
+            return
+        scan = collect_table_references(statements, 
allowed_functions=self._allowed_functions)
+        keys = {
+            self._canonical_ref(catalog, schema or self._schema, table)
+            for catalog, schema, table in scan.tables
+        }
+        if keys.isdisjoint(self._column_policy):
+            return
+        table_columns = {key: self._get_table_column_names(key) for key in 
keys}
+        denied: set[str] = set()
+        ambiguous: set[str] = set()
+        unverifiable: set[str] = set()
+        output_aliases: set[str] = set()
+        for statement in statements:
+            found = find_column_violations(
+                statement,
+                column_policy=self._column_policy,
+                table_columns=table_columns,
+                default_schema=self._schema,
+                dialect=dialect,
+            )
+            denied.update(found.denied)
+            ambiguous.update(found.ambiguous)
+            unverifiable.update(found.unverifiable)
+            output_aliases.update(found.output_aliases)
+        get_schema = self._build_tool_name("get_schema")
+        # Only whether the name is an output alias decides this, never whether 
a column of that
+        # name exists, so the hint cannot be used to tell.
+        alias_hint = (
+            f" {', '.join(sorted(output_aliases))} is an output alias, which 
outside a bare ORDER BY "
+            "may be read as a column: write the expression itself or its 
position (for example "
+            "GROUP BY 1) instead."
+            if output_aliases
+            else ""
+        )
+        if unverifiable:
+            raise SQLSafetyError(
+                f"Query uses a construct that cannot be checked against 
allowed_columns: "
+                f"{'; '.join(sorted(unverifiable))}. List the allowed columns 
explicitly: "
+                f"use {get_schema} to see them."
+            )
+        if ambiguous:
+            raise SQLSafetyError(
+                f"Query has columns that cannot be resolved to exactly one 
table: "
+                f"{', '.join(sorted(ambiguous))}. Qualify each column with its 
table or alias, e.g. c.name.{alias_hint}"
+            )
+        if denied:
+            raise SQLSafetyError(
+                f"Query reads columns that are not allowed or do not exist: "
+                f"{', '.join(sorted(denied))}. Use {get_schema} to see the 
columns you may query.{alias_hint}"
+            )
+
+    def _get_table_column_names(self, key: tuple[str | None, str | None, str]) 
-> tuple[str, ...]:
+        """Return the columns of the table with canonical ``key``, read from 
the database once."""
+        if key in self._table_column_names:
+            return self._table_column_names[key]
+        if self._reflected_tables is None:
+            self._reflected_tables = {
+                self._canonical_ref("", schema, name): (schema, name)
+                for schema, name, _ in self._find_allowed_tables()

Review Comment:
   `_find_allowed_tables` only lists tables (`get_table_names`), so a view in 
`allowed_tables` is "not found" here. Once `allowed_columns` is set, a query 
joining a view to a restricted table is refused, though it runs without 
`allowed_columns`, and a view can't be restricted itself. Could this lookup 
also check `get_view_names()`? Adding views to `_find_allowed_tables` itself 
would change `list_tables` too.



##########
providers/common/ai/src/airflow/providers/common/ai/toolsets/sql.py:
##########
@@ -848,3 +940,96 @@ def _enforce_allowed_tables(self, statements: list[Any]) 
-> None:
                 f"Query references tables that are not in the allowed tables 
list: "
                 f"{', '.join(sorted(set(disallowed)))}. Use 
{self._build_tool_name('list_tables')} to see the allowed tables."
             )
+
+    def _enforce_allowed_columns(self, statements: list[Any], *, dialect: str 
| None) -> None:
+        """
+        Reject a parsed query that reads a column ``allowed_columns`` does not 
allow.
+
+        No-op when ``allowed_columns`` is unset, and for a query that reaches 
no table it
+        narrows: nothing is read from the database for those. Otherwise the 
columns of every
+        table the query reaches are resolved (see 
:func:`find_column_violations`) and any read of
+        a denied column, or any construct that cannot be traced to a column, 
is refused with
+        :class:`SQLSafetyError`. ``call_tool`` turns that into a 
``ModelRetry`` and
+        ``check_query`` reports it invalid.
+        """
+        if not self._column_policy:
+            return
+        scan = collect_table_references(statements, 
allowed_functions=self._allowed_functions)
+        keys = {
+            self._canonical_ref(catalog, schema or self._schema, table)

Review Comment:
   No toolset test sets `schema` with `allowed_columns`, so changing this to 
`schema`, or `default_schema=self._schema` below to `None`, leaves the tests 
green while `SELECT email FROM customers` runs. A case with `schema="public"` 
and a bare `customers` would hold both.



##########
providers/common/ai/docs/toolsets/sql.rst:
##########
@@ -187,6 +189,121 @@ Postgres, which refuses it, and the model gets ``The 
query tool failed: permissi
 denied for table secrets``. :ref:`allowed-tables-enforcement` lists what the 
parser
 checks and where it stops.
 
+.. _sql-toolset-allowed-columns:
+
+Restricting columns
+-------------------
+
+``allowed_tables`` narrows the agent to tables. When several teams share one 
service
+account, ``allowed_columns`` narrows it further, to some of the columns of 
those tables.
+This agent can query ``customers`` but cannot read ``customers.email``; 
``orders`` is
+untouched:
+
+.. code-block:: python
+
+    SQLToolset(
+        db_conn_id="postgres_default",
+        allowed_tables=["customers", "orders"],
+        allowed_columns={"customers": ["id", "name", "region"]},
+    )
+
+``allowed_columns`` requires ``allowed_tables``, and each key must be on that 
list, written
+the same way (``"customers"`` or ``"public.customers"``). Matching is 
case-insensitive. With no
+``schema`` set, ``"customers"`` and ``"public.customers"`` can be one table, 
so listing both in
+``allowed_tables`` without giving both the same ``allowed_columns`` list 
raises ``ValueError``,
+because the wider list would let the columns out through the other spelling. A
+table with no entry keeps all its columns. An empty list, ``{"customers": 
[]}``, allows no
+column at all, so ``SELECT count(*) FROM customers`` runs and nothing else 
does.
+
+A column counts as read whenever the result depends on it, not only when it is 
selected.
+These are all refused while ``email`` is not allowed:
+
+- the select list, and a function or ``CASE`` expression over the column
+- ``WHERE``, ``HAVING``, ``JOIN ... ON`` and ``JOIN ... USING``, on either side
+- ``GROUP BY``, ``ORDER BY`` and ``DISTINCT``
+- a window's ``PARTITION BY`` and ``ORDER BY``
+- a subquery, a CTE body and every branch of a ``UNION``
+- a CTE column reached through an alias: ``WITH c AS (SELECT email AS e FROM 
customers)
+  SELECT 1 FROM c WHERE e IS NOT NULL``
+
+Each column is resolved to its table before the query runs. When the toolset 
cannot tell
+which table a column belongs to, it refuses the query instead of guessing:
+
+- A ``*`` or ``t.*`` in a query over a restricted table, wherever it sits: in 
the select
+  list, in a function such as Snowflake ``OBJECT_CONSTRUCT(*)`` or in a 
filter. The only
+  exception is the argument of a plain ``COUNT(*)``. Name the allowed columns 
instead.
+  A DuckDB ``COLUMNS(...)`` expression is refused too.
+- A bare column name that matches no table in the query, or more than one. 
Qualify it with
+  its table or alias.
+- A quoted column identifier (``"email"``), because the allow-list is matched
+  case-insensitively and a quoted name is not.
+- A ``NATURAL JOIN`` and a whole-row reference such as ``row_to_json(c)``, 
which read
+  columns without naming them.
+- ``DESCRIBE`` and, with ``allow_writes=True``, any ``INSERT``, ``UPDATE`` or 
``DELETE`` that
+  reaches a restricted table. A write can read a column too (``UPDATE 
customers SET name =
+  email``). Use ``get_schema`` to see the columns.
+
+Other constructs sqlglot does not resolve to a column, for example some 
``LATERAL`` and
+``PIVOT`` forms, may be refused as well. ``COUNT(*)`` and ``EXISTS (SELECT 1 
...)`` read no
+column and pass. These legitimate shapes are refused too, because the check 
cannot tell them
+from a read:
+
+- ``EXISTS (SELECT * FROM customers ...)``: write ``SELECT 1`` instead.
+- An output alias used anywhere but a bare ``ORDER BY``, in a query that has a 
restricted table
+  in scope: ``GROUP BY``, ``HAVING``, ``QUALIFY``, ``WHERE``, a window or an 
``ORDER BY``
+  expression, as in ``SELECT count(*) AS n FROM customers GROUP BY id HAVING n 
> 1``. This holds
+  on every dialect. A database may read the name as a column instead of the 
alias, so the
+  check cannot tell the two apart. Group, filter or sort by the expression 
itself or by its
+  position (``GROUP BY 1``). The same query over a table with no 
``allowed_columns`` entry
+  passes.
+- A bare ``ORDER BY`` output name (``ORDER BY n``) passes on PostgreSQL, 
MySQL, SQLite and
+  DuckDB, which read it as the output column, and is refused on a dialect 
where that was not
+  verified, or when the dialect is unknown. An ``ORDER BY`` expression such as
+  ``lower(email)`` is refused everywhere, because it reads the column.
+
+The refusal names the column, and the sentence is the same whether the column 
is denied or

Review Comment:
   This doesn't hold for a bare name that an unrestricted table also has. With 
`customers` restricted and joined to `orders`, which has a `phone` column, 
`WHERE phone = 'x'` is refused when `customers` also has a hidden `phone` and 
runs when it doesn't, so the agent learns whether it exists. `USING (phone)` 
and an unreferenced CTE body also answer differently for a denied and a missing 
name. Only names leak, so narrowing the sentence may be enough (it's repeated 
in `agent_security.rst`, the `SQLToolset` docstring and 
`find_column_violations`), unless you'd rather refuse bare names whenever a 
restricted table is joined.



##########
providers/common/ai/src/airflow/providers/common/ai/utils/sql_validation.py:
##########
@@ -412,6 +416,416 @@ def collect_table_references(
     return TableScan(tables=tables, unverifiable_sources=unverifiable)
 
 
+#: ``(catalog, schema, table)``, each part case-folded, ``None`` when absent.
+_TableKey = tuple[str | None, str | None, str]
+
+# Stands in for "no default schema" when handing tables to sqlglot, which 
wants every
+# table in its schema mapping at the same depth. The qualified SQL never 
leaves this module.
+_DEFAULT_SCHEMA_PLACEHOLDER = "__airflow_default_schema__"
+
+
+class ColumnScan(NamedTuple):
+    """Result of :func:`find_column_violations`."""
+
+    #: ``table.column`` for every column read of a restricted table that is 
not allowed, or
+    #: not found on it. Sorted and unique.
+    denied: list[str]
+    #: Bare column names that match no source, or more than one, so no table 
can be named.
+    ambiguous: list[str]
+    #: Constructs whose column reads cannot be traced (``SELECT *`` on a 
restricted table, a
+    #: quoted column identifier, a statement that is not a query).
+    unverifiable: list[str]
+    #: Names in ``denied`` or ``ambiguous`` that are an output alias of their 
SELECT, read as a
+    #: column outside a bare ORDER BY. Whether the name is a column of any 
table plays no part.
+    output_aliases: list[str]
+
+
+def _get_table_key(table: exp.Table, default_schema: str | None) -> _TableKey:
+    """Return the case-folded key of ``table``, filling in ``default_schema`` 
for an unqualified one."""
+    schema = table.db or default_schema
+    return (
+        table.catalog.casefold() if table.catalog else None,
+        schema.casefold() if schema else None,
+        table.name.casefold(),
+    )
+
+
+def _find_restricted_tables(
+    statement: exp.Expr, column_policy: Mapping[_TableKey, frozenset[str]], 
default_schema: str | None
+) -> list[str]:
+    """
+    List the tables in ``statement`` that have a column policy.
+
+    A table is matched by name only, so a CTE that shares a restricted table's 
name is
+    counted too. Over-matching just means the full column check runs on a 
query that did
+    not need it.
+    """
+    return sorted(
+        {
+            ".".join(part for part in (table.catalog, table.db, table.name) if 
part)
+            for table in statement.find_all(exp.Table)
+            if table.name and _get_table_key(table, default_schema) in 
column_policy
+        }
+    )
+
+
+def _has_quoted_column_identifier(statement: exp.Expr) -> bool:
+    """Report whether a column reference or ``USING`` list in ``statement`` 
has a quoted identifier."""
+    for column in statement.find_all(exp.Column):
+        parts = (column.args.get(part) for part in ("this", "table", "db", 
"catalog"))
+        if any(isinstance(part, exp.Identifier) and part.args.get("quoted") 
for part in parts):
+            return True
+    return any(
+        identifier.args.get("quoted")
+        for join in statement.find_all(exp.Join)
+        for using in join.args.get("using") or []
+        for identifier in using.find_all(exp.Identifier)
+    )
+
+
+def _find_source(scope: Scope, name: str) -> exp.Table | Scope | None:
+    """Resolve a table alias in ``scope``, then in the enclosing scopes (a 
correlated subquery)."""
+    current: Scope | None = scope
+    while current is not None:
+        if name in current.sources:
+            return current.sources[name]
+        current = current.parent
+    return None
+
+
+def _find_enclosing_scope(node: exp.Expr, scope_by_node: Mapping[int, Scope]) 
-> Scope | None:
+    """Return the scope of the nearest query that contains ``node``."""
+    current: exp.Expr | None = node.parent
+    while current is not None and id(current) not in scope_by_node:
+        current = current.parent
+    return scope_by_node[id(current)] if current is not None else None
+
+
+def _get_output_names(scope: Scope) -> set[str]:
+    """Return the case-folded names of the columns a query scope produces."""
+    expression = scope.expression
+    return (
+        {name.casefold() for name in expression.named_selects} if 
isinstance(expression, exp.Query) else set()
+    )
+
+
+def _find_star_reads(
+    statement: exp.Expr, column_policy: Mapping[_TableKey, frozenset[str]], 
default_schema: str | None
+) -> list[str]:
+    """
+    Describe every wildcard that expands to the columns of a restricted table.
+
+    Any ``*`` counts, wherever it sits, because a function can take it 
(Snowflake
+    ``OBJECT_CONSTRUCT(*)``) and a filter can read through it. The one 
exception is the
+    argument of a plain ``COUNT(*)``, which reads no column. A DuckDB 
``COLUMNS(...)``
+    expression is refused whatever it matches.
+    """
+    found: set[str] = set()
+    copy = statement.copy()
+    scopes = traverse_scope(copy)
+    scope_by_node = {id(scope.expression): scope for scope in scopes}
+
+    def list_restricted(sources: Sequence[exp.Table | Scope | None]) -> 
list[str]:
+        return [
+            source.name
+            for source in sources
+            if isinstance(source, exp.Table) and _get_table_key(source, 
default_schema) in column_policy
+        ]
+
+    for node in copy.find_all(exp.Star, exp.Columns):
+        scope = _find_enclosing_scope(node, scope_by_node)
+        if isinstance(node, exp.Columns):
+            found.add("a COLUMNS(...) expression")
+            continue
+        parent = node.parent
+        if isinstance(parent, exp.Count) and parent.this is node:
+            continue
+        if isinstance(parent, exp.Column):
+            sources = [_find_source(scope, parent.table)] if scope is not None 
else []
+        else:
+            sources = [source for _, source in 
scope.selected_sources.values()] if scope is not None else []
+        found.update(f"SELECT * on {name}" for name in 
list_restricted(sources))
+        if scope is None:
+            found.add("a * wildcard outside any query")
+    return sorted(found)
+
+
+def _get_qualified_key(table: exp.Table) -> _TableKey:
+    """Return the key of a table in qualified SQL, where "no default schema" 
is the placeholder."""
+    catalog, schema, name = _get_table_key(table, None)
+    return (catalog, None if schema == _DEFAULT_SCHEMA_PLACEHOLDER else 
schema, name)
+
+
+# Dialects where a bare name in ORDER BY is the output column of that name, 
not an input column.
+# PostgreSQL and MySQL document it; SQLite and DuckDB were run against a table 
with a same-named
+# column. The sqlglot name of an unresolved dialect is ``None``, which is not 
in the set: the
+# name is then read as a column, so a restricted table's column is not hidden 
behind an alias.
+_ORDER_BY_OUTPUT_NAME_DIALECTS: frozenset[str] = frozenset({"postgres", 
"mysql", "sqlite", "duckdb"})
+
+
+class _ColumnReadFinder:
+    """Settles, for one qualified statement, which column reads a restricted 
table does not allow."""
+
+    def __init__(
+        self,
+        column_policy: Mapping[_TableKey, frozenset[str]],
+        mapped_names: Mapping[_TableKey, set[str]],
+        scope_by_node: Mapping[int, Scope],
+        dialect: str | None,
+    ) -> None:
+        self._orders_by_output_name = dialect in _ORDER_BY_OUTPUT_NAME_DIALECTS
+        self._column_policy = column_policy
+        self._mapped_names = mapped_names
+        self._scope_by_node = scope_by_node
+        self.denied: set[str] = set()
+        self.ambiguous: set[str] = set()
+        self.unverifiable: set[str] = set()
+
+    def _is_restricted(self, source: exp.Table | Scope) -> bool:
+        return isinstance(source, exp.Table) and _get_qualified_key(source) in 
self._column_policy
+
+    def check_table_column(self, table: exp.Table, column: str) -> bool:
+        """Record a read of ``column`` on ``table`` that is not allowed or not 
found; return whether it was."""
+        key = _get_qualified_key(table)
+        name = column.casefold()
+        if key in self._column_policy and (
+            name not in self._column_policy[key] or name not in 
self._mapped_names[key]
+        ):
+            self.denied.add(f"{table.name.casefold()}.{name}")
+            return True
+        return False
+
+    def _has_column(self, source: exp.Table | Scope, name: str) -> bool:
+        if isinstance(source, exp.Table):
+            return name in self._mapped_names.get(_get_qualified_key(source), 
())
+        return name in _get_output_names(source)
+
+    def check_resolved_columns(self, scopes: Sequence[Scope]) -> set[int]:
+        """Check every column qualified with a table alias; return the ``id`` 
of each one it settled."""
+        settled: set[int] = set()
+        for scope in scopes:
+            for column in scope.columns:
+                if isinstance(column.this, exp.Star) or not column.table:
+                    continue
+                source = _find_source(scope, column.table)
+                if source is None:
+                    continue
+                settled.add(id(column))
+                if isinstance(source, exp.Table):
+                    self.check_table_column(source, column.name)
+        return settled
+
+    def check_whole_row_references(self, qualified: exp.Expr) -> None:
+        """Refuse a bare table alias (``SELECT c FROM t c``, 
``row_to_json(c)``), which is the whole row."""
+        for whole_row in qualified.find_all(exp.TableColumn):
+            enclosing = _find_enclosing_scope(whole_row, self._scope_by_node)
+            source = _find_source(enclosing, whole_row.name) if enclosing is 
not None else None
+            if isinstance(source, exp.Table) and self._is_restricted(source):
+                self.unverifiable.add(f"a whole-row reference to 
{source.name}")
+
+    def check_unsettled_columns(self, qualified: exp.Expr, settled: set[int]) 
-> None:
+        """
+        Resolve what ``check_resolved_columns`` left.
+
+        ``Scope.columns`` leaves out an unqualified column under HAVING or 
QUALIFY, and
+        qualification leaves an ambiguous or unknown one unqualified.
+        """
+        for column in qualified.find_all(exp.Column):
+            if isinstance(column.this, exp.Star) or id(column) in settled:
+                continue
+            name = column.name.casefold()
+            scope = _find_enclosing_scope(column, self._scope_by_node)
+            if column.table or scope is None:
+                self.denied.add(f"{column.table.casefold()}.{name}" if 
column.table else name)
+            elif isinstance(scope.expression, exp.Select):
+                self.resolve_bare_column(column, name, scope)
+
+    def resolve_bare_column(self, column: exp.Column, name: str, scope: Scope) 
-> None:
+        """
+        Resolve an unqualified column the way the database does: the innermost 
query that has it.
+
+        A subquery sees its own sources first and then those of every 
enclosing query, so a
+        correlated ``HAVING email`` over an unrelated table still reads the 
outer
+        ``customers.email``. A name that no query has, or that is only an 
output alias of the
+        select, is reported whenever a restricted table is in scope: a 
database may read the
+        name as a column the cached column list does not know, and whether an 
alias were
+        accepted would show whether the restricted table has a column of that 
name. The one
+        exception is a bare name in ORDER BY on a dialect known to read it as 
the output column.
+        """
+        select = scope.expression
+        output_names = _get_output_names(scope)
+        is_alias = name in output_names and not _is_projection(column, select)
+        ordered = column.parent
+        if (
+            self._orders_by_output_name
+            and isinstance(ordered, exp.Ordered)
+            and isinstance(ordered.parent, exp.Order)
+            and ordered.parent.parent is select
+            and name in output_names
+        ):
+            return
+        self._report_unresolved_column(name, scope, is_alias=is_alias)
+
+    def _report_unresolved_column(self, name: str, scope: Scope, *, is_alias: 
bool) -> None:
+        """Record what a bare ``name`` reads when it is denied, ambiguous or 
unknown."""
+        restricted: list[exp.Table] = []
+        level: Scope | None = scope
+        while level is not None:
+            sources = [source for _, source in level.selected_sources.values()]
+            restricted.extend(s for s in sources if isinstance(s, exp.Table) 
and self._is_restricted(s))
+            matches = [source for source in sources if 
self._has_column(source, name)]
+            if matches:
+                # A denied column is reported even when another table also has 
the name, so the
+                # answer does not depend on whether the name exists elsewhere.
+                visible = [
+                    source
+                    for source in matches
+                    if not (isinstance(source, exp.Table) and 
self.check_table_column(source, name))
+                ]
+                if len(visible) > 1 and len(visible) == len(matches):
+                    self.ambiguous.add(name)
+                return
+            level = level.parent
+        if is_alias and not restricted:
+            return
+        if restricted:
+            for table in restricted:
+                self.denied.add(f"{table.name.casefold()}.{name}")
+            return
+        sources = [source for _, source in scope.selected_sources.values()]
+        if len(sources) > 1:
+            self.ambiguous.add(name)
+        elif not (len(sources) == 1 and isinstance(sources[0], exp.Table)):
+            self.denied.add(name)
+
+    def find_output_aliases(self, qualified: exp.Expr) -> set[str]:
+        """
+        Return the reported names that are also an output alias where they are 
used.
+
+        Decided by the name and its position alone, never by whether a table 
has such a column,
+        and over every column whichever way it was resolved, so that it cannot 
tell the two apart.
+        """
+        reported = {entry.rsplit(".", 1)[-1] for entry in (*self.denied, 
*self.ambiguous)}
+        aliases: set[str] = set()
+        for column in qualified.find_all(exp.Column):
+            name = column.name.casefold()
+            scope = _find_enclosing_scope(column, self._scope_by_node)
+            if (
+                name in reported
+                and scope is not None
+                and isinstance(scope.expression, exp.Select)
+                and name in _get_output_names(scope)
+                and not _is_projection(column, scope.expression)
+            ):
+                aliases.add(name)
+        return aliases
+
+
+def _describe_statement(statement: exp.Expr, where: str) -> str:
+    """Name a statement type for a message, with the article that fits it."""
+    name = type(statement).__name__
+    return f"{'an' if name[0] in 'AEIOU' else 'a'} {name} statement on {where}"
+
+
+def _is_projection(column: exp.Column, select: exp.Expr) -> bool:
+    """Report whether ``column`` sits in the select list of ``select`` rather 
than a clause."""
+    node: exp.Expr = column
+    while node.parent is not None and node.parent is not select:
+        node = node.parent
+    return node.arg_key == "expressions"
+
+
+def find_column_violations(
+    statement: exp.Expr,
+    *,
+    column_policy: Mapping[_TableKey, frozenset[str]],
+    table_columns: Mapping[_TableKey, Sequence[str]],
+    default_schema: str | None,
+    dialect: str | None,
+) -> ColumnScan:
+    """
+    Report every read of a column that a restricted table does not allow.
+
+    A column is read whenever the result depends on it: in the select list, 
but also in
+    ``WHERE``, ``JOIN``, ``GROUP BY``, a window, or a CTE body reached through 
an alias.
+    So each column is resolved to its table with sqlglot's qualification and 
scope
+    analysis, not by looking at the select list. Anything that cannot be 
resolved to a
+    table is reported, never allowed: this is a guardrail, so a doubt means 
refuse.
+
+    A column that is denied and one that does not exist on a restricted table 
are reported
+    the same way, and so is an output alias used where the database may read 
it as a column
+    (``GROUP BY``, ``HAVING``, ``QUALIFY``, ``WHERE``, a window, an ``ORDER 
BY`` expression)
+    in a query that has a restricted table in scope, so the result never tells 
whether the
+    restricted table has a column of a given name. Only a bare ``ORDER BY`` 
name passes, and
+    only on a dialect known to read it as the output column.
+
+    :param statement: One parsed statement. It is not modified; the work runs 
on copies.
+    :param column_policy: Allowed column names (case-folded) of each 
restricted table.
+    :param table_columns: Every column of each table the statement reaches, 
restricted or
+        not (resolving an unqualified column needs all the tables in scope).
+    :param default_schema: Schema of an unqualified table reference, or 
``None``.
+    :param dialect: sqlglot dialect used to normalize identifiers.
+    :raises SQLSafetyError: If sqlglot cannot qualify the statement.
+    """
+    restricted = _find_restricted_tables(statement, column_policy, 
default_schema)
+    if not restricted:
+        return ColumnScan([], [], [], [])
+    where = ", ".join(restricted)
+
+    # DESCRIBE, EXPLAIN and DML can read a column (``UPDATE t SET a = 
secret``) through scopes
+    # qualification is not verified to cover, so they are refused outright.
+    if not isinstance(statement, exp.Query):
+        return ColumnScan([], [], [_describe_statement(statement, where)], [])
+    if (nested := next((n for n in statement.walk() if isinstance(n, 
_DML_TYPES)), None)) is not None:

Review Comment:
   No test reaches this line: every write case in the tests is a top-level 
statement, which the check above refuses first. With it removed the suite stays 
green and `WITH d AS (DELETE FROM customers WHERE email LIKE 'a%' RETURNING id) 
SELECT id FROM d` gets through. Could that go in 
`test_writes_reading_denied_column_are_refused`?



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to