Ir para o conteúdo

tempest_fastapi_sdk.admin.sql_shell

O console SQL do admin e a política que decide quem roda o quê.

« Admin, dados e API


sql_shell

A SQL console for the admin, with a policy in front of it.

Every serious admin panel grows one of these — phpMyAdmin, Adminer, Metabase's native query, Django SQL Explorer — because eventually someone needs an answer the list view cannot give. This is that console, plus the guard rails to make it survivable.

Read this before you enable it

A SQL filter in the application is defence in depth, not a security boundary. The analyser here parses statements properly (via sqlglot) rather than matching strings, which stops the ordinary mistakes: a DROP typed by someone who only meant to SELECT, an UPDATE with no WHERE, a query against a table that holds card data. It will not stop a determined operator with time — SQL has CTEs, subqueries, functions, dialect extensions and comment tricks, and any parser-based allowlist is a game of coverage.

The boundary that actually holds is the database user. A role granted only SELECT on three tables cannot DROP anything no matter what reaches it:

CREATE ROLE admin_console LOGIN PASSWORD '…';
GRANT CONNECT ON DATABASE app TO admin_console;
GRANT SELECT ON orders, customers, invoices TO admin_console;

Point the console at that connection, then use the policy below to narrow further and to produce a readable refusal instead of a database error. Used that way the two layers complement each other. Used alone, the policy is a speed bump.

The console is off by default and every attempt — allowed or refused — goes to the audit hook.

SqlCapabilityEnum

Bases: BaseStrEnum

What a console may do, one statement family per member.

Split the way an operator thinks about risk rather than the way SQL groups keywords: DELETE is separate from UPDATE because losing rows and corrupting them are different incidents, and DROP is separate from the rest of DDL because it is the one nobody undoes.

  • READ — SELECT, WITH … SELECT, DESCRIBE, the PRAGMA forms that only report (table_info(t), a bare PRAGMA journal_mode), and EXPLAIN / SHOW only where sqlglot parses them into a typed expression (the mysql dialect). Under postgres, sqlite and no dialect, sqlglot 30 falls back to a generic Command for EXPLAIN and SHOW, so they classify as ADMIN. A statement that reads at the top and writes inside — a data-modifying CTE, MySQL's EXPLAIN ANALYZE, which executes what it explains — takes the capability of the write.
  • INSERT — adds rows.
  • UPDATE — changes rows.
  • DELETE — removes rows.
  • DDL — CREATE / ALTER / COMMENT.
  • DROP — DROP and TRUNCATE: irreversible structure loss.
  • ADMIN — GRANT / REVOKE / SET and anything the analyser cannot classify. Unknown statements land here on purpose, so a construct nobody anticipated needs the most privileged capability rather than slipping through as harmless.

SqlShellError

Bases: Exception

The console refused or could not run a statement.

SqlShellDenied

Bases: SqlShellError

The policy refused the statement.

Distinct from a database error so a caller can tell "you are not allowed" from "your SQL is wrong" — the two need different messages and different log severities.

SqlStatement

Bases: BaseSchema

One analysed statement.

Attributes:

Name Type Description
sql str

The statement as it will be executed.

capability SqlCapabilityEnum

What running it would do.

tables list[str]

Tables it touches, lowercased and without a schema qualifier.

has_where bool

Whether a mutating statement carries a WHERE.

returns_rows bool

Whether to expect a result set.

SqlShellPolicy

Bases: BaseSchema

What the console is allowed to do.

The default is the safest useful thing: read-only, every table, a thousand rows. Widening it is a deliberate act.

Attributes:

Name Type Description
capabilities set[SqlCapabilityEnum]

Statement families allowed. Defaults to read-only.

allowed_tables set[str]

When non-empty, only these tables may be touched. Compared lowercased and without schema.

denied_tables set[str]

Never touchable, even when listed in allowed_tables — deny wins, so adding a table here cannot be undone by a broad allow rule elsewhere.

max_rows int

Rows fetched from a result set before truncating. Protects the browser and the server, not the database.

max_statements int

How many statements one submission may carry. Defaults to 1: multi-statement input is how an allowed SELECT smuggles a DROP past a reader skimming the box.

require_where bool

Refuse UPDATE / DELETE without a WHERE. The single most common console accident.

statement_timeout_ms int | None

Server-side statement timeout where the dialect supports it. None leaves the database default.

read_only property

read_only: bool

Return whether the policy permits nothing that mutates.

Returns:

Name Type Description
bool bool

True when every allowed capability is read-only,

bool

which is what lets the service open a read-only transaction.

table_allowed

table_allowed(table: str) -> bool

Return whether table may be touched.

Parameters:

Name Type Description Default
table str

The table name, any case.

required

Returns:

Name Type Description
bool bool

Whether the policy permits it. Deny is checked first, so

bool

a table in both lists is denied.

SqlResult

Bases: BaseSchema

What running a statement produced.

Attributes:

Name Type Description
columns list[str]

Column names, empty for a statement that returns no rows.

rows list[list[Any]]

The rows, already capped at policy.max_rows.

row_count int

Rows returned, or rows affected for a mutation.

truncated bool

Whether more rows existed than were fetched.

seconds float

Wall-clock duration.

capability SqlCapabilityEnum

What the statement did.

statement str

The statement that ran.

SqlAudit

Bases: BaseSchema

One console attempt, allowed or refused.

Every attempt is audited, including the refused ones — a record of what someone tried to run is usually more interesting than the list of what succeeded.

Attributes:

Name Type Description
principal str

Who ran it.

sql str

What they submitted, verbatim.

allowed bool

Whether the policy let it through.

capability SqlCapabilityEnum | None

What it would do, when the analyser could tell.

tables list[str]

Tables involved.

reason str | None

Why it was refused.

seconds float

Duration, 0 for a refusal.

row_count int

Rows returned or affected.

SqlShellService

SqlShellService(
    db: AsyncDatabaseManager,
    *,
    policy: SqlShellPolicy | None = None,
    dialect: str | None = None,
    auditor: SqlAuditor | None = None,
)

Runs console statements under a policy, and audits every attempt.

Example:

>>> service = SqlShellService(
...     db,
...     policy=SqlShellPolicy(
...         capabilities={SqlCapabilityEnum.READ},
...         denied_tables={"users"},
...     ),
...     dialect="postgres",
... )
>>> result = await service.execute("SELECT 1", principal="ops@x.com")

Attributes:

Name Type Description
policy SqlShellPolicy

What the console may do.

dialect str | None

sqlglot dialect used to parse.

Configure the service.

Parameters:

Name Type Description Default
db AsyncDatabaseManager

The database to run against. Point this at a restricted role — see the module docstring; the policy narrows and explains, the grants enforce.

required
policy SqlShellPolicy | None

What is permitted; a read-only default when None.

None
dialect str | None

sqlglot dialect for parsing.

None
auditor SqlAuditor | None

Called once per attempt, allowed or refused. Its failures are swallowed so a broken audit sink cannot take the console down — but a console you cannot audit is one you should turn off, so log there.

None

execute async

execute(sql: str, *, principal: str = 'unknown') -> SqlResult

Analyse, authorise and run sql.

Parameters:

Name Type Description Default
sql str

The statement to run.

required
principal str

Who is running it, for the audit trail.

'unknown'

Returns:

Name Type Description
SqlResult SqlResult

Columns, rows (capped), row count and timing.

Raises:

Type Description
SqlShellDenied

When the policy refuses it.

SqlShellError

When it does not parse, or the database rejects it.

analyze_sql

analyze_sql(sql: str, *, dialect: str | None = None) -> list[SqlStatement]

Parse sql and describe each statement it contains.

Example:

>>> analyze_sql("SELECT id FROM orders WHERE id = 1")[0].capability
<SqlCapabilityEnum.READ: 'read'>

Parameters:

Name Type Description Default
sql str

One or more statements.

required
dialect str | None

sqlglot dialect ("postgres", "sqlite"). Parsing with the right dialect matters: a statement valid in one and not another would otherwise be misread.

None

Returns:

Type Description
list[SqlStatement]

list[SqlStatement]: One entry per statement, in order.

Raises:

Type Description
ImportError

When the [admin-sql] extra is missing.

SqlShellError

When the SQL does not parse. Refusing unparseable input is deliberate — a statement the analyser cannot read is a statement the policy cannot judge.

check_policy

check_policy(statements: list[SqlStatement], policy: SqlShellPolicy) -> str | None

Return why statements are refused, or None when allowed.

Checks in order of bluntness — count, then capability, then tables, then the WHERE rule — so the message names the first and most fundamental problem rather than a detail behind it.

Parameters:

Name Type Description Default
statements list[SqlStatement]

The analysed statements.

required
policy SqlShellPolicy

The policy to apply.

required

Returns:

Type Description
str | None

str | None: A human-readable refusal, or None to allow.

SqlAuditor module-attribute

SqlAuditor = Callable[[SqlAudit], Awaitable[None] | None]