-
Notifications
You must be signed in to change notification settings - Fork 182
feat(wren): add strict query mode for SQL policy enforcement #1500
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
goldmedal
wants to merge
4
commits into
Canner:main
Choose a base branch
from
goldmedal:claude/elated-almeida
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
cfb1432
feat(wren): add strict query mode for SQL policy enforcement
goldmedal 636d360
fix(wren): address code review — type validation, CTE scope, TVF bloc…
goldmedal 0d479da
fix(wren): expanduser for WREN_HOME and fail closed on denied_functions
goldmedal f7d03e0
fix(wren): catch OSError alongside WrenError in CLI config loading
goldmedal File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,74 @@ | ||
| """Wren CLI configuration loaded from ~/.wren/config.json.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from dataclasses import dataclass, field | ||
| from pathlib import Path | ||
|
|
||
| from wren.model.error import ErrorCode, WrenError | ||
|
|
||
|
|
||
| @dataclass(frozen=True) | ||
| class WrenConfig: | ||
| """Immutable configuration for the Wren CLI. | ||
|
|
||
| Attributes | ||
| ---------- | ||
| strict_mode: | ||
| When ``True``, all table references in SQL must be defined in the MDL | ||
| manifest. Queries referencing non-MDL tables are rejected. | ||
| denied_functions: | ||
| Set of function names (lowercase) that are forbidden in SQL queries. | ||
| Matching is case-insensitive. | ||
| """ | ||
|
|
||
| strict_mode: bool = False | ||
| denied_functions: frozenset[str] = field(default_factory=frozenset) | ||
|
|
||
|
|
||
| def load_config(wren_home: Path) -> WrenConfig: | ||
| """Load configuration from ``wren_home/config.json``. | ||
|
|
||
| Returns default ``WrenConfig`` when the file does not exist. | ||
| Raises ``WrenError`` when the file exists but contains invalid JSON. | ||
| """ | ||
| config_path = wren_home / "config.json" | ||
| if not config_path.exists(): | ||
| return WrenConfig() | ||
|
|
||
| try: | ||
| raw = json.loads(config_path.read_text()) | ||
| except (json.JSONDecodeError, OSError) as e: | ||
| raise WrenError( | ||
| ErrorCode.GENERIC_USER_ERROR, | ||
| f"Failed to read {config_path}: {e}", | ||
| ) from e | ||
|
|
||
| if not isinstance(raw, dict): | ||
| raise WrenError( | ||
| ErrorCode.GENERIC_USER_ERROR, | ||
| f"{config_path} must contain a JSON object.", | ||
| ) | ||
|
|
||
| strict_mode_raw = raw.get("strict_mode", False) | ||
| if not isinstance(strict_mode_raw, bool): | ||
| raise WrenError( | ||
| ErrorCode.GENERIC_USER_ERROR, | ||
| f"{config_path}: 'strict_mode' must be a JSON boolean.", | ||
| ) | ||
|
|
||
| denied_raw = raw.get("denied_functions", []) | ||
| if not isinstance(denied_raw, list): | ||
| raise WrenError( | ||
| ErrorCode.GENERIC_USER_ERROR, | ||
| f"{config_path}: 'denied_functions' must be a JSON array.", | ||
| ) | ||
| if any(not isinstance(f, str) for f in denied_raw): | ||
| raise WrenError( | ||
| ErrorCode.GENERIC_USER_ERROR, | ||
| f"{config_path}: 'denied_functions' must contain only strings.", | ||
| ) | ||
| denied_functions = frozenset(f.lower() for f in denied_raw) | ||
|
|
||
| return WrenConfig(strict_mode=strict_mode_raw, denied_functions=denied_functions) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,120 @@ | ||
| """SQL policy validation for strict query mode. | ||
|
|
||
| Validates that a parsed SQL AST only references tables defined in the MDL | ||
| manifest and does not use any denied functions. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from sqlglot import exp | ||
|
|
||
| from wren.config import WrenConfig | ||
| from wren.model.error import ErrorCode, ErrorPhase, WrenError | ||
|
|
||
|
|
||
| def validate_sql_policy( | ||
| ast: exp.Expression, | ||
| model_names: set[str], | ||
| config: WrenConfig, | ||
| ) -> None: | ||
| """Raise ``WrenError`` if the SQL violates strict-mode policies. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| ast: | ||
| Parsed sqlglot AST of the user query. | ||
| model_names: | ||
| Set of model names defined in the MDL manifest. | ||
| config: | ||
| Wren configuration with strict_mode and denied_functions settings. | ||
| """ | ||
| if config.strict_mode: | ||
| _check_tables(ast, model_names) | ||
| if config.denied_functions: | ||
| _check_functions(ast, config.denied_functions) | ||
|
|
||
|
|
||
| def _visible_cte_names(node: exp.Expression) -> set[str]: | ||
| """Return CTE names visible at *node*'s scope by walking up the AST.""" | ||
| names: set[str] = set() | ||
| cursor = node.parent | ||
| while cursor is not None: | ||
| # A WITH clause is visible to its parent SELECT and siblings. | ||
| with_clause = cursor.args.get("with_") if hasattr(cursor, "args") else None | ||
| if isinstance(with_clause, exp.With): | ||
| for cte in with_clause.expressions: | ||
| alias = cte.args.get("alias") | ||
| if alias: | ||
| cte_name = ( | ||
| alias.this.name | ||
| if isinstance(alias.this, exp.Identifier) | ||
| else str(alias.this) | ||
| ) | ||
| names.add(cte_name.lower()) | ||
| cursor = cursor.parent | ||
| return names | ||
|
|
||
|
|
||
| def _check_tables( | ||
| ast: exp.Expression, | ||
| model_names: set[str], | ||
| ) -> None: | ||
| model_names_lower = {n.lower() for n in model_names} | ||
|
|
||
| for table in ast.find_all(exp.Table): | ||
| name = table.name | ||
| if not name: | ||
| # Table nodes with no name are table-valued functions | ||
| # (e.g. read_csv(), generate_series()). Block them in strict mode. | ||
| sql_text = table.sql() | ||
| if sql_text: | ||
| raise WrenError( | ||
| ErrorCode.MODEL_NOT_FOUND, | ||
| f"Table-valued function '{sql_text}' is not allowed. " | ||
| "In strict mode, all table references must correspond to MDL models.", | ||
| phase=ErrorPhase.SQL_POLICY_CHECK, | ||
| ) | ||
| continue | ||
| name_lower = name.lower() | ||
| if name_lower in model_names_lower: | ||
| continue | ||
| if name_lower in _visible_cte_names(table): | ||
| continue | ||
| raise WrenError( | ||
| ErrorCode.MODEL_NOT_FOUND, | ||
| f"Table '{name}' is not defined in the MDL manifest. " | ||
| "In strict mode, all table references must correspond to MDL models.", | ||
| phase=ErrorPhase.SQL_POLICY_CHECK, | ||
| ) | ||
|
|
||
| # Func subclasses used as FROM sources (e.g. UNNEST) produce no exp.Table | ||
| # node at all. Scan for Func nodes inside From clauses. | ||
| for from_clause in ast.find_all(exp.From): | ||
| source = from_clause.this | ||
| if isinstance(source, exp.Alias): | ||
| source = source.this | ||
| if isinstance(source, exp.Func): | ||
| raise WrenError( | ||
| ErrorCode.MODEL_NOT_FOUND, | ||
| f"Table-valued function '{source.sql()}' is not allowed. " | ||
| "In strict mode, all table references must correspond to MDL models.", | ||
| phase=ErrorPhase.SQL_POLICY_CHECK, | ||
| ) | ||
|
|
||
|
|
||
| def _check_functions( | ||
| ast: exp.Expression, | ||
| denied: frozenset[str], | ||
| ) -> None: | ||
| for func in ast.find_all(exp.Func): | ||
| if isinstance(func, exp.Anonymous): | ||
| name = func.name | ||
| else: | ||
| name = type(func).key | ||
| if name.lower() in denied: | ||
| raise WrenError( | ||
| ErrorCode.BLOCKED_FUNCTION, | ||
| f"Function '{name}' is not allowed. " | ||
| "This function is on the denied list.", | ||
| phase=ErrorPhase.SQL_POLICY_CHECK, | ||
| ) |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.