Skip to content

feat(bigquery): support authorized views with dataset restrictions#2561

Open
Genesis929 wants to merge 12 commits intogoogleapis:mainfrom
Genesis929:allowed_view_fix
Open

feat(bigquery): support authorized views with dataset restrictions#2561
Genesis929 wants to merge 12 commits intogoogleapis:mainfrom
Genesis929:allowed_view_fix

Conversation

@Genesis929
Copy link
Copy Markdown
Contributor

Refactors BigQuery query validation to support Authorized Views by combining behavioral analysis (Dry Run) with explicit reference auditing.

Working Logic:

The validation process uses a coordinated check:

  1. Behavioral Detection (Dry Run): Identifies physical tables accessed by the query. If tables are found and all are allowed, the query is permitted immediately.
  2. Explicit Reference Audit (Lexical Search): If the dry run identifies disallowed tables, a lexical scanner checks the SQL text for explicit mentions. Access is permitted if the disallowed tables are absent from the SQL, which correctly identifies Authorized View scenarios.
  3. Fallback Intent Check: If no tables are found (e.g. DDL/Dynamic SQL) or to confirm the final intent, a local SQL parser validates the query to catch restricted operations and disallowed identifiers.

Limitations:

  • Structural vs. Lexical Gap: SQL parsing complexity makes it difficult to understand all structural nuances; lexical search provides a safer layer to detect user intent where the structural parser might fall short.
  • False Positives: Queries may be blocked if non-table identifiers (like column aliases) exactly match a restricted table name. This prioritizes data security over permissive access.

Changes:

  • Added IsAnyTableExplicitlyReferenced using a lexical state machine.
  • Reorganized ValidateQueryAgainstAllowedDatasets to optimize for performance (early return) and safety (coordinated checks).
  • Simplified tool code by removing redundant mock indirection.
  • Added tests for Authorized Views and complex table ID formats.

Description

Should include a concise description of the changes (bug or feature), it's
impact, along with a summary of the solution

PR Checklist

Thank you for opening a Pull Request! Before submitting your PR, there are a
few things you can do to make sure it goes smoothly:

  • Make sure you reviewed
    CONTRIBUTING.md
  • Make sure to open an issue as a
    bug/issue
    before writing your code! That way we can discuss the change, evaluate
    designs, and agree on the general idea
  • Ensure the tests and linter pass
  • Code coverage does not decrease (if any source code was changed)
  • Appropriate docs were updated (if necessary)
  • Make sure to add ! if this involve a breaking change

🛠️ Fixes #<issue_number_goes_here>

Refactors BigQuery query validation to support Authorized Views by
combining behavioral analysis (Dry Run) with explicit reference auditing.

### Working Logic:
The validation process uses a coordinated check:
1. Behavioral Detection (Dry Run): Identifies physical tables accessed
   by the query. If tables are found and all are allowed, the query is
   permitted immediately.
2. Explicit Reference Audit (Lexical Search): If the dry run identifies
   disallowed tables, a lexical scanner checks the SQL text for explicit
   mentions. Access is permitted if the disallowed tables are absent
   from the SQL, which correctly identifies Authorized View scenarios.
3. Fallback Intent Check: If no tables are found (e.g. DDL/Dynamic SQL)
   or to confirm the final intent, a local SQL parser validates the query
   to catch restricted operations and disallowed identifiers.

### Limitations:
- Structural vs. Lexical Gap: SQL parsing complexity makes it difficult to
  understand all structural nuances; lexical search provides a safer
  layer to detect user intent where the structural parser might fall short.
- False Positives: Queries may be blocked if non-table identifiers
  (like column aliases) exactly match a restricted table name. This
  prioritizes data security over permissive access.

### Changes:
- Added IsAnyTableExplicitlyReferenced using a lexical state machine.
- Reorganized ValidateQueryAgainstAllowedDatasets to optimize for performance
  (early return) and safety (coordinated checks).
- Simplified tool code by removing redundant mock indirection.
- Added tests for Authorized Views and complex table ID formats.
@gemini-code-assist
Copy link
Copy Markdown
Contributor

Summary of Changes

Hello @Genesis929, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances BigQuery query validation by introducing robust support for authorized views when dataset restrictions are in place. The refactored validation process now intelligently combines BigQuery's dry run capabilities with a new lexical analysis step. This ensures that queries accessing data through authorized views are correctly permitted, while direct access to restricted underlying tables remains blocked, improving both security and flexibility.

Highlights

  • Authorized View Support: Implemented a new BigQuery query validation mechanism that explicitly supports authorized views when dataset restrictions are active.
  • Enhanced Query Validation Logic: Introduced a coordinated validation process combining BigQuery dry run analysis with a new lexical scanner (IsAnyTableExplicitlyReferenced) to accurately identify and permit authorized view scenarios.
  • Refactored BigQuery Tooling: Centralized query validation logic into a new ValidateQueryAgainstAllowedDatasets function, simplifying and standardizing its use across various BigQuery tools.
  • Improved SQL Parsing: The internal SQL parser was enhanced to better handle aliases, Common Table Expressions (CTEs), and various identifier formats, improving accuracy in table detection.
  • Comprehensive Testing: Added new integration tests specifically for authorized views and expanded existing tests to cover complex SQL parsing and restricted operations.
  • Documentation Update: Updated the bigquery-execute-sql documentation to reflect the new support for authorized views and clarify the behavior of dataset restrictions.
