tempest_fastapi_sdk.admin.sql_shell¶
O console SQL do admin e a política que decide quem roda o quê.
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, thePRAGMAforms that only report (table_info(t), a barePRAGMA journal_mode), andEXPLAIN/SHOWonly where sqlglot parses them into a typed expression (themysqldialect). Underpostgres,sqliteand no dialect, sqlglot 30 falls back to a genericCommandforEXPLAINandSHOW, so they classify asADMIN. A statement that reads at the top and writes inside — a data-modifying CTE, MySQL'sEXPLAIN 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—DROPandTRUNCATE: irreversible structure loss.ADMIN—GRANT/REVOKE/SETand 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 |
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
|
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 |
require_where |
bool
|
Refuse |
statement_timeout_ms |
int | None
|
Server-side statement timeout
where the dialect supports it. |
read_only
property
¶
Return whether the policy permits nothing that mutates.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
bool
|
|
bool
|
which is what lets the service open a read-only transaction. |
table_allowed
¶
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
|
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, |
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
|
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 ( |
None
|
Returns:
| Type | Description |
|---|---|
list[SqlStatement]
|
list[SqlStatement]: One entry per statement, in order. |
Raises:
| Type | Description |
|---|---|
ImportError
|
When the |
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 |