Almost every self-hosted admin panel eventually adds a "Run SQL" tab with a Read-Only toggle.
The first prototype almost always looks the same: trim the query, check whether it starts with SELECT, and pipe it into psql or mysql inside the database container.
It works for five minutes—until someone sends one of these:
-- 1. Client meta-command (runs a shell inside the container, not SQL)
\! id
-- 2. Transaction breakout
SELECT 1; COMMIT; DROP TABLE users;
-- 3. MySQL executable comment (looks like a comment, executes on the server)
/*!50000 DROP TABLE users */
-- 4. Postgres nested block comments & dollar quotes hiding semicolons
/* outer /* inner */ */ SELECT $$ ; $$; DELETE FROM sessions;
Even when nobody is trying to break out, a single accidental SELECT * FROM events on a 10-million-row table can stream gigabytes back into your control plane and OOM-kill the dashboard.
This is the design behind the database console in Nitrobase.
Nitrobase has only recently launched and is still in Beta. Its console is not a replacement for a full desktop SQL IDE. The goal is narrower: let you inspect production PostgreSQL, MySQL, and MariaDB databases directly from the browser while enforcing read-only safety inside the database engine itself—not just in a JavaScript parser.
Layer 1: Treat the SQL lexer as a guardrail, never the security boundary
Nitrobase does parse the input before anything touches a container (scanSql and checkConsoleSql), using a dialect-aware lexer rather than a naive .split(";") or ^SELECT regex:
-
PostgreSQL dialect: Handles nested
/* /* ... */ */block comments, dollar-quoted strings ($$...$$and$tag$...$tag$), andE'...'backslash escapes. -
MySQL / MariaDB dialect: Handles
#line comments, backtick-quoted identifiers, and flags server-executed comments (/*! ... */and MariaDB/*M! ... */). -
Client command blocking: Rejects any backslash outside strings/comments (
\!,\copy,\i) and blocks MySQL CLI commands (SYSTEM,SOURCE,TEE,PAGER,DELIMITER, etc.). -
Read-only rules: In Postgres, refuses transaction control (
BEGIN,COMMIT,ROLLBACK,SAVEPOINT,PREPARE) and session/role overrides (SET ROLE,SET SESSION AUTHORIZATION,SET TRANSACTION,SET default_transaction_read_only). In MySQL/MariaDB, restricts statements to an explicit read-only allowlist (SELECT,SHOW,DESCRIBE,EXPLAIN,WITH,TABLE,VALUES,USE) and blocksINTO OUTFILE/INTO DUMPFILE.
Why bother writing a real lexer if it is not the security boundary? Two reasons:
-
Clear, immediate feedback before spawning a container process (for example, refusing an unterminated dollar quote or a
mysqlclient command with a specific error code). -
Safe audit logging (
maskSqlLiterals): Every string literal and dollar-quoted body is replaced with'…'before logging—so a write-modeALTER ROLE app PASSWORD '...'never leaks plaintext credentials into audit history. If the SQL cannot even be tokenized (unterminated quote), it fails closed by masking everything from the first quote onward.
Still, any parser can have edge cases—such as a SELECT calling a volatile function with side effects. That is why the real enforcement lives in Layer 2.
Layer 2: Enforce read-only inside the database engine
When a query runs in read-only mode, Nitrobase does not log in as the database superuser or root account. Instead, after every deploy, it idempotently provisions a dedicated least-privilege role (nitrobase_console) per engine:
| Engine | Read-only role & isolation | Transaction & timeout guard |
|---|---|---|
| PostgreSQL |
nitrobase_console with NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS, PASSWORD NULL (blocks TCP SCRAM logins; container Unix socket only), pg_read_all_data + pg_read_all_stats, and default_transaction_read_only = on
|
PGOPTIONS sets default_transaction_read_only=on and statement_timeout; executed via psql -c 'BEGIN' -c 'SET TRANSACTION READ ONLY' -c "SET LOCAL statement_timeout = ..." -c "$sql" -c 'ROLLBACK'
|
| MySQL 8 |
'nitrobase_console'@'localhost' via --protocol=socket, SET PERSIST partial_revokes = ON, GRANT SELECT, SHOW VIEW ON *.*, then REVOKE SELECT, SHOW VIEW ON mysql.* (cannot read mysql.user password hashes) |
SET SESSION TRANSACTION READ ONLY, SET SESSION max_execution_time, START TRANSACTION READ ONLY, ending with ROLLBACK
|
| MariaDB |
'nitrobase_console'@'localhost' via --protocol=socket (since MariaDB lacks partial_revokes, Nitrobase refreshes per-database SELECT, SHOW VIEW grants excluding mysql, information_schema, performance_schema, sys before each read-only run) |
SET SESSION TRANSACTION READ ONLY, SET SESSION max_statement_time, START TRANSACTION READ ONLY, ending with ROLLBACK
|
Two subtle details here matter more than they look at first glance:
-
Passing SQL via
psql -c "$sql"(read fromstdin, never argv): Becausepsqlnever interprets backslash meta-commands inside-c, even if a backslash somehow slipped past validation,\! shis rejected as invalid SQL instead of spawning a shell. Meanwhile, reading the SQL fromstdinkeeps queries and passwords out ofpsoutput on the host (MYSQL_PWDis likewise read from an environment variable inside the container, never passed as-p). -
Locking out
mysql.*and TCP logins: A "read-only" MySQL user withSELECT ON *.*can still read password hashes frommysql.userunlessmysql.*is explicitly revoked. And giving Postgres'snitrobase_consolePASSWORD NULLguarantees it can never authenticate over TCP—only viadocker execon the local Unix socket.
Layer 3: Cap stdout and stderr inside the container
Preventing writes is only half the problem. Preventing a huge query from crashing the control plane is the other half.
If you let docker exec run uncapped and truncate output in Node.js afterward, the database client still reads and serializes the entire table across SSH into memory. Instead, Nitrobase wraps the database client in a small POSIX sh pipeline inside the container:
docker exec -i <container> sh -c '...'
│
├── stdout ──► head -c <maxBytes> ──► triggers SIGPIPE (stops DB client early)
│ ▲
│ └── appends "\n__nitrobase_exit_<nonce>__:<exitCode>" via FD 4
│
└── stderr ──► tail -c <maxErrorBytes> ──► drains NOTICE floods, keeps final ERROR
Look closely at what that FD redirection gives you:
-
head -con stdout stops reading as soon as the byte cap is reached, sendingSIGPIPEback topsqlormysqlso a runawaySELECT *stops immediately inside the container. -
tail -con stderr drains noisyNOTICEfloods without buffering them in the panel's RAM, while keeping the last bytes where the actualERROR:line lives. -
A per-run random hex nonce marker (
__nitrobase_exit_<nonce>__:<status>) follows the client output on stdout. Query results cannot spoof it, and ifhead -ctruncated stdout before the marker arrived, Nitrobase immediately sees the marker is missing and marks the result as truncated (backed up by a second byte-capped collector on the Node side as well).
For MySQL/MariaDB multi-statement scripts, Nitrobase uses the same nonce trick (SELECT '__nitrobase_result_<nonce>__' AS ...) right before the final statement so the parser cleanly isolates the last result set from earlier statements.
What this design still does not solve
A read-only transaction and byte cap protect data integrity and panel memory, not database CPU or I/O completely. An unindexed CROSS JOIN can still consume CPU until statement_timeout or max_execution_time fires.
And when a user explicitly switches the console to Write mode, Nitrobase connects as the database's main superuser/root account—at that point the safety net is intentionally off, relying on explicit mode confirmation and literal-masked audit logs rather than query restrictions.
My checklist for building a browser SQL console
- [ ] Never trust a regex or
.split(";")as your read-only security boundary - [ ] Block client meta-commands (
psql\!,mysqlSYSTEM/SOURCE) and avoid passing raw SQL or passwords on CLI argv - [ ] Run read-only queries under a dedicated least-privilege DB role inside a
READ ONLYtransaction with a server-side statement timeout - [ ] Restrict the read-only role from reading system credential tables (
mysql.*) and lock it to local socket access where possible - [ ] Cap stdout (
head -c+SIGPIPE) and stderr (tail -c) inside the container, using a per-run nonce marker to detect truncation cleanly - [ ] Mask string literals (and fail closed on malformed SQL) before writing queries to audit logs
A regex checks what a query looks like. Enforcing roles, transactions, and stream caps inside the container checks what it can actually do.
Nitrobase source code: https://github.com/AydenGroup/nitrobase
Top comments (1)
One gap for the Postgres lexer: set_config() is a function call, not SET. On PG 17 in your BEGIN / READ ONLY / SET LOCAL statement_timeout='2s' setup,
select set_config('statement_timeout','0',true); select pg_sleep(4)ran the full 4s. Packed into one statement it still got cancelled, so allowing only one statement closes it.