Changelog
  • docs/en/resources/tools/bigquery/bigquery-execute-sql.md
    • Updated documentation to clarify that dataset restrictions now support authorized views and how the validation process works.
  • internal/tools/bigquery/bigqueryanalyzecontribution/bigqueryanalyzecontribution.go
    • Refactored query validation logic to delegate to the new ValidateQueryAgainstAllowedDatasets utility function.
  • internal/tools/bigquery/bigquerycommon/table_name_parser.go
    • Enhanced the SQL parser to track aliases and Common Table Expressions (CTEs).
    • Added a new function IsAnyTableExplicitlyReferenced for lexical scanning of table IDs.
    • Improved identifier parsing to correctly handle underscores and various quoting styles.
  • internal/tools/bigquery/bigquerycommon/table_name_parser_test.go
    • Expanded test coverage for the TableParser with cases involving aliases and CTEs.
    • Added new tests for the IsAnyTableExplicitlyReferenced function, covering various matching and non-matching scenarios.
  • internal/tools/bigquery/bigquerycommon/util.go
    • Introduced ValidateQueryAgainstAllowedDatasets, a central function that orchestrates query validation using dry runs, explicit reference checks, and a fallback SQL parser.
    • Defined DatasetValidator interface for checking allowed datasets.
  • internal/tools/bigquery/bigqueryexecutesql/bigqueryexecutesql.go
    • Modified the Invoke method to utilize the new ValidateQueryAgainstAllowedDatasets for BigQuery queries when dataset restrictions are active.
  • internal/tools/bigquery/bigqueryforecast/bigqueryforecast.go
    • Refactored query validation logic to delegate to the new ValidateQueryAgainstAllowedDatasets utility function.
  • src/google-cloud-bigquery-storage
    • Added a subproject commit for google-cloud-bigquery-storage, indicating an update to this dependency.
  • tests/bigquery/bigquery_integration_test.go
    • Added a new integration test suite for BigQuery authorized views, including scenarios for successful view queries and failed direct table access.
    • Updated expected error messages for restricted operations to be more generic.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces support for authorized views in BigQuery dataset restrictions through a multi-layered validation approach, refactoring core logic into ValidateQueryAgainstAllowedDatasets and enhancing the SQL parser. While the feature's intent is sound, the current implementation has significant security vulnerabilities: the lexical scanner and validation logic can be bypassed using SQL comments within identifiers, and restricted operations like EXECUTE IMMEDIATE can be circumvented via multi-statement queries. These critical bypasses must be addressed to ensure robust dataset restriction enforcement. Additionally, the review identified high-severity regressions due to removed statement type validation, potentially leading to less clear error messages, and medium-severity performance concerns in the SQL parsing logic from repeated string allocations in loops.

Comment thread internal/tools/bigquery/bigquerycommon/table_name_parser.go Outdated
Comment thread internal/tools/bigquery/bigquerycommon/util.go
Comment thread internal/tools/bigquery/bigqueryforecast/bigqueryforecast.go Outdated
Comment thread internal/tools/bigquery/bigquerycommon/table_name_parser.go Outdated
Comment thread internal/tools/bigquery/bigquerycommon/table_name_parser.go Outdated
@Genesis929 Genesis929 marked this pull request as ready for review February 26, 2026 18:04
@Genesis929 Genesis929 requested a review from a team as a code owner February 26, 2026 18:04
@Genesis929 Genesis929 requested a review from a team as a code owner March 2, 2026 04:28
@duwenxin99
Copy link
Copy Markdown
Contributor

/gemini review

Copy link
Copy Markdown
Contributor

@gemini-code-assist gemini-code-assist Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces a sophisticated, multi-layered validation mechanism to support authorized views in BigQuery while enforcing dataset restrictions. The changes include a significant refactoring of the SQL parsing logic, centralizing validation, and adding comprehensive integration tests. The approach of combining a dry run, lexical analysis, and a fallback parser is robust. My feedback includes one suggestion to improve the user experience by providing more comprehensive error messages.

Comment on lines +121 to +123
if explicitlyReferenced {
return nil, fmt.Errorf("access to dataset '%s' is not allowed", strings.Join(strings.Split(violatingTables[0], ".")[:2], "."))
}
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

The current implementation reports only the first dataset that violates the access policy. This could be frustrating for a user if their query accesses multiple disallowed datasets, as they would have to fix them one by one. Consider reporting all unique violating datasets in the error message to improve the user experience. Note that this change would also require updating the corresponding integration tests that check for this error message.

if explicitlyReferenced {
	violatingDatasets := []string{}
	seenDatasets := make(map[string]struct{})
	for _, tableID := range violatingTables {
		datasetFQN := strings.Join(strings.Split(tableID, ".")[:2], ".")
		if _, seen := seenDatasets[datasetFQN]; !seen {
			violatingDatasets = append(violatingDatasets, fmt.Sprintf("'%s'", datasetFQN))
			seenDatasets[datasetFQN] = struct{}{}
		}
	}
	plural := ""
	if len(violatingDatasets) > 1 {
		plural = "s"
	}
	return nil, fmt.Errorf("access to dataset%s %s is not allowed", plural, strings.Join(violatingDatasets, ", "))
}

@duwenxin99 duwenxin99 added the priority: p2 Moderately-important priority. Fix may not be included in next release. label Mar 24, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority: p2 Moderately-important priority. Fix may not be included in next release.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants