bigquerycommon

package
v1.16.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func BQTypeStringFromToolType

func BQTypeStringFromToolType(toolType string) (string, error)

BQTypeStringFromToolType converts a tool parameter type string to a BigQuery standard SQL type string.

func DryRunQuery

func DryRunQuery(
	ctx context.Context,
	restService *bigqueryrestapi.Service,
	projectID string,
	location string,
	sql string,
	params []*bigqueryrestapi.QueryParameter,
	connProps []*bigqueryapi.ConnectionProperty,
	maximumBytesBilled int64,
	createSession bool,
) (*bigqueryrestapi.Job, error)

DryRunQuery performs a dry run of the SQL query to validate it and get metadata.

func InitializeDatasetParameters

func InitializeDatasetParameters(
	allowedDatasets []string,
	defaultProjectID string,
	projectKey, datasetKey string,
	projectDescription, datasetDescription string,
) (projectParam, datasetParam parameters.Parameter)

InitializeDatasetParameters generates project and dataset tool parameters based on allowedDatasets.

func IsAnyTableExplicitlyReferenced added in v1.14.0

func IsAnyTableExplicitlyReferenced(sql, defaultProjectID string, targetTableIDs []string) (bool, error)

IsAnyTableExplicitlyReferenced performs a lexical audit of the SQL to see if any of the target tables are explicitly named as identifiers. It correctly ignores names inside comments or strings.

func IsSystemResource added in v1.14.0

func IsSystemResource(datasetID, resourceID string) bool

IsSystemResource checks if a given dataset and table/function ID refer to a BigQuery system resource (like a built-in AI or ML function) that should be exempted from dataset restriction checks. Note: This function exempts system resources by dataset and resource name prefix (e.g. AI.FORECAST, ML.PREDICT). User-created datasets with these identical names will also be exempted; this is a known, acceptable tradeoff.

func StripSingleQuotes added in v1.4.0

func StripSingleQuotes(s string) string

StripSingleQuotes removes leading and trailing single quotes from a string if both are present.

func TableParser

func TableParser(sql, defaultProjectID string) ([]string, error)

TableParser parses a SQL query and returns a list of table IDs that it references. It is intended as a conservative fallback for when a dry run cannot be performed or analyzed.

func ValidColumnName added in v1.4.0

func ValidColumnName(s string) bool

ValidColumnName returns true if s is a safe BigQuery column name. Values that fail this check must not be interpolated as SQL identifiers or into single-quoted SQL string arguments that represent column references.

func ValidColumnParam added in v1.4.0

func ValidColumnParam(s string) bool

ValidColumnParam returns true if s (stripped of leading/trailing single quotes) is a safe column name.

func ValidContributionMetricParam added in v1.4.0

func ValidContributionMetricParam(s string) bool

ValidContributionMetricParam returns true if s (stripped of leading/trailing single quotes) is a safe contribution metric (does not contain single quotes).

func ValidTableID added in v1.4.0

func ValidTableID(s string) bool

ValidTableID returns true if s is a safe BigQuery table identifier of the form 'dataset.table' or 'project.dataset.table'. Values that fail this check must not be interpolated into backtick-quoted SQL.

func ValidateQueryAgainstAllowedDatasets added in v1.14.0

func ValidateQueryAgainstAllowedDatasets(
	ctx context.Context,
	restService *bigqueryrestapi.Service,
	projectID string,
	location string,
	sql string,
	params []*bigqueryrestapi.QueryParameter,
	connProps []*bigqueryapi.ConnectionProperty,
	validator DatasetValidator,
	maximumBytesBilled int64,
	createSession bool,
	opts ...ValidateOption,
) (*bigqueryrestapi.Job, util.ToolboxError)

ValidateQueryAgainstAllowedDatasets validates a SQL query against a list of allowed datasets.

