deltascope

package
v0.511.0 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

Public Package Module

Stable public package surface for library consumers.

Files

File Responsibility
doc.go Declares the public package placeholder
audit.go Exposes the stable public audit API, optional metadata-provider hooks, and public result/request types
query_access.go Exposes the stable public query access analysis API, schema resolver interface, and public result/request types
query_access_online_session.go Exposes the opaque unified online query access session, identified-conn constructor that skips a second identity probe, bounded sentinel errors including the PostgreSQL PG17 version boundary, and MySQL/TiDB/PG17 routing through shared private proof cores
query_access_online_capability.go Holds the single private capability-target routing definition for the unified online entry (MySQL/TiDB always linked; PG17 delegated to the build-tag leaf)
query_access_online_capability_postgresql.go Reports PostgreSQL capability as linked when built with the postgresql tag (postgresql build tag)
query_access_online_capability_notag.go Reports PostgreSQL capability as not linked when built without the postgresql tag; unified PG17 fails closed with the capability sentinel
query_access_session.go Exposes the opaque PostgreSQL session wrapper for trusted query access plus the shared private PG17 proof core used by the unified entry (postgresql build tag)
query_access_session_mysql_tidb.go Exposes the opaque MySQL/TiDB session boundary for same-connection metadata resolution plus the shared private MySQL/TiDB proof core used by the unified entry
query_access_session_stub.go Provides PostgreSQL session stub when built without postgresql tag
query_access_session_integration_test.go Deprecated PG17 session construction, validation, caller ownership, offline/default behavior, and same-connection compatibility against Docker
query_access_session_postgresql_recording_test.go Recording driver shared by unified tagged tests, plus deprecated PG17 foreign-table and bounded-failure no-leak compatibility
query_access_session_mysql_tidb_live_e2e_test.go Docker-backed unified MySQL 5.7/8.0/8.4 and TiDB 8.5 semantic matrix, plus per-target deprecated-session identity and result equivalence
query_access_online_session_test.go Verifies the unified online session contract: signatures, opacity, ownership, validation priority, generic sentinels, direct MySQL/TiDB semantic and ordered recording matrices (including exact MySQL 8.4 SUM, unknown-function, rejected-write, and parse-failure classification/admission/requirements/reasons), and no-execution/no-leak evidence
query_access_online_session_postgresql_tag_test.go Verifies PostgreSQL 17 routing through the unified entry: exact COUNT(1) admission, excluded-shape and foreign-table fail-closed behavior, ordered recording-driver no-execution/no-leak, ownership, validation, and bounded failures (postgresql build tag)
query_access_online_session_postgresql_notag_test.go Verifies the no-tag build keeps the unified symbols, fails an observed PostgreSQL target closed, and preserves legacy PostgreSQL stubs
query_access_online_session_postgresql_integration_test.go Real PG17 same-backend-session proof, COUNT(1)/excluded-shape/parse-failure/foreign-table evidence, and unified-versus-legacy equivalence for the unified online entry (postgresql + integration build tags)
version.go Publishes ReportedVersion(), the DefaultVersion fallback, and the canonical ASCII logo
version_test.go Verifies untagged, devel, and pseudo-version builds do not claim DefaultVersion as the sole version, and that tagged versions and the absent-build-info fallback stay intact
audit_test.go Verifies the public audit API with defaults, overrides, multi-statement and wholly-unparsable diagnostics, PostgreSQL routing, metadata-aware request plumbing, and JSON that omits CLI-only fail_on_triggered
audit_dml_table_existence_test.go Verifies the public MySQL/TiDB DML missing-target blocker, existing-table behavior, and offline non-claim
audit_ddl_lifecycle_mysql_test.go Verifies MySQL/TiDB lifecycle findings, normalized notice identifiers, ALTER TABLE index-notice reuse/action metadata, and no-leak behavior
audit_unsupported_diagnostics_evidence_test.go Verifies parser-error calls return a non-nil error together with review-floored partial results, preserved valid statements/findings, and located safe diagnostics
audit_unsupported_verdict_floor_postgresql_tag_test.go Verifies public Audit floors PostgreSQL SELECT 1 from pass to review while keeping ErrUnsupportedStatement and audited-only statements
audit_postgresql_tag_test.go Verifies the public PostgreSQL offline primary-key equality impact contract
query_access_test.go Verifies the public query access API with dialect routing, mode handling, JSON structure parity, and context cancellation
query_access_probe_boundary_no_leak_test.go No-leak regression for the MySQL/TiDB builtin-identity probe boundary: asserts injected markers, identity facts, candidates, session/context, manifest, raw SQL, and severity are absent from the SDK result and JSON mapping

Exports

  • Audit(ctx, request)
  • Request
  • MetadataProvider
  • Metadata
  • InstanceFacts
  • TableSnapshot
  • Table
  • Column
  • Index
  • Constraint
  • Result Retains audited statement results when another bounded statement fails parsing; Audit still returns a non-nil error for the unaudited statement.
  • StatementResult
  • Explanation
  • Finding
  • FindingExplanation
  • ExplanationMetadata
  • Level Public finding level type for blocker, warning, and notice
  • Summary
  • Location
  • Dialect Includes DialectPostgreSQL for PostgreSQL request routing support
  • Verdict
  • DefaultVersion
  • ReportedVersion()
  • Logo
  • AnalyzeQueryAccess(ctx, request) Performs query access analysis and returns read classification, admission, and permission requirements
  • QueryAccessRequest Input for query access analysis with SQL, dialect, mode, optional analysis profile, default schema, and optional schema resolver
  • QueryAccessAnalysisProfile Closed compatibility targets: empty, mysql-5.7, mysql-8.0, mysql-8.4, and tidb-8.5
  • ErrInvalidQueryAccessAnalysisProfile Returned when a profile is outside the closed set
  • ErrQueryAccessAnalysisProfileDialectMismatch Returned when a profile is selected for another dialect
  • QueryAccessResult Output of query access analysis with structured JSON fields for dialect, mode, classification, admission, relations, columns, outputs, requirements, unresolved references, and warnings
  • QueryAccessMode Controls which column references become requirements: strict or projection_only
  • QueryAccessReadClassification Describes whether SQL is read-only: read_only, not_read_only, or indeterminate
  • QueryAccessAdmission Describes whether SQL is eligible for authorization: admissible, rejected, or indeterminate
  • QueryAccessSchemaResolver Optional interface for resolving relation metadata during analysis
  • QueryAccessRelationReference Relation reference with Unbound field marking relations that must not produce physical requirements
  • QueryAccessColumnReference Column reference with Unbound field indicating the column could not be resolved to a qualified schema.table.column
  • OnlineQueryAccessSession (canonical) Opaque unified wrapper for a caller-owned *sql.Conn. Exposes no identity, product, profile, capability, connection state, exported field, or getter, and marshals as {}
  • NewOnlineQueryAccessSessionFromConn(ctx, conn) Conn-only constructor: pings, identifies the server, and derives a private routing target. Never opens, pools, closes, or retries the connection. Nil context/connection, failed liveness, and untrustworthy identity map to ErrOnlineQueryAccessSessionUnavailable; a reachable PostgreSQL identity outside PG17 maps to ErrOnlineQueryAccessPostgreSQLVersionUnsupported; other recognized unsupported capabilities map to ErrOnlineQueryAccessCapabilityUnsupported. Official DeltaScope binaries are built with the postgresql tag and route PostgreSQL 17 through the same-connection trusted proof
  • NewOnlineQueryAccessSessionFromIdentifiedConn(conn, identity) Reuses an already-observed Server Identity. Does not ping or query VERSION again. Transports that opened an online.Session should use this. Nil connection or identity maps to ErrOnlineQueryAccessSessionUnavailable; a PostgreSQL identity outside PG17 maps to ErrOnlineQueryAccessPostgreSQLVersionUnsupported; other recognized unsupported capabilities map to ErrOnlineQueryAccessCapabilityUnsupported
  • AnalyzeOnlineQueryAccessWithSession(ctx, session, req) (canonical) Unified online analysis entry with a fixed validation priority (session/context; dialect mismatch; profile; resolver; linked capability; existing request validation). Empty request dialect uses observed identity; a non-empty dialect is a constraint that must match. Routes MySQL 5.7/8.0/8.4, TiDB 8.5, and PostgreSQL 17 (postgresql build tag) through their existing private proof cores; the no-tag source build keeps PostgreSQL fail-closed with the capability sentinel
  • ErrOnlineQueryAccessSessionUnavailable Bounded sentinel: context/session unusable (nil input, failed liveness, failed identity)
  • ErrOnlineQueryAccessDialectMismatch Bounded sentinel: non-empty request dialect did not match observed identity
  • ErrOnlineQueryAccessProfileNotAllowed Bounded sentinel: caller analysis profile rejected; capability derives from observed identity
  • ErrOnlineQueryAccessSchemaResolverNotAllowed Bounded sentinel: external schema resolver rejected; online proof uses the same-connection resolver
  • ErrOnlineQueryAccessPostgreSQLVersionUnsupported Bounded sentinel: reachable PostgreSQL identity is outside the trusted PG17 version boundary; its message is online PostgreSQL Query Access requires PostgreSQL 17 and it unwraps to ErrOnlineQueryAccessCapabilityUnsupported
  • ErrOnlineQueryAccessCapabilityUnsupported Bounded sentinel: recognized but unsupported capability other than the PostgreSQL version-specific boundary, or PostgreSQL 17 in a no-postgresql-tag source build
  • PostgreSQLQueryAccessSession (deprecated; use OnlineQueryAccessSession) Opaque wrapper for a caller-owned *sql.Conn for trusted PostgreSQL query access analysis (postgresql build tag only); the unified OnlineQueryAccessSession routes PG17 through the same private proof core
  • NewPostgreSQLQueryAccessSessionFromConn(ctx, conn) (deprecated; use NewOnlineQueryAccessSessionFromConn) Creates an opaque session from a caller-owned *sql.Conn with context for liveness check; the session does not close the connection (postgresql build tag; stub returns ErrPostgreSQLSessionNotAvailable in non-postgresql builds)
  • AnalyzePostgreSQLQueryAccessWithSession(ctx, session, req) (deprecated; use AnalyzeOnlineQueryAccessWithSession) Performs trusted PostgreSQL query access analysis using a caller-owned connection session; may return read_only + admissible when all effects are manifest-proven (postgresql build tag; stub returns ErrPostgreSQLSessionNotAvailable in non-postgresql builds)
  • MySQLTiDBQueryAccessSession (deprecated; use OnlineQueryAccessSession) Opaque wrapper for a caller-owned MySQL/TiDB *sql.Conn; the connection remains caller-owned
  • NewMySQLTiDBQueryAccessSessionFromConn(ctx, conn) (deprecated; use NewOnlineQueryAccessSessionFromConn) Creates an opaque MySQL/TiDB session after a liveness check
  • AnalyzeMySQLTiDBQueryAccessWithSession(ctx, session, req) (deprecated; use AnalyzeOnlineQueryAccessWithSession) Resolves relation metadata through the session connection, rejects external schema resolvers, and remains the dialect-specific SDK boundary for the private MySQL/TiDB semantic capability. The production builtin semantic registry is enabled for mysql-5.7, mysql-8.0, mysql-8.4, and tidb-8.5. Each profile supports COUNT(*), direct-column COUNT/SUM/AVG/MIN/MAX; the 8.x profiles additionally support ROW_NUMBER/RANK/DENSE_RANK with direct partition and order columns. Default AnalyzeQueryAccess remains offline and fail-closed; CLI and HTTP online mode route the same capability through AnalyzeOnlineQueryAccessWithSession.

Migrating from the Dialect-Specific Session APIs

The six dialect-specific compatibility identifiers are deprecated. Use the unified online entry instead:

Deprecated Replacement
PostgreSQLQueryAccessSession OnlineQueryAccessSession
MySQLTiDBQueryAccessSession OnlineQueryAccessSession
NewPostgreSQLQueryAccessSessionFromConn NewOnlineQueryAccessSessionFromConn
NewMySQLTiDBQueryAccessSessionFromConn NewOnlineQueryAccessSessionFromConn
AnalyzePostgreSQLQueryAccessWithSession AnalyzeOnlineQueryAccessWithSession
AnalyzeMySQLTiDBQueryAccessWithSession AnalyzeOnlineQueryAccessWithSession

The unified session is constructed from the same caller-owned *sql.Conn; construction pings and identifies the server, and the caller keeps full connection lifecycle control. Leave QueryAccessRequest.Dialect empty so the observed server identity selects the MySQL, TiDB, or PostgreSQL route; a non-empty dialect is only an optional matching constraint. The unified entry returns its own bounded ErrOnlineQueryAccess... sentinels, so migrate errors.Is checks from the dialect-specific sentinels (for example ErrMySQLTiDBQueryAccessSessionUnavailable) to the generic ones rather than expecting one-to-one error aliases.

Query Access Test Ownership

The unified online-session suite owns exhaustive semantic and detailed-probe evidence, including ordered recording-driver probes. Deprecated API tests retain only source, stub, exact-error, validation-order, caller-ownership, privacy, and one per-target equivalence contract. The committed ownership ledger in docs/plans/2026-08-15-query-access-test-ownership-consolidation-implementation.md names every authorized deletion and its focused green evidence.

Notes

  • Audit and Query Access treat exactly one leading UTF-8 BOM as an input encoding marker before parsing; marker-only input is rejected as empty, while BOM-free Query Access empty input remains unchanged. BOM characters later in SQL remain part of the input.
  • Request now carries top-level Schema and MetadataProvider fields so CLI, HTTP, and library consumers can opt into metadata-aware audits without changing the offline call shape.
  • Public MetadataProvider stays minimal; standalone PostgreSQL index-owner resolution remains an internal optional seam behind the application metadata enrichment layer.
  • Result and StatementResult expose an optional Explanation field for additive shared result context without changing verdict semantics. The built-in audit flow populates these aggregate fields whenever findings are present.
  • Result now also exposes Unsupported ([]spec.UnsupportedDetail) and Diagnostics ([]spec.Diagnostic) arrays so library consumers can inspect structured partial-support and parser-error/unsupported-statement outcomes. A partial result with an unaudited parser-error diagnostic is floored from pass to review; existing review/reject verdicts and wholly unparseable behavior remain unchanged.
  • ErrUnsupportedStatement is returned when unsupported statements are present, while still returning a populated Result for supported statements.
  • Finding now exposes an optional Explanation field so library consumers can read structured per-finding why, risk, suggestion, and metadata-status notes directly.
  • DefaultVersion is v0.511.0, the fallback when Go build information is absent.
  • ReportedVersion() prefers the Go module version (tag or pseudo-version) or VCS revision (devel-<rev> / devel-<rev>-dirty) so untagged, devel, and go install @main builds do not claim the last release tag as the sole version.
  • Release ldflags still override CLI, server, and MCP Version to the release tag. Release surface gates keep DefaultVersion aligned with that tag as the absent-build-info fallback.

Dependencies

  • Upstream: external library consumers
  • Downstream: context, internal/application/audit, internal/application/queryaccess, internal/domain/queryaccess, internal/domain/report, internal/domain/rule, internal/domain/spec

Update Rule

  • If members/interfaces/dependencies change, update this file in same change.

Documentation

Overview

Package deltascope exposes the public library surface for consumers. input: public audit requests carrying SQL text, dialect, optional config path, and optional metadata providers output: stable audit results for embedding DeltaScope in tools and agents pos: public audit API above the internal application service note: if this file changes, update this header and module README.md.

Package deltascope exposes the public library surface for consumers. input: external library calls into the DeltaScope audit engine output: stable exported API for embedding DeltaScope pos: public package boundary above internal application services note: if this file changes, update this header and module README.md.

Package deltascope exposes the public library surface for consumers. input: public query access requests carrying SQL text, dialect, mode, profile, and optional schema resolver output: stable query access analysis results for embedding DeltaScope in tools and agents pos: public query access API above the internal application service note: if this file changes, update this header and module README.md.

Defense in Depth: Query access analysis is one layer in a defense-in-depth authorization strategy. It supplements, but does not replace, database authorization, grant evaluation, row-level security, and audit logging. Always pair this analysis with proper authentication and authorization checks.

Package deltascope exposes the unified online query access capability seam. input: identity-derived online capability target output: single private routing definition for which capabilities are linked and routable in this build pos: private unified online capability routing seam shared by constructor and analysis entry note: if this file changes, update this header and module README.md.

Package deltascope reports PostgreSQL capability as not linked when built without the postgresql tag; the unified online entry fails closed for an observed PostgreSQL target with ErrOnlineQueryAccessCapabilityUnsupported. This is source-build compatibility only and is not a separate official product edition. input: none (build-tag capability leaf) output: queryAccessPostgreSQLCapabilityLinked() = false pos: no-postgresql-tag private capability leaf for the unified online entry note: if this file changes, update this header and module README.md.

Package deltascope exposes the unified online query access session boundary. input: caller-owned *sql.Conn, optional already-observed Server Identity, context, and a query access request with optional dialect constraint output: opaque unified session, identified-conn constructor that skips a second identity probe, generic online analysis entry, bounded sentinel errors, and MySQL/TiDB/PG17 routing pos: public unified online query access session API above dialect-specific entries note: if this file changes, update this header and module README.md.

Package deltascope exposes the public library surface for consumers. input: caller-owned *sql.Conn for PostgreSQL trusted query access output: shared types and errors for session API across build tags pos: public shared session types (no build tag) note: if this file changes, update this header and module README.md.

Package deltascope exposes the explicit MySQL/TiDB query access session boundary. input: caller-owned *sql.Conn and a validated MySQL/TiDB query access request output: query access results with same-connection relation metadata resolution pos: public opt-in session API and shared private proof core for same-connection semantic promotion note: if this file changes, update this header and module README.md.

Package deltascope provides the PostgreSQL session stub when built without the postgresql tag. input: none (stub only) output: ErrPostgreSQLSessionNotAvailable for legacy calls; fail-closed unified PG17 route stub pos: public stub for non-PostgreSQL builds note: if this file changes, update this header and module README.md.

Package deltascope exposes the stable public audit API. input: build metadata consumers and public version/logo queries output: reported build version from Go module/VCS info, DefaultVersion fallback, and ASCII logo values for CLIs and services pos: public package metadata alongside the stable audit entrypoint note: if this file changes, update this header and module README.md.

Index

Constants

View Source
const (
	ImpactSourceShape    ImpactSource = "shape"
	ImpactSourceMetadata ImpactSource = "metadata"
	ImpactSourcePlan     ImpactSource = "plan"

	ImpactRiskLow     ImpactRisk = "low"
	ImpactRiskMedium  ImpactRisk = "medium"
	ImpactRiskHigh    ImpactRisk = "high"
	ImpactRiskUnknown ImpactRisk = "unknown"

	ImpactConfidenceLow    ImpactConfidence = "low"
	ImpactConfidenceMedium ImpactConfidence = "medium"
	ImpactConfidenceHigh   ImpactConfidence = "high"
)
View Source
const (
	// DefaultVersion is the repository's current default semantic version.
	// It is used only when Go build information is absent.
	DefaultVersion = "v0.511.0"

	Logo = "    ____       ____        _____                     \n" +
		"   / __ \\___  / / /_____ _/ ___/_________  ____  ___ \n" +
		"  / / / / _ \\/ / __/ __ `/\\__ \\/ ___/ __ \\/ __ \\/ _ \\\n" +
		" / /_/ /  __/ / /_/ /_/ /___/ / /__/ /_/ / /_/ /  __/\n" +
		"/_____/\\___/_/\\__/\\__,_//____/\\___/\\____/ .___/\\___/ \n" +
		"                                       /_/           "
)

Variables

View Source
var (
	// ErrOnlineQueryAccessSessionUnavailable indicates the context or caller-owned
	// connection session was unusable (nil input, failed liveness, or failed
	// identity acquisition).
	ErrOnlineQueryAccessSessionUnavailable = errors.New("online query access session is unavailable")
	// ErrOnlineQueryAccessDialectMismatch indicates a non-empty request dialect
	// did not match the identity observed on the connection.
	ErrOnlineQueryAccessDialectMismatch = errors.New("online query access dialect mismatch")
	// ErrOnlineQueryAccessProfileNotAllowed indicates a caller supplied an
	// analysis profile; capability is derived from observed server identity.
	ErrOnlineQueryAccessProfileNotAllowed = errors.New("online query access rejects caller analysis profile; capability is derived from server identity")
	// ErrOnlineQueryAccessSchemaResolverNotAllowed indicates a caller supplied an
	// external schema resolver; online proof must use the same-connection resolver.
	ErrOnlineQueryAccessSchemaResolverNotAllowed = errors.New("online query access does not accept an external schema resolver")
	// ErrOnlineQueryAccessCapabilityUnsupported indicates the observed server
	// capability is recognized but not supported by this build or milestone.
	ErrOnlineQueryAccessCapabilityUnsupported = errors.New("online query access capability is not supported")
	// ErrOnlineQueryAccessPostgreSQLVersionUnsupported identifies a reachable
	// PostgreSQL server outside the intentionally trusted PG17 capability.
	ErrOnlineQueryAccessPostgreSQLVersionUnsupported error = postgreSQLQueryAccessVersionUnsupportedError{}
)

Generic online query access sentinel errors. These are the bounded public boundary of the unified entry; callers must use errors.Is, not string matching. They never embed credentials, endpoints, raw versions, catalog facts, or driver text. The PostgreSQL version sentinel below uses only the fixed supported-version requirement.

View Source
var (
	ErrMySQLTiDBQueryAccessSessionUnavailable       = errors.New("mysql/tidb query access session is unavailable")
	ErrMySQLTiDBQueryAccessDialectRequired          = errors.New("mysql/tidb query access session requires MySQL or TiDB dialect")
	ErrMySQLTiDBQueryAccessSchemaResolverNotAllowed = errors.New("mysql/tidb query access session does not accept an external schema resolver")
	ErrMySQLTiDBQueryAccessProfileNotAllowed        = errors.New("mysql/tidb query access session rejects caller analysis profile; capability is derived from server identity")
)
View Source
var ErrInvalidQueryAccessAnalysisProfile = errors.New("invalid query access analysis profile")

ErrInvalidQueryAccessAnalysisProfile is returned for a profile outside the closed set.

View Source
var ErrInvalidQueryAccessMode = errors.New("invalid query access mode: must be strict or projection_only")

ErrInvalidQueryAccessMode is returned when the mode is not a recognized value.

View Source
var ErrPostgreSQLQueryAccessProfileNotAllowed = errors.New("postgresql session rejects caller analysis profile; capability is derived from server identity")

ErrPostgreSQLQueryAccessProfileNotAllowed is returned when a caller supplies a non-empty AnalysisProfile on a session-based PostgreSQL request.

View Source
var ErrPostgreSQLSessionNotAvailable = errors.New("postgresql session support requires build tag: go build -tags postgresql")

ErrPostgreSQLSessionNotAvailable indicates PostgreSQL session support was not compiled in. This error is returned by the stub constructor when built without the postgresql tag.

View Source
var ErrQueryAccessAnalysisProfileDialectMismatch = errors.New("query access analysis profile does not match dialect")

ErrQueryAccessAnalysisProfileDialectMismatch is returned when a profile belongs to another dialect.

View Source
var ErrQueryAccessUnsupportedDialect = errors.New("unsupported dialect for query access analysis")

ErrQueryAccessUnsupportedDialect is returned when the dialect is not supported for query access analysis.

View Source
var ErrUnsupportedStatement = errors.New("deltascope audit includes unsupported statements")

Functions

func ReportedVersion added in v0.510.4

func ReportedVersion() string

ReportedVersion returns the version string for this DeltaScope build. Tagged and pseudo-version module builds report that module version. Devel source builds report VCS revision as devel-<rev> or devel-<rev>-dirty. DefaultVersion is used only when build information is absent.

Types

type Column

type Column = spec.Column

Column mirrors the domain column shape used inside metadata snapshots.

type Constraint

type Constraint = spec.Constraint

Constraint mirrors the domain constraint shape used inside metadata snapshots.

type Dialect

type Dialect string

Dialect identifies the SQL dialect for public callers.

const (
	DialectMySQL      Dialect = "mysql"
	DialectTiDB       Dialect = "tidb"
	DialectPostgreSQL Dialect = "postgresql"
)

type Explanation added in v0.6.2

type Explanation struct {
	Summary string   `json:"summary,omitempty"`
	Reasons []string `json:"reasons,omitempty"`
}

Explanation is the stable public result-level explanation shape.

type ExplanationMetadata added in v0.6.2

type ExplanationMetadata struct {
	Status string `json:"status,omitempty"`
	Note   string `json:"note,omitempty"`
}

ExplanationMetadata describes how metadata availability affected a public finding explanation.

type Finding

type Finding struct {
	RuleID         string              `json:"rule_id"`
	Level          Level               `json:"level"`
	Message        string              `json:"message"`
	StatementIndex int                 `json:"statement_index,omitempty"`
	StatementKind  string              `json:"statement_kind,omitempty"`
	Location       *Location           `json:"location,omitempty"`
	Suggestion     string              `json:"suggestion,omitempty"`
	Metadata       map[string]any      `json:"metadata,omitempty"`
	Explanation    *FindingExplanation `json:"explanation,omitempty"`
}

Finding is the stable public finding shape.

type FindingExplanation added in v0.6.2

type FindingExplanation struct {
	Summary    string               `json:"summary,omitempty"`
	Why        string               `json:"why,omitempty"`
	Risk       string               `json:"risk,omitempty"`
	Suggestion string               `json:"suggestion,omitempty"`
	Metadata   *ExplanationMetadata `json:"metadata,omitempty"`
}

FindingExplanation is the stable public per-finding explanation shape.

type Impact added in v0.14.0

type Impact struct {
	EstimatedRows  *int64           `json:"estimated_rows,omitempty"`
	EstimatedRatio *float64         `json:"estimated_ratio,omitempty"`
	RiskLevel      ImpactRisk       `json:"risk_level,omitempty"`
	Confidence     ImpactConfidence `json:"confidence,omitempty"`
	Source         ImpactSource     `json:"source,omitempty"`
	ReasonCodes    []string         `json:"reason_codes,omitempty"`
	Notes          []string         `json:"notes,omitempty"`
}

Impact is the stable public statement-level DML impact estimate shape.

type ImpactConfidence added in v0.14.0

type ImpactConfidence string

ImpactConfidence identifies the public estimate-confidence bucket.

type ImpactRisk added in v0.14.0

type ImpactRisk string

ImpactRisk identifies the public conservative risk bucket for a DML statement.

type ImpactSource added in v0.14.0

type ImpactSource string

ImpactSource identifies the public origin of a statement-level DML impact estimate.

type Index

type Index = spec.Index

Index mirrors the domain index shape used inside metadata snapshots.

type InstanceFacts

type InstanceFacts = spec.InstanceFacts

InstanceFacts mirror metadata-aware instance facts for public providers.

type Level

type Level string

Level identifies the public finding severity.

const (
	LevelBlocker Level = "blocker"
	LevelWarning Level = "warning"
	LevelNotice  Level = "notice"
)

type Location

type Location struct {
	Line   int `json:"line,omitempty"`
	Column int `json:"column,omitempty"`
}

Location identifies a public source span when available.

type Metadata

type Metadata = spec.Metadata

Metadata mirrors the optional domain metadata facts exposed on statements.

type MetadataProvider

type MetadataProvider interface {
	LoadInstanceFacts(ctx context.Context, dialect Dialect, schema string) (*InstanceFacts, error)
	LoadTableSnapshot(ctx context.Context, dialect Dialect, schema string, table string) (*TableSnapshot, error)
}

MetadataProvider supplies optional metadata-aware facts for one public audit request.

type MySQLTiDBQueryAccessSession deprecated added in v0.410.0

type MySQLTiDBQueryAccessSession struct {
	// contains filtered or unexported fields
}

MySQLTiDBQueryAccessSession is an opaque wrapper around a caller-owned *sql.Conn. The session derives its capability target from server identity at construction time.

Deprecated: Use OnlineQueryAccessSession.

func NewMySQLTiDBQueryAccessSessionFromConn deprecated added in v0.410.0

func NewMySQLTiDBQueryAccessSessionFromConn(ctx context.Context, conn *sql.Conn) (*MySQLTiDBQueryAccessSession, error)

NewMySQLTiDBQueryAccessSessionFromConn creates a session after a context-controlled liveness check and server identity validation.

Deprecated: Use NewOnlineQueryAccessSessionFromConn.

type OnlineQueryAccessSession added in v0.490.0

type OnlineQueryAccessSession struct {
	// contains filtered or unexported fields
}

OnlineQueryAccessSession is an opaque wrapper around a caller-owned *sql.Conn.

Construction pings and identifies the server on that connection and stores only the private connection and identity-derived routing target. The session never opens, pools, closes, or retries the connection; the caller retains full lifecycle control. It exposes no identity, product, dialect, profile, capability, connection, or JSON-visible state and has no public getters.

func NewOnlineQueryAccessSessionFromConn added in v0.490.0

func NewOnlineQueryAccessSessionFromConn(ctx context.Context, conn *sql.Conn) (*OnlineQueryAccessSession, error)

NewOnlineQueryAccessSessionFromConn creates a unified online session from a caller-owned *sql.Conn. The constructor performs its own liveness check and derives the routing target from observed server identity; callers cannot supply a product, dialect, profile, version, or capability target.

Nil context or connection, failed liveness, and untrustworthy identity acquisition (unknown product, malformed version, failed version query) map to ErrOnlineQueryAccessSessionUnavailable. A recognized PostgreSQL identity outside the trusted PG17 series maps to ErrOnlineQueryAccessPostgreSQLVersionUnsupported. Other recognized products outside the supported set (for example MySQL 8.1 or TiDB 7.x) and an observed PostgreSQL target in a source build without the postgresql tag map to ErrOnlineQueryAccessCapabilityUnsupported.

func NewOnlineQueryAccessSessionFromIdentifiedConn added in v0.511.0

func NewOnlineQueryAccessSessionFromIdentifiedConn(conn *sql.Conn, identity *online.ServerIdentity) (*OnlineQueryAccessSession, error)

NewOnlineQueryAccessSessionFromIdentifiedConn wraps a caller-owned *sql.Conn whose Observed Server Identity is already known. It does not ping or query VERSION again. Transports that opened an online.Session should use this.

type PlanEstimateProvider added in v0.18.0

type PlanEstimateProvider interface {
	LoadPlanEstimate(ctx context.Context, statement spec.Statement) (*spec.ImpactEstimate, error)
}

PlanEstimateProvider optionally supplies planner-backed DML impact estimates.

type PostgreSQLQueryAccessSession deprecated added in v0.390.0

type PostgreSQLQueryAccessSession struct {
	// contains filtered or unexported fields
}

PostgreSQLQueryAccessSession is an opaque wrapper around a caller-owned *sql.Conn for trusted PostgreSQL query access analysis.

The session does not own or close the caller's connection. The caller retains full lifecycle control. Analysis on an already-closed connection returns a bounded error.

The wrapper exposes no OIDs, manifest entries, catalog SQL, credentials, session binding, or Trusted flag. It has no JSON-marshalable fields.

Deprecated: Use OnlineQueryAccessSession.

func NewPostgreSQLQueryAccessSessionFromConn deprecated added in v0.390.0

func NewPostgreSQLQueryAccessSessionFromConn(_ context.Context, _ *sql.Conn) (*PostgreSQLQueryAccessSession, error)

NewPostgreSQLQueryAccessSessionFromConn returns ErrPostgreSQLSessionNotAvailable when built without the postgresql tag.

Deprecated: Use NewOnlineQueryAccessSessionFromConn.

type QueryAccessAdmission added in v0.380.0

type QueryAccessAdmission string

QueryAccessAdmission describes whether SQL is eligible for caller authorization.

const (
	// QueryAccessAdmissible indicates the statement is eligible for authorization checks.
	QueryAccessAdmissible QueryAccessAdmission = "admissible"
	// QueryAccessRejected indicates the statement is not eligible for authorization checks.
	QueryAccessRejected QueryAccessAdmission = "rejected"
	// QueryAccessIndeterminateAdmission indicates the admission status could not be determined.
	QueryAccessIndeterminateAdmission QueryAccessAdmission = "indeterminate"
)

type QueryAccessAnalysisProfile added in v0.410.0

type QueryAccessAnalysisProfile string

QueryAccessAnalysisProfile identifies a closed engine/version compatibility target.

const (
	// QueryAccessAnalysisProfileEmpty preserves the existing offline behavior.
	QueryAccessAnalysisProfileEmpty QueryAccessAnalysisProfile = QueryAccessAnalysisProfile(appqa.AnalysisProfileEmpty)
	// QueryAccessAnalysisProfileMySQL57 identifies the MySQL 5.7 compatibility target.
	QueryAccessAnalysisProfileMySQL57 QueryAccessAnalysisProfile = QueryAccessAnalysisProfile(appqa.AnalysisProfileMySQL57)
	// QueryAccessAnalysisProfileMySQL80 identifies the MySQL 8.0 compatibility target.
	QueryAccessAnalysisProfileMySQL80 QueryAccessAnalysisProfile = QueryAccessAnalysisProfile(appqa.AnalysisProfileMySQL80)
	// QueryAccessAnalysisProfileMySQL84 identifies the MySQL 8.4 compatibility target.
	QueryAccessAnalysisProfileMySQL84 QueryAccessAnalysisProfile = QueryAccessAnalysisProfile(appqa.AnalysisProfileMySQL84)
	// QueryAccessAnalysisProfileTiDB85 identifies the TiDB 8.5 compatibility target.
	QueryAccessAnalysisProfileTiDB85 QueryAccessAnalysisProfile = QueryAccessAnalysisProfile(appqa.AnalysisProfileTiDB85)
)

type QueryAccessColumnReference added in v0.380.0

type QueryAccessColumnReference struct {
	Schema  string   `json:"schema,omitempty"`
	Table   string   `json:"table"`
	Column  string   `json:"column"`
	Usages  []string `json:"usages"`
	Unbound bool     `json:"unbound,omitempty"`
}

QueryAccessColumnReference represents a source column reference.

type QueryAccessColumnSchema added in v0.380.0

type QueryAccessColumnSchema struct {
	Name    string
	Ordinal int
}

QueryAccessColumnSchema contains metadata about a column.

type QueryAccessMode added in v0.380.0

type QueryAccessMode string

QueryAccessMode controls which column references become requirements.

const (
	// QueryAccessModeStrict requires all referenced columns to be authorized.
	QueryAccessModeStrict QueryAccessMode = "strict"
	// QueryAccessModeProjectionOnly requires only projected columns to be authorized.
	QueryAccessModeProjectionOnly QueryAccessMode = "projection_only"
)

type QueryAccessOutputColumn added in v0.380.0

type QueryAccessOutputColumn struct {
	Name    string   `json:"name"`
	Sources []string `json:"sources"`
}

QueryAccessOutputColumn represents a final output column.

type QueryAccessReadClassification added in v0.380.0

type QueryAccessReadClassification string

QueryAccessReadClassification describes whether SQL is demonstrably read-only.

const (
	// QueryAccessReadOnly indicates the statement contains no write operations.
	QueryAccessReadOnly QueryAccessReadClassification = "read_only"
	// QueryAccessNotReadOnly indicates the statement contains at least one write operation.
	QueryAccessNotReadOnly QueryAccessReadClassification = "not_read_only"
	// QueryAccessIndeterminate indicates the read-only status could not be determined.
	QueryAccessIndeterminate QueryAccessReadClassification = "indeterminate"
)

type QueryAccessRelationKind added in v0.380.0

type QueryAccessRelationKind string

QueryAccessRelationKind describes the type of relation reference.

const (
	// QueryAccessRelationTable indicates a base table reference.
	QueryAccessRelationTable QueryAccessRelationKind = "table"
	// QueryAccessRelationView indicates a view reference.
	QueryAccessRelationView QueryAccessRelationKind = "view"
	// QueryAccessRelationCTE indicates a common table expression reference.
	QueryAccessRelationCTE QueryAccessRelationKind = "cte"
	// QueryAccessRelationDerived indicates a derived table (subquery) reference.
	QueryAccessRelationDerived QueryAccessRelationKind = "derived"
)

type QueryAccessRelationReference added in v0.380.0

type QueryAccessRelationReference struct {
	Schema             string `json:"schema,omitempty"`
	Name               string `json:"name"`
	Alias              string `json:"alias,omitempty"`
	Kind               string `json:"kind"`
	PermissionRequired bool   `json:"permission_required"`
	Unbound            bool   `json:"unbound,omitempty"`
}

QueryAccessRelationReference represents a relation read by the query.

type QueryAccessRelationSchema added in v0.380.0

type QueryAccessRelationSchema struct {
	Schema  string
	Name    string
	Kind    string
	Columns []QueryAccessColumnSchema
	IsView  bool
}

QueryAccessRelationSchema contains metadata about a relation for resolution.

type QueryAccessRequest added in v0.380.0

type QueryAccessRequest struct {
	SQL             string
	Dialect         Dialect
	Mode            QueryAccessMode
	DefaultSchema   string
	AnalysisProfile QueryAccessAnalysisProfile
	SchemaResolver  QueryAccessSchemaResolver // optional
}

QueryAccessRequest is the input for query access analysis.

type QueryAccessRequirement added in v0.380.0

type QueryAccessRequirement struct {
	Object    string `json:"object"`
	Privilege string `json:"privilege"`
}

QueryAccessRequirement represents a permission requirement.

type QueryAccessResult added in v0.380.0

type QueryAccessResult struct {
	Dialect            string                         `json:"dialect"`
	Mode               QueryAccessMode                `json:"mode"`
	ReadClassification QueryAccessReadClassification  `json:"read_classification"`
	Admission          QueryAccessAdmission           `json:"admission"`
	ReasonCodes        []string                       `json:"reason_codes,omitempty"`
	Relations          []QueryAccessRelationReference `json:"relations,omitempty"`
	ReferencedColumns  []QueryAccessColumnReference   `json:"referenced_columns,omitempty"`
	Outputs            []QueryAccessOutputColumn      `json:"outputs,omitempty"`
	Requirements       []QueryAccessRequirement       `json:"requirements,omitempty"`
	Unresolved         []QueryAccessUnresolved        `json:"unresolved,omitempty"`
	Warnings           []string                       `json:"warnings,omitempty"`
}

QueryAccessResult is the output of query access analysis.

func AnalyzeMySQLTiDBQueryAccessWithSession deprecated added in v0.410.0

func AnalyzeMySQLTiDBQueryAccessWithSession(
	ctx context.Context,
	session *MySQLTiDBQueryAccessSession,
	req QueryAccessRequest,
) (*QueryAccessResult, error)

AnalyzeMySQLTiDBQueryAccessWithSession resolves relation metadata on the caller's connection and enables the private application semantic capability for the session-owned resolver. Rejects a non-empty caller AnalysisProfile; the capability is derived from server identity.

Deprecated: Use AnalyzeOnlineQueryAccessWithSession.

func AnalyzeOnlineQueryAccessWithSession added in v0.490.0

func AnalyzeOnlineQueryAccessWithSession(
	ctx context.Context,
	session *OnlineQueryAccessSession,
	req QueryAccessRequest,
) (*QueryAccessResult, error)

AnalyzeOnlineQueryAccessWithSession analyzes a request through a unified online session. Validation is fixed in this order:

  1. context and session usability;
  2. non-empty request dialect against observed identity;
  3. empty caller analysis profile;
  4. absent caller schema resolver;
  5. linked capability availability;
  6. existing mode and analysis validation.

An empty request dialect delegates dialect selection to the observed identity. A non-empty request dialect is only a constraint and must match exactly; it never selects or overrides the proof route.

func AnalyzePostgreSQLQueryAccessWithSession deprecated added in v0.390.0

func AnalyzePostgreSQLQueryAccessWithSession(_ context.Context, _ *PostgreSQLQueryAccessSession, _ QueryAccessRequest) (*QueryAccessResult, error)

AnalyzePostgreSQLQueryAccessWithSession returns ErrPostgreSQLSessionNotAvailable when built without the postgresql tag.

Deprecated: Use AnalyzeOnlineQueryAccessWithSession.

func AnalyzeQueryAccess added in v0.380.0

func AnalyzeQueryAccess(ctx context.Context, req QueryAccessRequest) (*QueryAccessResult, error)

AnalyzeQueryAccess performs query access analysis.

type QueryAccessSchemaResolver added in v0.380.0

type QueryAccessSchemaResolver interface {
	ResolveRelation(ctx context.Context, dialect, schema, name string) (QueryAccessRelationSchema, error)
}

QueryAccessSchemaResolver resolves relation metadata for name resolution.

type QueryAccessUnresolved added in v0.380.0

type QueryAccessUnresolved struct {
	Reference string `json:"reference"`
	Reason    string `json:"reason"`
}

QueryAccessUnresolved represents an unresolved reference.

type Request

type Request struct {
	SQL              string
	Dialect          Dialect
	ConfigPath       string
	Schema           string
	MetadataProvider MetadataProvider
}

Request describes one public audit invocation.

type Result

type Result struct {
	Verdict        Verdict                  `json:"verdict"`
	Summary        Summary                  `json:"summary"`
	Statements     []StatementResult        `json:"statements,omitempty"`
	GlobalFindings []Finding                `json:"global_findings,omitempty"`
	Unsupported    []spec.UnsupportedDetail `json:"unsupported,omitempty"`
	Explanation    *Explanation             `json:"explanation,omitempty"`
	Diagnostics    []spec.Diagnostic        `json:"diagnostics,omitempty"`
}

Result is the stable public audit output.

func Audit

func Audit(ctx context.Context, request Request) (Result, error)

Audit executes the stable public audit flow.

type StatementResult

type StatementResult struct {
	Index         int          `json:"index"`
	Kind          string       `json:"kind"`
	RawSQL        string       `json:"raw_sql,omitempty"`
	NormalizedSQL string       `json:"normalized_sql,omitempty"`
	Findings      []Finding    `json:"findings,omitempty"`
	Impact        *Impact      `json:"impact,omitempty"`
	Explanation   *Explanation `json:"explanation,omitempty"`
}

StatementResult stores public findings for a single SQL statement.

type Summary

type Summary struct {
	Statements int `json:"statements"`
	Blockers   int `json:"blockers"`
	Warnings   int `json:"warnings"`
	Notices    int `json:"notices"`
}

Summary captures high-level public audit counts.

type Table

type Table = spec.Table

Table mirrors the domain table shape used inside metadata snapshots.

type TableSnapshot

type TableSnapshot = spec.TableSnapshot

TableSnapshot mirrors metadata-aware target table snapshots for public providers.

type Verdict

type Verdict string

Verdict identifies the final public audit outcome.

const (
	VerdictPass   Verdict = "pass"
	VerdictReview Verdict = "review"
	VerdictReject Verdict = "reject"
)

Jump to

Keyboard shortcuts

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