Documentation
¶
Overview ¶
Package dbviewer runs read-only (and, when explicitly allowed, write) SQL against a managed database by exec'ing the engine's own client inside its container. Credentials never leave the container.
Index ¶
- Constants
- Variables
- func CapabilityEngines() []string
- func HistoryKeepFromEnv(lookup func(string) (string, bool)) int
- type Capabilities
- type Capability
- type Column
- type Dialect
- type DynamoLimits
- type DynamoOp
- type DynamoPrepared
- type DynamoRequest
- type DynamoResult
- type DynamoSortCond
- type EngineCapabilities
- type Evidence
- type Execer
- type Filter
- type ForeignKey
- type Index
- type Kind
- type Limits
- type MongoOp
- type MongoQuery
- type MongoRequest
- type MongoResult
- type Page
- type PageQuery
- type QueryError
- type RedisClient
- type RedisClients
- type RedisEntry
- type RedisInfo
- type RedisInfoField
- type RedisInfoSection
- type RedisKey
- type RedisPair
- type RedisScan
- type RedisSlowEntry
- type RedisSlowlog
- type RedisValue
- type Result
- type SchemaNode
- type Statement
- type Status
- type Structure
- type Table
- type Target
- func (t Target) Clients(ctx context.Context) (RedisClients, error)
- func (t Target) Evidence(ctx context.Context) (Evidence, error)
- func (t Target) Explain(ctx context.Context, st Statement, analyze bool) (Result, error)
- func (t Target) GetKey(ctx context.Context, key string) (RedisValue, error)
- func (t Target) Info(ctx context.Context) (RedisInfo, error)
- func (t Target) Run(ctx context.Context, st Statement, write bool) (Result, error)
- func (t Target) RunDynamo(ctx context.Context, q DynamoPrepared) (DynamoResult, error)
- func (t Target) RunMongo(ctx context.Context, q MongoQuery) (MongoResult, error)
- func (t Target) RunTrusted(ctx context.Context, sql string) (Result, error)
- func (t Target) ScanKeys(ctx context.Context, cursor, pattern string, count int) (RedisScan, error)
- func (t Target) Schema(ctx context.Context) ([]SchemaNode, error)
- func (t Target) SchemaOutline(ctx context.Context) ([]SchemaNode, error)
- func (t Target) Slowlog(ctx context.Context, count int) (RedisSlowlog, error)
- func (t Target) TablePage(ctx context.Context, q PageQuery) (Page, error)
- func (t Target) TableStructure(ctx context.Context, schema, table string) (Structure, error)
Constants ¶
const ( KindQuery = "query" KindExplain = "explain" KindShow = "show" KindWrite = "write" )
Statement kinds the guard classifies an accepted statement into.
const ( EnvQueryTimeout = "APP_DB_QUERY_TIMEOUT" EnvQueryMaxRows = "APP_DB_QUERY_MAX_ROWS" EnvQueryMaxBytes = "APP_DB_QUERY_MAX_BYTES" EnvQueryMaxCell = "APP_DB_QUERY_MAX_CELL_BYTES" EnvSchemaMaxRows = "APP_DB_SCHEMA_MAX_ROWS" EnvQueryMaxSQL = "APP_DB_QUERY_MAX_SQL_BYTES" EnvHistoryKeep = "APP_DB_QUERY_HISTORY_KEEP" )
Environment variables that tune the console. Each has a default so an unset variable behaves the same on every install.
const ( OpContains = "contains" OpEquals = "equals" OpIsNull = "is_null" OpNotNull = "not_null" )
Filter operators accepted by a table page.
const MaxFilters = 8
MaxFilters bounds how many column filters one page request may combine.
Variables ¶
var ( ErrEmpty = errors.New("statement is empty") ErrMultiStatement = errors.New("only a single statement is allowed") ErrBackslash = errors.New("backslash is not allowed in console statements") ErrControlChar = errors.New("statement contains a control character") ErrUnterminated = errors.New("unterminated string, identifier, or comment") ErrExecutableComment = errors.New("executable comments are not allowed") ErrUnicodeEscape = errors.New("unicode escape syntax is not allowed") ErrNotAllowed = errors.New("statement type is not allowed in read-only mode") ErrDenied = errors.New("statement uses a function or keyword that is not allowed") )
Rejection reasons, exported so handlers can map them to a 400.
var ErrDynamoDenied = errors.New("dynamodb request is not allowed")
ErrDynamoDenied reports a request the DynamoDB guard refuses.
var ErrMongoDenied = errors.New("mongodb request is not allowed")
ErrMongoDenied reports a request the Mongo guard refuses.
var ErrNotFound = errors.New("not found")
ErrNotFound reports a table or column the database does not have.
var ErrTimeout = errors.New("query exceeded the configured timeout")
ErrTimeout reports that the statement ran past the configured timeout.
Functions ¶
func CapabilityEngines ¶
func CapabilityEngines() []string
CapabilityEngines lists the engines in the registry (for tests and docs).
Types ¶
type Capabilities ¶
type Capabilities struct {
Browse Capability `json:"browse"`
Query Capability `json:"query"`
WriteQuery Capability `json:"write_query"`
Edit Capability `json:"edit"`
Import Capability `json:"import"`
Export Capability `json:"export"`
Explain Capability `json:"explain"`
SchemaObjects Capability `json:"schema_objects"`
KeyBrowse Capability `json:"key_browse"`
Documents Capability `json:"documents"`
Aggregation Capability `json:"aggregation"`
Stats Capability `json:"stats"`
Indexes Capability `json:"indexes"`
Users Capability `json:"users"`
}
Capabilities lists every explorer feature the UI can render for an engine.
type Capability ¶
Capability is one feature switch. Reason is an i18n key suffix the UI maps to text, empty when the capability is available.
type Column ¶
type Column struct {
Name string `json:"name"`
Type string `json:"type"`
Nullable bool `json:"nullable"`
Default string `json:"default,omitempty"`
PrimaryKey bool `json:"primary_key"`
}
Column is one table column.
type Dialect ¶
type Dialect string
Dialect selects the lexing and deny-list rules for one SQL family.
const ( DialectPostgres Dialect = "postgres" DialectMySQL Dialect = "mysql" DialectMariaDB Dialect = "mariadb" )
Supported dialects.
const DialectDynamoDB Dialect = "dynamodb"
DialectDynamoDB marks a DynamoDB local target. It is never a SQL dialect: only typed requests reach it.
const DialectMongo Dialect = "mongodb"
DialectMongo marks a MongoDB target. It is never a SQL dialect: only the typed Mongo requests below reach it.
type DynamoLimits ¶
DynamoLimits holds the page sizes, read from env like the other viewer limits.
func DynamoLimitsFromEnv ¶
func DynamoLimitsFromEnv(lookup func(string) (string, bool)) DynamoLimits
DynamoLimitsFromEnv reads the page limits, falling back to defaults for unset or invalid values.
type DynamoOp ¶
type DynamoOp string
DynamoOp is one allow-listed read operation. Writes and table changes have no constant here, so they cannot be built.
type DynamoPrepared ¶
type DynamoPrepared struct {
Op DynamoOp
Limit int
Fingerprint string
// contains filtered or unexported fields
}
DynamoPrepared is a request the guard accepted, with its body ready to send.
func CheckDynamo ¶
func CheckDynamo(req DynamoRequest, lim Limits, dl DynamoLimits) (DynamoPrepared, error)
CheckDynamo validates a request against the allow-list and the limits, then builds the body from re-serialised data.
type DynamoRequest ¶
type DynamoRequest struct {
Op DynamoOp
Table string
Index string
// KeyName and KeyValue are the partition key equality of a Query; KeyValue is DynamoDB JSON such as {"S":"x"}.
KeyName string
KeyValue json.RawMessage
Sort *DynamoSortCond
Limit int
// StartKey is the previous page's LastEvaluatedKey, DynamoDB JSON.
StartKey json.RawMessage
// Confirm must be true for a Scan: it reads every item it passes and is slow on large tables.
Confirm bool
// StartTable pages ListTables.
StartTable string
}
DynamoRequest is the typed input; no field is ever executed or concatenated into a command.
type DynamoResult ¶
type DynamoResult struct {
Tables []string `json:"tables,omitempty"`
LastTable string `json:"last_table,omitempty"`
Table json.RawMessage `json:"table,omitempty"`
TTL json.RawMessage `json:"ttl,omitempty"`
Items []json.RawMessage `json:"items"`
Count int `json:"count"`
ScannedCount int `json:"scanned_count"`
LastKey json.RawMessage `json:"last_evaluated_key,omitempty"`
ConsumedCapacity json.RawMessage `json:"consumed_capacity,omitempty"`
Truncated bool `json:"truncated"`
DurationMs int64 `json:"duration_ms"`
}
DynamoResult is the engine answer, trimmed to the caps. Items stay DynamoDB JSON.
type DynamoSortCond ¶
type DynamoSortCond struct {
Name string `json:"name"`
Op string `json:"op"`
Value json.RawMessage `json:"value"`
}
DynamoSortCond is an optional condition on the sort key of a Query.
type EngineCapabilities ¶
type EngineCapabilities struct {
Engine string `json:"engine"`
Kind Kind `json:"kind"`
Planned bool `json:"planned"`
Capabilities Capabilities `json:"capabilities"`
}
EngineCapabilities is the registry row for one engine. Planned marks an engine whose explorer is being built, so the UI shows "not ready".
func CapabilitiesFor ¶
func CapabilitiesFor(engine string) EngineCapabilities
CapabilitiesFor returns the registry row for an engine. Unknown engines get an all unsupported row so the UI degrades instead of failing.
func ExternalCapabilitiesFor ¶
func ExternalCapabilitiesFor(engine string) EngineCapabilities
ExternalCapabilitiesFor is CapabilitiesFor for a connected (not run) database: the viewer reaches only SQL engines there, and writes need the managed path.
type Evidence ¶
type Evidence struct {
DatabaseSizeBytes int64 `json:"database_size_bytes"`
SchemasScanned int `json:"schemas_scanned"`
UserTables int64 `json:"user_tables"`
ExcludedSchemas []string `json:"excluded_schemas"`
}
Evidence is what the catalog says about a database independent of the schema listing, so an empty listing can be checked against it.
type Execer ¶
type Execer interface {
ExecWithInput(ctx context.Context, containerID string, cmd []string, stdin io.Reader) (io.ReadCloser, error)
}
Execer is the slice of docker.Runtime the console needs.
type Filter ¶
type Filter struct {
Column string `json:"column"`
Op string `json:"op"`
Value string `json:"value"`
}
Filter restricts one column of a table page.
type ForeignKey ¶
type ForeignKey struct {
Name string `json:"name"`
Schema string `json:"schema"`
Table string `json:"table"`
Columns []string `json:"columns"`
RefSchema string `json:"ref_schema"`
RefTable string `json:"ref_table"`
RefColumns []string `json:"ref_columns"`
}
ForeignKey is one foreign key constraint. Schema and Table name the table that owns it; RefSchema and RefTable the table it points at.
type Index ¶
type Index struct {
Name string `json:"name"`
Definition string `json:"definition"`
Unique bool `json:"unique"`
Primary bool `json:"primary"`
}
Index is one table index.
type Kind ¶
type Kind string
Kind groups engines by the shape of their data, so the UI picks a layout.
type Limits ¶
type Limits struct {
Timeout time.Duration
MaxRows int
MaxBytes int
MaxCellBytes int
SchemaRows int
SQLBytes int
}
Limits bounds one console execution.
type MongoOp ¶
type MongoOp string
MongoOp is one allow-listed read operation.
const ( MongoListDatabases MongoOp = "listDatabases" MongoListCollections MongoOp = "listCollections" MongoCollections MongoOp = "collections" MongoFind MongoOp = "find" MongoCountDocuments MongoOp = "countDocuments" MongoEstimatedCount MongoOp = "estimatedDocumentCount" MongoGetIndexes MongoOp = "getIndexes" MongoStats MongoOp = "stats" )
Allowed operations. Anything else is rejected before a script is built.
type MongoQuery ¶
type MongoQuery struct {
Op MongoOp
Limit int
Fingerprint string
// contains filtered or unexported fields
}
MongoQuery is a request the guard accepted, with its script ready to run.
func CheckMongo ¶
func CheckMongo(req MongoRequest, lim Limits) (MongoQuery, error)
CheckMongo validates a request against the allow-list and the limits and builds the script from the re-serialised, validated data only.
type MongoRequest ¶
type MongoRequest struct {
Op MongoOp
Database string
Collection string
Filter json.RawMessage
Sort json.RawMessage
Projection json.RawMessage
// After is the _id of the last document of the previous page.
After json.RawMessage
Limit int
}
MongoRequest is the typed input; no field is ever executed as script text.
type MongoResult ¶
type MongoResult struct {
Documents []json.RawMessage `json:"documents"`
Truncated bool `json:"truncated"`
// NextAfter is the canonical extended JSON _id of the last document when more exist.
NextAfter json.RawMessage `json:"next_after,omitempty"`
DurationMs int64 `json:"duration_ms"`
}
MongoResult holds the lines one Mongo operation produced.
type PageQuery ¶
type PageQuery struct {
Schema, Table string
Limit, Offset int
SortColumn string
SortDesc bool
FilterColumn string
FilterOp string
FilterValue string
Filters []Filter
}
PageQuery asks for one page of a table. FilterColumn/FilterOp/FilterValue are the first filter; Filters adds more, all combined with AND.
type QueryError ¶
type QueryError struct{ Message string }
QueryError carries the database's own error text, which is safe to show: it describes the caller's statement and never contains credentials.
func (*QueryError) Error ¶
func (e *QueryError) Error() string
type RedisClient ¶
type RedisClient struct {
ID string `json:"id"`
Addr string `json:"addr"`
Age int64 `json:"age"`
Idle int64 `json:"idle"`
Flags string `json:"flags"`
DB string `json:"db"`
Cmd string `json:"cmd"`
User string `json:"user"`
}
RedisClient is one connected client. Names can hold secrets, so they are not returned.
func ParseRedisClients ¶
func ParseRedisClients(lines []string) []RedisClient
ParseRedisClients reads CLIENT LIST lines, keeping only safe fields.
type RedisClients ¶
type RedisClients struct {
Clients []RedisClient `json:"clients"`
Truncated bool `json:"truncated"`
}
RedisClients is the capped CLIENT LIST result.
type RedisEntry ¶
type RedisEntry struct {
ID string `json:"id,omitempty"`
Field string `json:"field,omitempty"`
Value string `json:"value,omitempty"`
Score string `json:"score,omitempty"`
Pairs []RedisPair `json:"pairs,omitempty"`
}
RedisEntry is one element of a typed value: a list item, set member, hash field, sorted set member with score, or stream entry with its pairs.
type RedisInfo ¶
type RedisInfo struct {
Sections []RedisInfoSection `json:"sections"`
}
RedisInfo is the INFO panel. Paths, run ids and anything secret-shaped are never in the allow list.
func ParseRedisInfo ¶
ParseRedisInfo splits INFO output into allow listed sections.
type RedisInfoField ¶
RedisInfoField is one allow listed INFO value.
type RedisInfoSection ¶
type RedisInfoSection struct {
Name string `json:"name"`
Fields []RedisInfoField `json:"fields"`
}
RedisInfoSection is one INFO section with only its allow listed fields.
type RedisSlowEntry ¶
type RedisSlowEntry struct {
ID int64 `json:"id"`
Time int64 `json:"time"`
DurationUS int64 `json:"durationUs"`
Command string `json:"command"`
ArgCount int `json:"argCount"`
Client string `json:"client,omitempty"`
}
RedisSlowEntry never carries arguments: only the command name, how many arguments there were and their total size.
func ParseRedisSlowlog ¶
func ParseRedisSlowlog(lines []string) []RedisSlowEntry
ParseRedisSlowlog reads `redis-cli --no-raw SLOWLOG GET` output. Argument values are never collected: only the command name (the first element of field 4) and the number of further argument lines are kept. Labels are right aligned past nine items, so lines are read by trimmed position.
type RedisSlowlog ¶
type RedisSlowlog struct {
Entries []RedisSlowEntry `json:"entries"`
Truncated bool `json:"truncated"`
}
RedisSlowlog is the capped SLOWLOG GET result.
type RedisValue ¶
type RedisValue struct {
Type string `json:"type"`
TTL int64 `json:"ttl"`
Lines []string `json:"lines"`
Truncated bool `json:"truncated"`
// Typed detail (redis_typed.go). Size and MemoryBytes are -1 when unknown.
Encoding string `json:"encoding"`
Size int64 `json:"size"`
MemoryBytes int64 `json:"memoryBytes"`
Subtype string `json:"subtype,omitempty"`
BitLength int64 `json:"bitLength,omitempty"`
BitCount int64 `json:"bitCount,omitempty"`
Unsupported bool `json:"unsupported,omitempty"`
Entries []RedisEntry `json:"entries"`
}
RedisValue is a key's value rendered as text lines, capped by Limits.
type Result ¶
type Result struct {
Columns []string `json:"columns"`
Rows [][]*string `json:"rows"`
RowCount int `json:"row_count"`
Truncated bool `json:"truncated"`
DurationMs int64 `json:"duration_ms"`
}
Result is one statement's output. A nil cell is SQL NULL.
type SchemaNode ¶
SchemaNode groups tables under one schema (a MySQL database).
type Statement ¶
type Statement struct {
// SQL is the statement with its trailing semicolon removed.
SQL string
Kind string
Fingerprint string
// First is the lowercased leading keyword.
First string
}
Statement is a statement the guard accepted.
type Status ¶
type Status string
Status says whether one explorer capability works for an engine today.
type Structure ¶
type Structure struct {
Schema string `json:"schema"`
Name string `json:"name"`
Kind string `json:"kind"`
RowEstimate int64 `json:"row_estimate"`
SizeBytes int64 `json:"size_bytes"`
Columns []Column `json:"columns"`
Indexes []Index `json:"indexes"`
ForeignKeys []ForeignKey `json:"foreign_keys"`
ReferencedBy []ForeignKey `json:"referenced_by"`
DDL string `json:"ddl"`
}
Structure is the full detail of one table, what the schema outline leaves out. ForeignKeys point away from the table, ReferencedBy point at it.
type Table ¶
type Table struct {
Name string `json:"name"`
Kind string `json:"kind"`
RowEstimate int64 `json:"row_estimate"`
SizeBytes int64 `json:"size_bytes"`
Columns []Column `json:"columns"`
Indexes []Index `json:"indexes"`
}
Table is a table, view, or other relation.
type Target ¶
type Target struct {
Exec Execer
ContainerID string
Dialect Dialect
Limits Limits
// External marks a database this platform does not run: Exec starts a
// helper that carries the connection, and ContainerID is unused.
External bool
}
Target is one running database container.
func (Target) Clients ¶
func (t Target) Clients(ctx context.Context) (RedisClients, error)
Clients lists connected clients, capped by the row limit.
func (Target) Explain ¶
Explain returns the plan for a read statement as text lines (Postgres, MySQL, and MariaDB all accept an EXPLAIN prefix).
func (Target) GetKey ¶
GetKey reads one key with fixed read-only commands chosen by type. The key is only ever sent through redisQuote, and every reply is bounded before it is read.
func (Target) Run ¶
Run executes a guard-approved statement. write must match the allowWrites value the statement was checked with.
func (Target) RunDynamo ¶
func (t Target) RunDynamo(ctx context.Context, q DynamoPrepared) (DynamoResult, error)
RunDynamo executes a guard-approved request inside the container and parses the answer.
func (Target) RunMongo ¶
func (t Target) RunMongo(ctx context.Context, q MongoQuery) (MongoResult, error)
RunMongo executes a guard-approved query and collects its output lines.
func (Target) RunTrusted ¶
RunTrusted executes SQL the control plane built itself (introspection, table pages). It still runs in a read-only transaction.
func (Target) Schema ¶
func (t Target) Schema(ctx context.Context) ([]SchemaNode, error)
Schema lists every user schema with its tables, columns, and indexes.
func (Target) SchemaOutline ¶
func (t Target) SchemaOutline(ctx context.Context) ([]SchemaNode, error)
SchemaOutline lists every user schema with its tables, row estimates and sizes but no columns or indexes, so a database with thousands of tables stays a small document. Per-table detail comes from TableStructure.