Why custom SQL parsing (TableParserDetailed & IsAnyTableExplicitlyReferenced) is needed alongside BigQuery dry run statistics:

  1. Supporting Authorized Views: When a query accesses an Authorized View (e.g. `SELECT * FROM allowed_ds.my_view`), BigQuery's dry run resolves the view and includes ALL underlying base tables in Statistics.Query.ReferencedTables, even if they reside in restricted datasets (e.g. `restricted_ds.base_table`). If we relied solely on dry run statistics, queries against legitimate authorized views would be erroneously blocked. To distinguish legitimate authorized view access from unauthorized direct access: - If a restricted dataset appears in dry run statistics, IsAnyTableExplicitlyReferenced performs a lexical scan of the SQL to check whether the restricted table is explicitly referenced by name in the query text. - If the user explicitly typed the restricted table name, the query is blocked. - If the restricted table was NOT named in the query (and all other references are fully qualified), the access is via an authorized view and is granted exemption.

  2. Catching Unanalyzable or Ambiguous Operations: Dry run statistics alone cannot detect every security boundary issue: - Unqualified table references (e.g. `SELECT * FROM my_table`): In the presence of dataset restrictions, table names must be fully qualified (dataset.table) to prevent accidental or ambiguous resolution based on session state or search paths. TableParserDetailed detects unqualified references. - Procedural operations (SET session variables, CALL, etc.) whose dynamic behavior cannot be safely analyzed.

Types

type DatasetValidator added in v1.14.0

type DatasetValidator interface {
	IsDatasetAllowed(projectID, datasetID string) bool
}

DatasetValidator defines the interface for checking if a dataset is allowed.

type MockSource added in v1.4.0

type MockSource struct {
	sources.Source
	CalledSQL       string
	Client          *bigqueryapi.Client
	Service         *bigqueryrestapi.Service
	AllowedDatasets []string
	RunSQLResult    any
	RunSQLError     error
	WriteMode       string
	Session         *bigqueryds.Session
}

MockSource is a reusable mock implementation of sources.Source for BigQuery tool tests.

func (*MockSource) BigQueryAllowedDatasets added in v1.4.0

func (m *MockSource) BigQueryAllowedDatasets() []string

func (*MockSource) BigQueryClient added in v1.4.0

func (m *MockSource) BigQueryClient() *bigqueryapi.Client

func (*MockSource) BigQuerySession added in v1.4.0

func (m *MockSource) BigQuerySession() bigqueryds.BigQuerySessionProvider

func (*MockSource) BigQueryWriteMode added in v1.5.0

func (m *MockSource) BigQueryWriteMode() string

func (*MockSource) GetAuthTokenHeaderName added in v1.4.0

func (m *MockSource) GetAuthTokenHeaderName() string

func (*MockSource) GetMaximumBytesBilled added in v1.4.0

func (m *MockSource) GetMaximumBytesBilled() int64

func (*MockSource) IsDatasetAllowed added in v1.4.0

func (m *MockSource) IsDatasetAllowed(projectID, datasetID string) bool

func (*MockSource) RetrieveClientAndService added in v1.4.0

func (m *MockSource) RetrieveClientAndService(tools.AccessToken) (*bigqueryapi.Client, *bigqueryrestapi.Service, error)

func (*MockSource) RunSQL added in v1.4.0

func (m *MockSource) RunSQL(ctx context.Context, client *bigqueryapi.Client, sql string, queryType string, params []bigqueryapi.QueryParameter, connProps []*bigqueryapi.ConnectionProperty, labels map[string]string) (any, error)

func (*MockSource) UseClientAuthorization added in v1.4.0

func (m *MockSource) UseClientAuthorization() bool

type ParseResult added in v1.14.0

type ParseResult struct {
	// TableIDs are fully-qualified project.dataset.table references found in the query.
	TableIDs []string
	// UnqualifiedRefs are single-part table references (e.g. `FROM my_table`) that are
	// neither a CTE nor an alias. Their dataset can only be resolved at execution time
	// (via the session's default dataset), so they cannot be statically validated.
	UnqualifiedRefs []string
}

ParseResult holds the outcome of a lexical scan of a query.

func TableParserDetailed added in v1.14.0

func TableParserDetailed(sql, defaultProjectID string) (ParseResult, error)

TableParserDetailed parses a SQL query and returns both fully-qualified table IDs and single-part unqualified table references found in the query.

type ValidateOption added in v1.14.0

type ValidateOption func(*validateOptions)

ValidateOption configures optional behavior for ValidateQueryAgainstAllowedDatasets.

func WithSessionTempObject added in v1.14.0

func WithSessionTempObject(name string) ValidateOption

WithSessionTempObject exempts a server-generated session temporary object name (such as a CREATE TEMP MODEL target) from dataset allowlist checks on dry-run target tables and from unqualified table reference checks. Only pass server-generated identifiers that cannot be controlled by user input.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL