sqlpolicy

package
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Nov 23, 2026 License: Apache-2.0 Imports: 9 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package sqlpolicy restricts the SQL that clients may run on a SQLite connection. Decision record 0007 (docs/content/docs/decisions/0007-sql-policy.md) states the rules; this package applies them to an ncruces connection.

Index

Constants

This section is empty.

Variables

View Source
var ErrBroken = errors.New("sqlpolicy: connection unusable")

ErrBroken reports that the engine panicked, for example on a stack overflow, or that a reset failed, which leaves the connection in an unknown state. Whether a write transaction was open cannot be known; the engine must assume that one was, and discard the connection.

Functions

This section is empty.

Types

type Conn

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

Conn is a SQLite connection with a Policy applied. Client SQL must run through Run, and the server's own SQL through Privileged; like the connection it wraps, a Conn is not safe for concurrent use.

func (*Conn) Close

func (c *Conn) Close() (err error)

Close closes the connection. After ErrBroken, SQLite may be unable to close it, and its files are then released only when Go finalizes them, which does not release its locks; see the record.

func (*Conn) Privileged

func (c *Conn) Privileged(fn func(*sqlite3.Conn) error) (err error)

Privileged runs fn with the authorizer suspended, for the server's own statements: BEGIN, COMMIT, ROLLBACK and its own pragmas. It restores the authorizer when fn returns or panics. fn must close every statement it prepares. A client's triggers and views that fn's statements reach run with no authorizer and no time limit; see the record's requirements.

func (*Conn) Reset

func (c *Conn) Reset(ctx context.Context) error

Reset returns everything a client can change on the connection to the policy's defaults: it rolls back an open transaction, drops every object in the temp schema and empties its sqlite_sequence, turns foreign key enforcement on and clears the last inserted row id. It is interrupted when the policy's timeout or ctx ends. If it fails, the connection is broken.

func (*Conn) Run

func (c *Conn) Run(ctx context.Context, sql string, fn func(*sqlite3.Stmt) error) (err error)

Run compiles the one statement in sql and runs it, interrupting it when the policy's timeout or ctx ends. fn binds parameters and steps the statement; a nil fn steps it to completion. Run closes the statement after fn returns.

Run refuses, before anything is compiled, SQL longer than MaxSQLLength or holding a NUL byte; and, before any step, SQL that holds no statement or anything after the first statement other than white space, comments and the statement's own semicolon. A refusal by the policy, including the timeout and the memory limit, is returned as *Error; any other error comes from SQLite or from fn. After a panic in the engine, this Run and every later one return an error that wraps ErrBroken, or *Error with ReasonMemory for the first. A panic in fn's own code is not recovered.

type Error

type Error struct {
	Reason Reason
}

Error is a refusal by the policy. It carries no SQL text, which can hold secrets.

func (*Error) Error

func (e *Error) Error() string

type Limits

type Limits struct {
	MaxLength            int           // bytes in one string or BLOB, one row's record and one aggregate's result (SQLITE_LIMIT_LENGTH)
	MaxSQLLength         int           // bytes of SQL text given to one Run (SQLITE_LIMIT_SQL_LENGTH)
	MaxExprDepth         int           // depth of an expression tree, against which joined tables, composite-key pairs, nested subqueries and joined CTEs also count, and nesting of views, CTEs and subqueries (SQLITE_LIMIT_EXPR_DEPTH)
	MaxParserDepth       int           // depth of the parser's stack, which nesting in parentheses uses (SQLITE_LIMIT_PARSER_DEPTH)
	MaxCompoundSelect    int           // terms in a compound SELECT (SQLITE_LIMIT_COMPOUND_SELECT)
	MaxVDBEOps           int           // instructions in one compiled statement (SQLITE_LIMIT_VDBE_OP)
	MaxFunctionArgs      int           // arguments to one SQL function (SQLITE_LIMIT_FUNCTION_ARG)
	MaxLikePatternLength int           // bytes in a LIKE or GLOB pattern (SQLITE_LIMIT_LIKE_PATTERN_LENGTH)
	MaxVariableNumber    int           // highest parameter number (SQLITE_LIMIT_VARIABLE_NUMBER)
	MaxTriggerDepth      int           // nesting depth of triggers and foreign key actions (SQLITE_LIMIT_TRIGGER_DEPTH)
	MaxPageCount         int           // pages the main database may hold (PRAGMA max_page_count); zero leaves SQLite's
	Timeout              time.Duration // wall-clock time one Run may take
}

Limits are the limits a Policy applies to a connection. A zero field takes its default. The defaults suit tests; the server sets each field from its own configuration.

type Policy

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

Policy is a validated set of limits. Create one with New.

func New

func New(l Limits) (*Policy, error)

New returns a Policy with l's limits, using the default for each zero field. It fails if a field is out of the range the SQLite build supports, or if the nesting limits together exceed the modelled stack cost, which is a floor: SQL within the limits can still overflow the stack. MaxSQLLength and MaxVDBEOps also bound the policy's own statements and the SQL SQLite compiles itself, and New does not check their lower end: Apply fails below about 26 bytes or 51 instructions, and a little above that Apply succeeds but Reset or SQLite's own SQL, such as CREATE TABLE's, fails.

func (*Policy) Apply

func (p *Policy) Apply(ctx context.Context, c *sqlite3.Conn) (_ *Conn, err error)

Apply configures c for untrusted SQL: database configuration, temporary storage in memory, limits, the optional page count, and the authorizer. The engine calls Apply after its own set-up of c, and issues every later statement of its own through Privileged. Setting the authorizer expires statements prepared on c before Apply, so SQLite compiles them again under the policy if they are stepped.

The first statement on c that reads the schema loads it, and clients wrote it. If the engine's set-up before Apply, such as PRAGMA journal_mode, ran one, the schema was loaded there, outside Apply, and the engine must bound and recover that set-up itself (record 0007, requirement 5). Otherwise Apply's first statement loads it. Apply is interrupted when ctx ends, and a panic in the engine is returned as an error, as in Run; the connection is then unusable.

type Reason

type Reason string

Reason names the rule that refused a statement. Its values are stable.

const (
	ReasonAttach         Reason = "attach"          // ATTACH, and VACUUM, which attaches its output
	ReasonDetach         Reason = "detach"          // DETACH
	ReasonTransaction    Reason = "transaction"     // BEGIN, COMMIT, END, ROLLBACK; SAVEPOINT, RELEASE and ROLLBACK TO outside a transaction
	ReasonPragma         Reason = "pragma"          // a pragma outside the allowlist, in any form
	ReasonFunction       Reason = "function"        // an SQL function outside the allowlist
	ReasonStatement      Reason = "statement"       // any other kind of statement, such as CREATE VIRTUAL TABLE, or an ALTER TABLE that checks existing rows
	ReasonStatementCount Reason = "statement_count" // no statement, or text after the first one
	ReasonNUL            Reason = "nul"             // a NUL byte in the SQL
	ReasonSQLLength      Reason = "sql_length"      // SQL longer than MaxSQLLength
	ReasonTimeLimit      Reason = "time_limit"      // the statement ran past the policy's timeout
	ReasonMemory         Reason = "memory"          // the connection's memory; the Conn is then broken
)

Reasons.

Jump to

Keyboard shortcuts

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