gizmodata/hardcharger
À propos
🚀 Hardcharger, the analytics server from GizmoData
Données et analyseProgression mesurée des étoiles
- in 24h
- Historique en cours
- in 7 days
- Historique en cours
- in 15 days
- Historique en cours
- in 1 month
- Historique en cours
Variations nettes sur des périodes qui se chevauchent, pas des totaux quotidiens. Les mesures absentes restent vides. Les étoiles indiquent l’intérêt, pas la qualité.
README.md
OriginalFast, secure, remote DuckDB SQL on Hardcharger Engine. Every feature included.
Hardcharger Engine is GizmoData's performance fork of DuckDB.
The quickest start: fully managed, nothing to install.
📖 Documentation · ⬇️ Install it yourself
Or try it on your phone or tablet:
🏎️ What is Hardcharger?
Hardcharger™ puts Hardcharger Engine 2.0, GizmoData's performance fork of DuckDB 2.0, on the network. Clients connect over Chargewire, an open HTTP protocol that moves Apache Arrow record batches straight from the engine to your application: no gRPC, no Flight, no sidecars.
It is the successor to GizmoSQL, rebuilt from scratch for DuckDB 2.0, and it is free: no editions, no license keys. Everything that was Enterprise in GizmoSQL is in every Hardcharger build.
- 🦆 Hardcharger Engine inside. A standalone server on the v2 C API of
Hardcharger Engine 2.0, not an extension. The
engine is DuckDB 2.0, the DuckDB team's work, with targeted
performance changes from GizmoData on top: join planning for OR conditions under
DISTINCTand for timestamp-to-date keys, integer range filters, filtered scans, read-ahead, substring search and regex extraction (the changes and what we measured). DuckDB's SQL syntax, extensions and file format are unchanged. - ⚡ Chargewire on the wire. A query and its first rows come back in one HTTP round trip. Large results stream as Arrow IPC, compressed with LZ4 or zstd when asked, and can be resumed. Bulk ingest streams Arrow straight into a table.
- 🔐 Security in the core, not bolted on. Token sign-in, TLS and mTLS, and role-based access control checked inside the engine against each statement's own plan. Also row policies, column masking, tenants, SSO (OIDC/JWKS) and a tamper-evident audit log.
- 🔭 Observable. Instrumentation into a DuckDB file or PostgreSQL, catalog logging (also
into DuckLake), a Prometheus
/metricsendpoint, query profiles andKILL SESSION. - 🧩 Configured your way. Flags,
HARDCHARGER_*environment variables, or a YAML file. - 🌐 Ready to scale out. Results are already described as partitions with locations, so distributed query execution can arrive without a protocol change.
📖 The documentation covers installing, connecting from every client, security, operations and the full reference.
🖥️ Desktop app (v2.1.0+)
Run Hardcharger from a native app for macOS 15+ on Apple silicon or Windows: start and stop the server, open its SQL workspace, manage settings, and follow the logs. Closing the window leaves the server running in the macOS menu bar or Windows system tray; Quit Hardcharger stops it.
The dashboard images show the design preview with sample data. The app runs the same
hardcharger-server executable shipped in the command-line packages and opens its built-in
web UI in a separate window. It also bundles the hardcharger CLI. Pick the desktop app
for an interactive computer, or the command-line packages for terminals, automation,
containers and operating-system services. Both remain supported.
For v2.1.0+, desktop release artifacts use the Hardcharger-desktop-… prefix:
the macOS .dmg is signed and notarized, and the Windows .msi is signed. The existing
Windows Hardcharger-windows-…msi installs the command-line tools. Linux users continue
to use the command-line packages or Docker; a Linux desktop package is follow-up work.
See the desktop guide for installation, network sharing, certificates,
settings import/export, and the difference between closing and quitting.
🌐 Built-in web UI
Hardcharger has a web UI compiled into the server binary: nothing extra to install, and it is
served on the server's own port and TLS certificate. It is off by default; --web-ui turns it on
(or HARDCHARGER_WEB_UI=true, or web_ui: true in the YAML file).
openssl req -x509 -newkey ec -pkeyopt ec_paramgen_curve:prime256v1 -nodes -days 30 -subj /CN=localhost -addext subjectAltName=DNS:localhost -keyout server.key -out server.pem
HARDCHARGER_ADMIN_PASSWORD='change-me' hardcharger-server --web-ui --tls-cert server.pem --tls-key server.key --database demo.duckdb
# open https://localhost:31337/ui and sign in as hardcharger / change-me (the certificate is self-signed)
- ✍️ SQL editor: up to 20 tabs, each with its own session (its own transaction, temporary tables and settings). Ctrl/⌘+Enter runs the statement at the cursor (a bar in the margin marks it) or exactly the selection; ⇧ runs all, with a result tab per result set and Messages. Cancel stops the statement on the server and says how far a script got. An open or failed transaction shows as a badge, with Commit and Rollback, straight from the server.
- 📊 Results grid for up to a million rows, in DuckDB's own formatting: sort (NULLs last), filter, resize columns, and select cells, ranges or rows like a spreadsheet, with the full keyboard. Ctrl/⌘+C copies so a paste into Excel or Google Sheets lands as cells (in every browser, Safari included); double-click or Enter shows a value in full, JSON pretty-printed.
- 🔭 SQL Monitor (v2.1.0+) for unrestricted administrators: live queued, executing and fetching
statements, recent outcomes and timeouts, queue status and available concurrency slots
(
--enable-instrumentation), captured query profiles, and separate query-detail windows. Server Configuration (v2.1.0+) shows current session/global values, edits and resets settings at supported runtime scopes, and identifies startup settings that need a restart. Both tabs are available in a browser through--web-uiand in the desktop SQL workspace. See SQL Monitor and Server Configuration. - 🗂️ Schema browser and autocomplete that follow access control: each user sees only the catalogs, schemas, tables and columns their roles allow. Tables and Views in their own groups, columns with their types; double-click or drag a name into the editor (fully qualified, quoted where needed); preview a table, show a view's definition, search every table and view by name. Autocomplete offers tables, schemas, columns (through aliases too), functions and keywords.
- 📤 Upload data: a CSV, TSV, Excel (.xlsx, .xls, .xlsb), Parquet, JSON or Arrow file into a new table, or appended to (columns matched by name) or replacing an existing one, from the toolbar, the schema browser, or a file dropped on the page. The browser reads the file (an Excel workbook's sheets, dates in its own date system, numbers, text and blank cells; a CSV's delimiter, quotes and header row), shows the first rows with each column's type to change, rename or skip, and sends it over Chargewire's bulk ingest in pieces of a few megabytes, in one transaction: a progress bar, Cancel, and a failed upload leaves the table unchanged. Large CSV, JSON-lines, Parquet and Arrow files upload at any size.
- 💾 Downloads of the rows as shown (CSV, TSV, JSON, Excel) or the whole typed result (Parquet, Arrow IPC), made in the browser.
- 🗺️ GEOMETRY values as WKT (as DuckDB's
ST_AsTextwrites them), and a Map view of the rows shown on a built-in world basemap (nothing loaded from other sites), with a map of a single value in the cell inspector. - 📁 Saved queries in folders, kept in the browser, with export and import as a file; Run as one of your roles under access control.
- 📐 A resizable editor and side panel (drag, keyboard, double-click to reset; kept in the browser), a short How the editor works help with the server's session idle timeout, and a layout for phone-sized screens.
- 🧭 API page: the server's own Chargewire API, from its OpenAPI description
(
/chargewire/v1/openapi.json), in Swagger UI. Try it out sends requests to this server only, signed in as you: the page adds your sign-in to each request as it leaves, so there is no token to paste, and it never goes to another origin or into storage. Arrow results come back as a file to download. - 🔏 Certificate sign-in under mutual TLS: the browser presents its client certificate to
load
/uiat all, and with--mtls-certificate-sign-inthe page offers Sign in with my certificate, no password needed. - 🌐 Sign in with your identity provider: with browser sign-in on (below), the page offers
Sign in with beside the user name and password, and comes back signed in. A
link to
/ui/?sign_in=browserstarts that sign-in without the click. - 🔒 Start sessions read-only on the sign-in page (or a link with
?read_only=1) makes every new editor session read-only, confirmed by the server before anything runs: a default for your own sessions, not a restricted account. - 🛡️ The server's own sign-in, a short-lived token kept only in the tab, and a strict Content-Security-Policy: nothing loads from another origin.
The UI's source is in ui/, built and tested with the server in the same CI run.
📱 iPhone and iPad app
The whole server runs on the iPhone or iPad itself: the same hardcharger-server, Hardcharger
Engine 2.0 and its built-in extensions, built into the app. The app shows:
- 🖥️ Web UI: the server's own web UI (editor, results grid, schema browser, sessions, API page, uploads), signed in by the app; or a saved remote server's.
- ⌨️ Console: the
hardchargercommand-line client in the app, with its dot commands and formatting: Return runs a statement once it ends with;, ↑/↓ history, ⌘↩ on iPad. - 📲 Your files: import CSV, TSV, JSON and Parquet from Files, the share sheet or a drop on iPad; the database is in Files (On My iPhone › Hardcharger).
- 📡 Share on Local Network (off by default): a laptop on the same Wi-Fi opens the web UI over TLS at the address in the QR code, checking the certificate's fingerprint.
- 🌐 Other servers: saved in the Keychain, signed in with a password or single sign-on.
Get it on the App Store; it needs iOS 18 or later. To build it yourself, see
ios/.
🤖 Android app
The same server runs on Android phones and tablets (Android 9 or later), with its web UI, the
hardcharger console, files from the document picker and the share sheet, and passwords kept in
Android's secure storage. Get it on Google Play, or build it from
android/.
🚀 Performance
Measured on one machine (Apple M5 Max) against GizmoSQL 1.41 with the same data (details and method):
| Workload | Hardcharger | GizmoSQL 1.41 | |
|---|---|---|---|
| The 22 queries derived from TPC-H, SF10 | 832 ms | 1,201 ms | 1.44× faster |
| Fetch 10M rows (1.73 GB of Arrow) | 0.83 s | 1.32 s | 1.59× faster |
| 10 concurrent clients | 39.0 queries/s | 21.9 queries/s | 1.8× the throughput |
| 10 concurrent clients, p95 latency | 471 ms | 1,328 ms | 2.8× lower |
Over a real network: two AWS c8gn.8xlarge machines, TLS on both servers, median of five runs (details and method; the loads: partitioned uploads):
| Workload | Hardcharger | GizmoSQL 1.42 | |
|---|---|---|---|
| Fetch SF10 lineitem (60M rows, 10.5 GB of Arrow) | 0.97 s | 15.2 s | 15.7× faster |
| Fetch SF1 lineitem (6M rows) | 0.148 s | 1.74 s | 11.7× faster |
| Fetch 100M narrow rows | 0.45 s | 5.43 s | 12.0× faster |
| Fetch SF1 lineitem across regions (46 ms away) | 1.96 s | 12.26 s | 6.3× faster |
| Load SF10 lineitem (bulk ingest, 8 upload parts) | 3.00 s | 9.44 s | 3.1× faster |
| Load SF1 lineitem across regions (8 upload parts) | 2.91 s | 13.94 s | 4.8× faster |
The queries and data (lineitem at scale factor 1 or 10) come from DuckDB's tpch extension,
and the runs follow none of the TPC-H run rules or metrics. Derived from the TPC-H benchmark;
not an official TPC-H result and not comparable to published TPC-H results, as these results
do not comply with the TPC-H specification. TPC-H™ is a trademark of the Transaction Processing
Performance Council (TPC).
⚙️ How it's fast
Every result travels through an asynchronous pipeline: no stage waits for another unless a queue is full.
flowchart LR
D[(Hardcharger Engine 2.0<br/>parallel execution)] --> P[Produce<br/>Arrow batches,<br/>122,880 rows each]
P --> Z[Compress<br/>lz4_frame or zstd,<br/>worker pool, when asked for]
Z --> T[Encrypt and send<br/>TLS in 1 MiB writes,<br/>overlapped with the next]
T --> C1[connection 1]
T --> C2[connection 2]
T --> CN[connection N]
- 🔁 Overlapped stages. The engine keeps producing while earlier batches are being compressed and encrypted, and the socket never waits for the next batch to be built. With TLS on, one stream runs as fast as plain HTTP.
- 🧵 Parallel, selective compression.
lz4_frame(for fast links) orzstd(for slow ones) runs on a pool of threads, several batches at once, and the batches still leave in order. A buffer that a sample shows won't shrink enough is sent as it is, by reference, so compression costs only what it saves. The Go/Python driver picks the codec from the link's round trip by default. - 🔀 Partitioned results. A client can ask for a large result as several partitions and
read them over separate connections at once, past the limits of a single TCP stream and a
single core. The order is kept when the query asks for one. The server sizes the split by
the result: a few batches get a partition per two batches, a large result as many as the
client reads (the Go/Python driver asks for up to 32, JDBC and the
hardchargerCLI for 8;hardcharger.query.result_partitions,--result-partitionschange it). Small results still come as one stream. - 📦 Big batches. Results go out in 122,880-row batches, so per-batch overhead is negligible; small queries still answer in one round trip.
- 📥 Parallel ingest. Uploads are read in 1 MiB pieces and inserted on all of the engine's threads, in one transaction: a failed load leaves nothing behind.
- 📤 Partitioned uploads. The Go/Python driver sends a load in 16,384-row slices as up to
16 parts over separate connections at once (32 on a high-latency link; fewer for a small
load;
hardcharger.ingest.parts), inserted from all of them in parallel and committed as one: all or nothing.
Correctness is never traded for speed: a result is complete only when every partition has arrived with its end-of-stream marker, so a query that fails mid-stream can never look like a short, successful one.
⚡ Quick start
Install
The install page picks the right download for your computer: the desktop app for macOS and Windows, the server and CLI, Docker, Python, and the iPhone, iPad and Android apps.
For the server and CLI on macOS (Apple silicon) or Linux (x86-64, arm64), the one-line installer
puts hardcharger-server and the hardcharger client in ~/.hardcharger:
curl https://install.hardcharger.gizmodata.com | sh
HARDCHARGER_ADMIN_PASSWORD='change-me' ~/.hardcharger/bin/hardcharger-server --database my.duckdb
On Windows (PowerShell):
irm https://install.hardcharger.gizmodata.com/install.ps1 | iex
The installer keeps every version you install side by side and switches between them in seconds.
See hardcharger-install for choosing a version,
adding it to your PATH, listing and uninstalling.
Docker
docker run --rm -p 31337:31337 -p 31338:31338 \
-e HARDCHARGER_ADMIN_PASSWORD='change-me' \
ghcr.io/gizmodata/hardcharger:latest
Images are multi-architecture (linux/amd64, linux/arm64) and published to both
ghcr.io/gizmodata/hardcharger and docker.io/gizmodata/hardcharger. Port 31337 speaks
Chargewire; 31338 answers /health.
The :X.Y.Z-adbc and :latest-adbc variants on both registries include the same
server and CLI plus 15 native ADBC drivers: BigQuery, Databricks, Exasol, Flight SQL,
SQL Server, MySQL, PostgreSQL, Redshift, Snowflake, Trino, GizmoSQL, Oracle, Db2,
Quack and Hardcharger. From 2.13.4 the GizmoData drivers among them are Hardcharger 2.7.2,
Quack 1.1.0, Oracle 1.1.0, Db2 0.3.0 and GizmoSQL 2.0.18; Hardcharger's, Quack's, Oracle's
and Db2's options are named as the
ADBC driver style guide asks
(hardcharger.*, quack.*, oracle.*, db2.*; the older adbc.<driver>.* names still
work but print a deprecation warning). Both linux/amd64 and linux/arm64 are supported.
For example:
docker run --rm -p 31337:31337 -p 31338:31338 \
-e HARDCHARGER_ADMIN_PASSWORD='change-me' \
ghcr.io/gizmodata/hardcharger:latest-adbc
Driver manifests are installed system-wide in /etc/adbc/drivers; stable library
paths are /usr/local/lib/libadbc_driver_<name>.so. An ADBC driver manager in the
container can discover them by name (hardcharger, gizmosql, snowflake, etc.).
SNOWFLAKE_ADBC_DRIVER_PATH points at the bundled Snowflake library. Driver versions,
source-asset digests and notices are under /usr/share/doc/hardcharger-adbc/; dbc's
driver manifests and bundled license files are retained in /etc/adbc/drivers.
These variants use the same non-root user and server entrypoint as the base image.
See releasing for the separate driver-layer workflow.
Installed extensions (INSTALL) and persistent secrets live under the home directory
(~/.duckdb/), as DuckDB keeps them. Without a usable one (no HOME, or a container run
as a user the image has no account for, which gets HOME=/), the server uses the
account's home from the password database, else .duckdb/ in the database file's
directory, and says so at startup; mount a writable volume for the database (--database /data/my.duckdb) and they go there. Init SQL can set extension_directory and
secret_directory to anywhere else.
In v2.1.0+, non-iOS builds statically include DuckDB's standard core_functions,
parquet, json and icu extensions. Optional extensions—including httpfs, postgres,
ducklake, tpch and autocomplete—load at runtime and can be replaced independently
of the server. Automatic installation and loading of known extensions are enabled by
default, matching GizmoSQL; signature verification stays enabled. A first use may need
network access and a writable extension cache. For offline use, preinstall the needed
modules for the server's DuckDB version and platform. Administrators can select a custom
repository or disable automatic installation/loading through init SQL. See
Extensions. iOS keeps its extensions built in and dynamic loading off.
ghcr.io/gizmodata/hardcharger:main (and :sha-<commit>) is the development build: the
newest commit on main that passed every CI gate, built exactly as a release. Use
:latest or a version tag for anything else.
Python
pip install hardcharger
import hardcharger
with hardcharger.Server(password="change-me") as server:
print(server.uri) # hardcharger://127.0.0.1:<port>?tls=false
The hardcharger package is the server: it downloads hardcharger-server for your
platform on first use and runs it. The client is adbc-driver-hardcharger (below);
pip install "hardcharger[adbc]" installs both, and server.connect() then returns a
connection. See python/README.md.
Homebrew
On macOS 15+ (Apple silicon) and Linux (x86-64 and arm64):
brew install gizmodata/tap/hardcharger # hardcharger-server and the hardcharger CLI
brew install --cask gizmodata/tap/hardcharger-desktop # the desktop app (macOS)
HARDCHARGER_ADMIN_PASSWORD='change-me' hardcharger-server --database my.duckdb
The formula and the cask follow every release; brew upgrade brings the new one.
Binaries
These packages contain the server and command-line client. For the graphical app in
v2.1.0+, choose a Hardcharger-desktop-… artifact instead; see Desktop app.
Linux (x86-64 and arm64), macOS (Apple silicon) and Windows (x64 and arm64) builds are attached to every release:
tar -xzf hardcharger-macos-arm64.tar.gz
HARDCHARGER_ADMIN_PASSWORD='change-me' ./hardcharger-macos-arm64/bin/hardcharger-server --database my.duckdb
Linux x86-64 comes in two builds. hardcharger-linux-amd64.tar.gz is optimized for x86-64-v3
CPUs (AVX2: Intel Haswell, AMD Excavator or newer) and checks the CPU when it starts.
hardcharger-linux-amd64-baseline.tar.gz (from 2.13.2 on) runs on any x86-64 CPU, such as a
virtual machine whose CPU model hides AVX2 (QEMU's kvm64), but slower. Use it only where the
optimized build says the CPU is too old; changing the VM's CPU model (to host, or a model
with AVX2 such as QEMU's Haswell or Proxmox's x86-64-v3) is often the better fix. The one-line installer and the Python package pick the baseline build
on such a CPU by themselves. DuckDB's downloadable extensions need AVX2 as well, so the baseline
build has httpfs, ducklake, postgres_scanner and (from 2.13.3) sqlite_scanner built in (with
core_functions, parquet, json and icu) and, on a CPU without AVX2, refuses to install or load any other extension.
On Windows (PowerShell), unzip hardcharger-windows-amd64.zip or -arm64.zip, or run
Hardcharger-windows-amd64.msi / -arm64.msi, which installs under Program Files and
puts hardcharger-server.exe and the hardcharger.exe client on the PATH. Ctrl+C or
Ctrl+Break stops the server as SIGINT or SIGTERM does elsewhere.
Expand-Archive hardcharger-windows-amd64.zip -DestinationPath .
$env:HARDCHARGER_ADMIN_PASSWORD = 'change-me'
.\hardcharger-windows-amd64\bin\hardcharger-server.exe --database my.duckdb
🔌 Connect
Python (ADBC)
pip install adbc-driver-hardcharger
from adbc_driver_hardcharger import dbapi as hardcharger
with hardcharger.connect(uri="hardcharger://localhost?tls=false", username="hardcharger", password="change-me") as conn:
with conn.cursor() as cur:
cur.execute(operation="SELECT 42 AS answer, ? AS greeting", parameters=["hello"])
print(cur.fetch_arrow_table())
hardcharger://host is HTTPS on port 31337 (on 443 for a GizmoData Cloud host, *.gizmodata.com); ?tls=false is plain HTTP for local
development. hardcharger-adbc is a native
Go driver, on the Chargewire ADBC driver, with
query and session tags, hardcharger.* settings and browser sign-in. Its library loads into
any ADBC driver manager (C/C++, R, Rust, ...) as driver = "hardcharger", with the same
hardcharger:// URIs, and Go programs import it directly.
Java (JDBC)
Properties properties = new Properties();
properties.setProperty("user", "hardcharger");
properties.setProperty("password", "change-me");
properties.setProperty("useEncryption", "false"); // plain HTTP on localhost
try (Connection connection = DriverManager.getConnection("jdbc:hardcharger://localhost", properties);
ResultSet rows = connection.createStatement().executeQuery("SELECT 42 AS answer")) {
rows.next();
System.out.println(rows.getInt("answer"));
}
hardcharger-jdbc is a single jar for Java 17+,
with no gRPC, Netty or protobuf: jdbc:hardcharger://host[:port] (port 31337 by default) on
the Chargewire JDBC driver. Its README shows how
to add it to DBeaver and other BI tools.
JavaScript
import { connect } from "@gizmodata/hardcharger";
const conn = await connect({ url: "hardcharger://localhost?tls=false", username: "hardcharger", password: "change-me" });
const table = await conn.query("SELECT 42 AS answer, ? AS greeting", ["hello"]);
console.log(table.toArray().map((row) => row.toJSON()));
await conn.close();
@gizmodata/hardcharger, the Hardcharger™
JavaScript client, takes the same hardcharger:// URLs (port 31337 by default) and returns Arrow JS Tables or streams of record
batches, in Node, browsers (allow the page's origin with --cors-origins), Deno, Bun and
Cloudflare Workers. No native code, no gRPC. It is a thin layer on
@gizmodata/chargewire, the generic JavaScript client
for any Chargewire server, which it re-exports.
Plain HTTP
Chargewire is plain HTTP, so curl works. Rows come back as an Arrow IPC stream (here read
with pyarrow, pip install pyarrow):
TOKEN=$(curl -s localhost:31337/chargewire/v1/auth/token -H 'Content-Type: application/json' \
-d '{"grant_type": "password", "username": "hardcharger", "password": "change-me"}' | jq -r .access_token)
SESSION=$(curl -s localhost:31337/chargewire/v1/sessions -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -d '{}' | jq -r .session_id)
curl -s localhost:31337/chargewire/v1/sessions/$SESSION/statements -H "Authorization: Bearer $TOKEN" \
-H 'Content-Type: application/json' -H 'Accept: application/vnd.apache.arrow.stream' \
-d '{"sql": "SELECT 42 AS answer"}' |
python3 -c 'import sys, pyarrow as pa; print(pa.ipc.open_stream(source=sys.stdin.buffer).read_all().to_pylist())'
[{'answer': 42}]
Without that Accept header the answer is the statement's JSON document: its state, and
in result its Arrow schema and partitions, whose rows GET …/statements/{id}/result
returns (Chargewire §6.3, §6.4).
A session (and its statements, results, prepared statements and ingests) belongs to the token
that opened it: its user and that token's authority, meaning its role, scoped token,
catalog_access rules, tenant and identity-provider groups. Any other token gets
404 session_not_found on it, a readonly or scoped token of the same user included, so a
client that attaches to a session by its id runs with that session's own rights or not at
all. A new token with the same authority, such as signing in again with the same password,
reaches the session.
The server describes its API in OpenAPI 3.1 at GET /chargewire/v1/openapi.json (no sign-in
needed; discovery, GET /chargewire, lists it as capability openapi), for API tools and client
generators; the web UI's API page shows it:
curl -s localhost:31337/chargewire/v1/openapi.json | jq '{openapi, title: .info.title, paths: (.paths | length)}'
💻 Command-line client
hardcharger, the command-line client, ships beside hardcharger-server in every tarball
and in the image. It uses TLS by default. Connect to a server without TLS:
hardcharger --no-tls (the same as --tls=false or --tls false). Run it with no
statement for an interactive shell (it asks for the password, or reads
HARDCHARGER_PASSWORD):
$ hardcharger --host localhost --no-tls --username hardcharger
Password:
Hardcharger Client 0.3.0
Connected to localhost:31337
Type '.help' for help, '.quit' to exit.
my.main> CREATE OR REPLACE TABLE trips AS SELECT * FROM (VALUES (1, 'Boston', 12.5), (2, 'Denver', 30.0)) t(id, city, miles);
OK, 2 rows affected
my.main> SELECT city, miles FROM trips ORDER BY miles DESC;
┌─────────┬──────────────┐
│ city │ miles │
│ varchar │ decimal(3,1) │
├─────────┼──────────────┤
│ Denver │ 30.0 │
│ Boston │ 12.5 │
├─────────┴──────────────┤
│ 2 rows 2 columns │
└────────────────────────┘
my.main> .quit
History, tab completion, syntax highlighting, a pager for long results, dot commands
(.help, .tables, .mode, ...), and Ctrl-C cancels the running statement while the
shell goes on. A large result is read over up to 8 connections at once, in the same order;
--result-partitions N (or HARDCHARGER_RESULT_PARTITIONS) changes that, and 1 reads every
result over one connection.
Use --read-only (or HARDCHARGER_CLIENT_READ_ONLY=true) to require a read-only
session. The client asks for it when opening the session and requires the server to
confirm it before running SQL. A server that does not support the option refuses the
connection. The restriction also applies to replacement sessions after a disconnect;
open a new connection without the option to write again. The default is unchanged.
Read-only sessions restrict database changes; they do not sandbox administrator-installed
extensions. The server's separate HARDCHARGER_READ_ONLY setting opens its database file
read-only and does not configure the CLI.
A server that is starting again after a stop (a GizmoData Cloud cluster with auto-resume)
answers server_resuming while it starts, and the client waits for it and then goes on:
sign-in, session and statement are sent again as the server asks. While it waits it says so,
a countdown in a terminal (The server is resuming (…): retrying in 4 s, 0:21 so far. Ctrl-C stops waiting.) and a line per answer in a log; --quiet waits without a word, and Ctrl-C
stops waiting. --resume-timeout SECONDS (or HARDCHARGER_RESUME_TIMEOUT) sets how long it
waits, 600 by default; 0 reports the server's answer at once.
The client never starts a stopped server for nothing. When the server says it is stopped, it
connects without signing in (The server is stopped; it starts when you run the first statement.): the prompt, tab completion, .show and exiting send nothing, and the first
statement (or a dot command that reads the server, such as .tables) signs in, starts it and
runs. A wrong password is reported by that statement. Closing and Ctrl-C never sign in.
One statement with --command (-c), in any output mode (--csv, --json,
--markdown, --table, or .mode for the rest):
$ HARDCHARGER_PASSWORD='change-me' hardcharger --host localhost --no-tls --username hardcharger --csv \
--command "SELECT city, miles FROM trips ORDER BY id"
city,miles
Boston,12.5
Denver,30.0
A script from a heredoc, a pipe or --file; the exit status is 1 when a statement fails:
$ export HARDCHARGER_PASSWORD='change-me'
$ hardcharger --host localhost --no-tls --username hardcharger --quiet <<'SQL'
INSERT INTO trips VALUES (3, 'Austin', 8.5);
SELECT count(*) AS trips, sum(miles) AS miles FROM trips;
SQL
OK, 1 row affected
┌────────┬───────────────┐
│ trips │ miles │
│ bigint │ decimal(38,1) │
├────────┼───────────────┤
│ 3 │ 51.0 │
├────────┴───────────────┤
│ 1 row 2 columns │
└────────────────────────┘
The client uses TLS unless told otherwise, as the drivers do: --no-tls (or --tls=false,
--tls false, --tls off, or HARDCHARGER_TLS=false) is plain HTTP, for a local server like
this one started without --tls-cert; in the shell, .connect HOST PORT USERNAME --no-tls.
Against such a server without it, the client says so and connects nothing in plaintext. When
nothing answers, the error says why (Could not connect to http://localhost:9: connection refused. Is the server running on that port?), and a script run without any connection
options connects to the default (https://localhost:31337) at its first statement, so its
error is the connection's too. --tls-roots names a private CA, --mtls-cert and --mtls-key a client
certificate, and --auth-type external signs in through the server's browser sign-in. A URI
takes the place of --host, --port and --tls, with the Python driver's rules:
hardcharger://db.example.com is HTTPS to port 31337, and
hardcharger 'hardcharger://localhost?tls=false' --username hardcharger is plain HTTP. It is GizmoSQL's
gizmosql_client, on Chargewire:
docs/migrating-from-gizmosql.md
maps its options and lists what changed.
📦 Everything included
| 🦆 Hardcharger Engine 2.0 (GizmoData's fork of DuckDB 2.0), DuckLake and DuckDB's extensions | ✅ |
🖥️ Built-in web UI: SQL editor, results grid, schema browser, exports (--web-ui) |
✅ |
| 📱 iPhone and iPad app: the server on the device, its web UI and a SQL console | ✅ |
| ⚡ Chargewire: streamed and resumable results, bind parameters, prepared statements, bulk ingest, lz4_frame and zstd | ✅ |
| 🔐 TLS and mTLS, password and token sign-in, SSO via OIDC/JWKS, browser sign-in, authorized e-mail filters | ✅ |
| 👥 Role-based access control: users, roles, grants, ownership, system privileges | ✅ |
| 🛡️ Row policies, column masking, tenants, per-catalog access rules, Open Policy Agent | ✅ |
| 🧾 Tamper-evident audit log | ✅ |
| 🔭 Session and statement instrumentation, catalog logging, query profiles | ✅ |
📈 Prometheus /metrics and SQL metrics |
✅ |
🚦 Statement queue, timeouts, KILL SESSION, hardcharger_cancel(), graceful shutdown |
✅ |
🔍 hardcharger_active_connections(), hardcharger_server_info() (no instrumentation needed) |
✅ |
| 💳 License key | Not needed |
🆚 Why Hardcharger instead of Quack?
Quack is DuckDB Labs' own remote protocol: a
DuckDB extension that lets one DuckDB serve its databases (CALL quack_serve(...)) and another
ATTACH them over HTTP. It comes from DuckDB's extension repository and loads on first use,
works on every platform DuckDB ships extensions for (Windows included) and in the browser through
DuckDB-Wasm, lets one query join remote tables with local ones, and it is fast. If every client
is a DuckDB you trust, Quack is the easy choice.
Hardcharger™ is built for the other case: one server that many people and applications share, reached through drivers, with each user's access governed by the server. Both are young (Quack is an experimental extension, Hardcharger is 0.x); this is what each offers today:
| Hardcharger | Quack | |
|---|---|---|
ATTACH from DuckDB, joining remote tables with local ones |
✅ ¹ | ✅ |
Drivers that don't embed DuckDB: ADBC, JDBC, JavaScript, curl |
✅ | ❌ ² |
| Browsers | ✅ | ✅ ³ |
| Bind parameters sent to the server | ✅ | ❌ ⁴ |
| Bulk ingest, cancellation | ✅ | ✅ |
| TLS | ✅ | ✅ ⁵ |
| Users with passwords, tokens, SSO (OIDC/JWKS) | ✅ | partial ⁶ |
| Client certificates (mTLS), as identity too | ✅ | ❌ ⁷ |
| Roles and grants, checked against each statement's plan | ✅ | partial ⁸ |
| Row policies, column masking, tenants, Open Policy Agent | ✅ | ❌ |
| Tamper-evident audit log | ✅ | ❌ |
Instrumentation tables, Prometheus /metrics |
✅ | partial ⁹ |
Statement queue, statement timeouts, KILL SESSION |
✅ | partial ¹⁰ |
| Standalone server: binaries, Docker image, Windows MSI, YAML config | ✅ | ❌ ¹¹ |
| Built-in web UI | ✅ | ❌ |
| Written, versioned protocol spec with a conformance suite | ✅ | partial ¹² |
| License | Apache 2.0 | MIT |
- Through an ADBC extension for DuckDB and
hardcharger-adbc's driver library: Columnar's
adbcor Query.Farm'sadbc_scanner. Each attaches Hardcharger's tables, joins them with local ones and writes to them (CREATE TABLE … ASthroughadbc,INSERTthroughadbc_scanner).adbc_scannersends filters to the server with bind parameters;adbcsends only the columns, and DuckDB filters the rows. Neither is published for DuckDB 2.0 yet; both work on DuckDB 1.5.6, andadbcalso on DuckDB 2.0 built from its source (setup). - Quack's clients are DuckDB itself (the CLI, or a DuckDB library such as Python's or DuckDB-Wasm) with the extension loaded. Results travel in DuckDB's own format, not Arrow.
- Through DuckDB-Wasm. The Quack endpoint allows every origin (
Access-Control-Allow-Origin: *). - Quack sends SQL text only.
SELECT … WHERE i = ?on an attached table fails ("Values were not provided for the following parameters"), because the client sendsWHERE (i = $1)to the server without the value. It runs withSET disabled_optimizers = 'remote_pushdown', but then the client reads the whole table and filters it locally. - The server can use its own certificate or a self-signed one it generates; clients check it against a CA or pin its SHA-256 fingerprint.
- One shared token by default.
quack_authentication_functioncan point at your own SQL function (per-user tokens from a table, say), but the server keeps no user for the session; DuckDB's docs suggest writing an extension to record one. - The Quack server doesn't ask for a client certificate.
- A hook,
quack_authorization_function, gets each statement's text and can allow, refuse or rewrite it; by default it allows everything. DuckDB has no roles or grants. - Every Quack message can go to DuckDB's log (
CALL enable_logging('Quack')), andquack_active_connections()lists connections and their current SQL. We found no metrics endpoint. - A connection limit (
quack_server_max_connections) andquack_cancel(), which stops another connection's query. We found no statement queue and no server-side statement timeout. - Quack serves from inside any DuckDB process that runs
CALL quack_serve(...), and is set up with DuckDB settings in SQL. - Quack's protocol has a version that client and server agree on (version 3 in DuckDB 2.0), and its messages are defined in the extension's source. We found no separate specification or conformance suite, and DuckDB's docs say the protocol may still change.
Checked on running servers, with Quack e7a9be3f8c (the commit DuckDB 2.0 pins and its extension
repository serves) and Hardcharger; docs/hardcharger-vs-quack.md
shows how.
Where Hardcharger is faster
Measured on 2026-10-19 on AWS c8gn.8xlarge machines: server and client in one placement group
(LAN), or the client in another region, about 46 ms away (WAN). TLS on every server unless the
row says plaintext; median of five runs. Hardcharger at 2718a17e with the Chargewire ADBC
driver's default settings, Quack e7a9be3f8c attached from DuckDB 2.0, GizmoSQL 1.42 for
reference. The data is TPC-H-derived, as under Performance. These are the
shapes where Hardcharger came out ahead;
the full results
include the shapes where Quack is faster.
| Workload | Hardcharger | Quack | GizmoSQL 1.42 |
|---|---|---|---|
| Fetch SF1 lineitem (6M rows), WAN | 0.383 s | 1.508 s | 12.972 s |
| Load SF1 lineitem, WAN | 1.107 s | 1.801 s † | 13.802 s |
| Fetch SF1 lineitem, LAN | 0.126 s | 0.164 s | 1.484 s |
| Load SF1 lineitem, LAN | 0.538 s | 0.600 s † | 1.607 s |
| Fetch SF10 lineitem (60M rows), LAN, plaintext | 0.746 s | 0.962 s | 13.216 s |
† Quack with preserve_insertion_order = false. Hardcharger's driver loads in parallel parts,
which keep no row order either. Quack keeping insertion order, its default, took 2.684 s (WAN)
and 1.016 s (LAN).
⚙️ Configuration
Every option is a flag (--read-only), an environment variable (HARDCHARGER_READ_ONLY)
or a key in a YAML file passed with --config (read_only: true). Flags win over
environment variables, which win over the file. hardcharger-server --help lists them all.
# hardcharger.yaml
database: /data/analytics.duckdb
port: 31337
health_port: 31338
log_level: info
print_queries: true
init_sql_commands_file: /etc/hardcharger/init.sql
Startup banner and logging
Started with a text log (the default), the server opens it with a banner: the wordmark,
its version, the Chargewire and DuckDB versions, and where to go (the web UI's address when
--web-ui is on, else the Chargewire endpoint), then the documentation's:
__ __ __ __
/ / / /___ __________/ /____/ /_ ____ __________ ____ _____
/ /_/ / __ `/ ___/ __ / ___/ __ \/ __ `/ ___/ __ `/ _ \/ ___/
/ __ / /_/ / / / /_/ / /__/ / / / /_/ / / / /_/ / __/ /
/_/ /_/\__,_/_/ \__,_/\___/_/ /_/\__,_/_/ \__, /\___/_/
/____/
Hardcharger 2.0.0 | Chargewire 1.0.0 | DuckDB v2.0.0 | by GizmoData
UI http://localhost:31337/ui/ Docs docs.hardcharger.gizmodata.com
http://build-box:31337/ui/
It is plain ASCII within 80 columns, and never in a JSON log (--log-format json).
--no-banner (or --banner=false, HARDCHARGER_NO_BANNER=true, HARDCHARGER_BANNER=false,
banner: false in the YAML file) leaves it out. Every boolean option takes --no-NAME.
The addresses printed (in the banner, and as url= on the Hardcharger is ready and the web UI is on lines) are ones a browser can open: a server bound to every interface (0.0.0.0, the default,
or ::) prints http://localhost:<port> and http://<this machine's name>:<port>
(the second as also=), and with TLS the certificate's first DNS name (else the machine's
name), so the browser shows no certificate warning; listen= is the address bound.
--log-emoji auto|always|never (HARDCHARGER_LOG_EMOJI, log_emoji:) marks the level of a text
log line: ✅ for an outcome (ready, stopped), ⚠️ for a warning, ❌ for an error and 💥 for one
that stops the server (info and debug lines get none). auto, the default, marks lines only
when the log goes to a terminal and the locale is UTF-8 (LC_ALL, LC_CTYPE or LANG
names UTF-8; on Windows, the console's code page is UTF-8), so a file, a pipe, systemd's
journal, Docker and Kubernetes get none. JSON lines never have them. The log has no colour.
In SQL, SET SESSION name = value changes a DuckDB setting for your session only. A plain
SET name = value takes the setting's own default scope, which for about half of DuckDB's
settings (arrow_lossless_conversion among them) is GLOBAL: then only an administrator
may run it, and it changes the default of every session that has no value of its own.
Where sessions start
A new session starts in the database's catalog (memory, or the --database file's) and its
main schema. To start every session in a catalog the init SQL attaches, name it:
init_sql_commands: "ATTACH ':memory:' AS lake; CREATE SCHEMA lake.sales;"
default_catalog: lake # flag: --default-catalog lake
default_schema: sales # flag: --default-schema sales
- A client's own
catalog/schemasession options (ChargewirePOST /chargewire/v1/sessions) still win, andUSEstill moves a session anywhere. Aschemaoption alone is that schema in the default catalog.default_schemaalone is that schema in the database's catalog;default_catalogalone starts in that catalog's default schema (main). - With neither option set, an init SQL that ends in
USE xorUSE x.ysets where sessions start, as in GizmoSQL 1.x. The server reads where the init SQL's connection ended up (aUSEthat a later one undid doesn't count) and logs it:init SQL ended in USE lake.sales: sessions start there (set default_catalog to choose explicitly). Setting either option turns this off. - Both are checked once the init SQL has run: a catalog that isn't attached, a schema that
doesn't exist, or one of the server's own catalogs (
system,_hardcharger_system, the instrumentation and log catalogs) stops the server with exit code 1 and says why (default_catalog 'lake' is not attached: the attached catalogs are memory (attach it in the init SQL)). - Under access control a session moves there only if its user's own
USEcould: a user held tocatalog_accessrules that don't include it, or a tenant's user, starts where they would without it (logged at debug level), and a tenant with a default catalog starts its users there. A user outside any tenant sees every catalog's name, so they start in the default and their grants decide what they may read there. - The administrator sees the effective defaults in
hardcharger_server_info()(default_catalog,default_schema).
Behind a load balancer or proxy
Behind an HTTP reverse proxy (an ingress, an application load balancer) every connection
comes from the proxy, so by default the log, the audit records, hardcharger_active_connections()
and the per-address bound on browser sign-ins all see the proxy's address. List the proxies in
trusted_proxies (CIDRs or single addresses, IPv4 or IPv6) and Hardcharger takes the client's
address from their forwarding header instead:
trusted_proxies: [10.0.0.0/8, fd00::/8] # flag: --trusted-proxies 10.0.0.0/8,fd00::/8
Only a request whose TCP peer is in the list is read this way; anyone else's
X-Forwarded-FororForwardedheader is ignored. The default (empty) trusts no one.X-Forwarded-Foris read right to left, skipping each hop that is itself a trusted proxy; the first that isn't is the client (when every hop is trusted, the leftmost). Several instances of the header count as one list, in order. A request withoutX-Forwarded-Foruses RFC 7239Forwarded: for=the same way (quoted values,"[2001:db8::7]:4711"). When both are presentX-Forwarded-Forwins: the common proxies append to it and pass a client's ownForwardedheader on unchanged. Behind a proxy that sets onlyForwarded, have it dropX-Forwarded-For.A hop that is
unknown, obfuscated (for=_hidden), not an IP address, or otherwise malformed stops the search, and the proxy's own address is recorded.A forwarded address has no port:
203.0.113.9,[2001:db8::7](a direct client's is127.0.0.1:51234,[::1]:51234). Where it was forwarded, the proxy's ownaddress:portis kept beside it:proxy_addressinhardcharger_active_connections(),proxyin security log and audit lines.The forwarded address only describes the client. It is never used for authentication, and client certificates and certificate-bound tokens stay tied to the real connection. A client certificate refused by the TLS handshake is recorded with the TCP peer, since no request has arrived yet.
List only proxies that append to or overwrite these headers: one that passes a client's header through lets that client choose the address it is recorded under.
A proxy you can't trust by its address (one whose pods share an address range with other workloads, as a shared ingress in Kubernetes often does) can be trusted by a secret instead. Set
trusted_proxy_secret(at least 32 characters; preferHARDCHARGER_TRUSTED_PROXY_SECRET, as a flag is visible in process listings) and have the proxy add it to every request it forwards in theX-Hardcharger-Proxy-Secretheader, overwriting any value a client sent. A request carrying it is read exactly as one from a listed proxy, whatever its address; with both settings, either trust is enough. The header is compared in constant time and removed from every request before anything reads it (it is never logged, listed, echoed or passed on by the web UI's relay). A wrong or missing secret leaves the connection's own address as the client's, answers exactly as no header would, and a wrong one is logged once an hour without its value. Liketrusted_proxies, it is never used for authentication or TLS.# nginx in front of Hardcharger: replace the client's forwarding and secret headers proxy_set_header X-Forwarded-For $remote_addr; proxy_set_header X-Hardcharger-Proxy-Secret "<the server's trusted_proxy_secret>";The limits on failed sign-ins (below) count by this address too. Behind a proxy that isn't listed (or sending
trusted_proxy_secret), every client has the proxy's address, so a lock of one user from "one address" keeps that user out through the whole proxy: list your proxies, or, until you can, setlogin_lockout_threshold: 0(the delays stay on). A password sign-in that carries a forwarding header the server doesn't believe is logged once an hour, saying so.
Failed sign-ins
Every password check (the Chargewire password grant, the web UI's sign-in,
--verify-credentials, and the current password a user gives in ALTER USER ... REPLACE)
goes through the same limits, for the administrator and store users alike. A wrong current
password in a user's own change counts as a failed sign-in of that user from the session's
client address, and while that pair is locked the change is refused the same way, unchecked:
- One user from one client address: after
login_lockout_threshold(5) failed passwords withinlogin_failure_window_seconds(900) of each other, that pair is locked forlogin_lockout_seconds(900). While it is locked, every attempt of that user from that address is refused before the password is checked, the right one included. The same user from any other address is still checked, so nobody can lock an account, the administrator's included, out from everywhere. - One user from any address: after
login_user_backoff_after(5) failures, a growing delay between attempts:login_backoff_base_seconds(1), doubling with each further failure, at mostlogin_backoff_max_seconds(30). An attempt sooner is refused. Never a lock, and an address the user signed in from withinlogin_known_address_days(30) skips it. - One address trying any users: the same delay after
login_address_backoff_after(20) failures from that address. - Attempts at once count as failures until they end, for all three: no more than the
threshold's worth are checked before the first of them fails, and once a delay applies, one
attempt is checked at a time when it ends (the others are refused with
Retry-After: 1), however many arrive together. - The answer is
429 rate_limitedwithRetry-After(seconds) and the detailtoo many failed sign-in attempts: try again in N s, the same whether the user exists or not (an unknown name is counted like a known one). A successful sign-in resets its pair's count. An IPv6 client counts as its /64. - Every replica agrees: each failure, success and clear is a record in the access-control
store (not access-control data: writing one makes no replica reload), and replicas read each
other's about once a second, so a lock holds on whichever replica the next attempt reaches,
after a restart, and in
--verify-credentials. Checks by--verify-credentialsthat overlap take turns per user and per client address (a lock row in the store; a DuckDB store file is opened by one check at a time), each reading the records before it checks and writing its own before it answers; one that can't write its failure answers undecided (exit 2), as does one that waits longer thanrbac_store_timeout_secondsfor its turn ("reason": "store_busy"). Decisions are made from memory: a guess never waits on the store, and while the store doesn't answer each replica counts on its own (a warning says so). Without a store the counts are the process's own. - An administrator without
catalog_accessrules sees them and clears them:
SELECT scope, user_name, client_address, failures, locked, retry_after_seconds
FROM hardcharger_login_locks(); -- pairs, users and addresses with failures
SELECT hardcharger_clear_login_lock('joe', '203.0.113.9'); -- one pair (and joe's delay)
SELECT hardcharger_clear_login_lock('joe', NULL); -- joe from everywhere
SELECT hardcharger_clear_login_lock(NULL, '203.0.113.9'); -- one address
SELECT hardcharger_clear_login_lock(NULL, NULL); -- everything
- A lock, its end and a clear are security warnings in the log and records in the audit
chain (
status=locked|unlocked|cleared,user,client_address). Metrics:hardcharger_login_failures_total,hardcharger_login_throttled_total{reason="locked"| "user_backoff"|"address_backoff"},hardcharger_login_locks_totalandhardcharger_login_locks_active.hardcharger_users()shows each user'slast_sign_in_atandfailed_sign_insto the administrator, and a user its own. - Setting
login_lockout_thresholdto 0 turns pair locks off;login_address_backoff_after0 turns the per-address delay off (with both 0, only the per-user delay is left: for servers behind a proxy whose clients all share its address untiltrusted_proxy_secretortrusted_proxiesis set);login_backoff_max_seconds0 turns the delays off.
DuckDB files and DuckLake metadata
An existing plain DuckDB file keeps its storage format: the --database file and ordinary
files you ATTACH. --storage-version (storage_version) selects the format for a new
server database or a new plain attached database; unset, these use DuckDB 2.0's format.
v2.1.0+ removes Hardcharger's DuckLake metadata storage-version patch. DuckLake now
follows upstream behavior: its DuckDB metadata database defaults to the latest storage
format, including when attaching an existing metadata file. Writes/checkpoints can upgrade
it so an older DuckDB cannot reopen it. --storage-version does not override DuckLake's
metadata choice. Back up metadata before using it with a newer server.
Hardcharger no longer guarantees that older DuckDB clients can reopen DuckLake metadata
after writes by a newer server. Use the compatibility and migration controls supported by
your chosen upstream DuckLake version. DuckLake's catalog format and its
AUTOMATIC_MIGRATION option are separate from the metadata database's storage format.
PostgreSQL metadata has no DuckDB file storage version. See Extensions.
Open files. A query over a DuckLake table holds many of its data files open at once, so
a table with thousands of partition files needs more than the 1024 open files that
containers and services usually start with. The server raises its soft limit to the hard
limit at startup (v2.1.1+) and warns in its log when the hard limit is below 8192. Raise
that with ulimit -Hn, docker run --ulimit nofile=1048576:1048576, Compose's
ulimits: nofile:, or systemd's LimitNOFILE=.
Prepared statements (v2.14.1+). A prepared statement that writes to a DuckLake catalog is
bound and planned again each time it runs outside the transaction that prepared it, so it always
uses the catalog as that transaction sees it. Its unqualified names are resolved again at each run:
after USE <catalog>.<schema> within the same catalog, an unqualified table name means that
schema's table. A statement whose names would now resolve in another catalog (after USE of
another database) is refused with "Prepare the statement again"; prepare it again, or name the
catalog in the statement. This applies to the administrator's sessions; every other session
(users of the access-control store, tokens with catalog_access rules) already plans and checks
every run of a prepared statement against its grants or rules, is not refused, and follows USE
as before.
Statements prepared and run inside one explicit transaction keep their plan, and statements on
other catalogs are unchanged.
Logs
The server logs to stderr (log_file for a file), at log_level (info by default), as
text or, with log_format: json, one JSON object per line. Statements are logged as they
start and end with print_queries (on by default), at query_log_level. Whatever those
say, a statement stopped by a cancel gets one info line, statement cancelled, with its
session_id, statement_id (the q_… id), user, reason and duration (seconds, its
wait in the statement queue included):
{"time":"2026-10-20T14:31:39.702Z","level":"info","message":"statement cancelled","session_id":"s_…","statement_id":"q_…","user":"joe","reason":"timeout","duration":"1.003"}
reason is Chargewire's cancel_reason: client (the client's cancel, or it closed the
connection of a streamed result), timeout (Chargewire-Statement-Timeout or
query_timeout_seconds), killed (KILL SESSION), cancelled (hardcharger_cancel()),
session_closed (the session was deleted) or server_shutdown. A statement that
ends on its own, or fails, gets none.
What the statement log masks
Statement text and error text are kept in several places: the log's statement, prepare,
Client SQL command execution succeeded and statement failed lines (at any level),
_hardcharger_instr.sql_statements (sql_text, prepare_error) and sql_executions
(error_message), the catalog log, hardcharger_active_connections() and
hardcharger_live_queries(), the access-control audit record (sql, error) and the line a
failed init SQL statement stops the server with. Before text reaches any of them, the credential
values in it are replaced by ***. The client that sent a statement still gets its own error
as DuckDB gave it.
A masker recognises forms; it does not understand statements. What is masked is the list
below, and nothing else: a credential written in any other form is logged as written. Each
form has a test (server/unit/redaction_test.cc, server/tests/test_log_masking_forms.py).
A statement is read as DuckDB's own tokenizer reads it, so a value is found where DuckDB finds
it, whatever comments, quoting or Unicode white space surround it. In a name, case is ignored
and - reads as _. Characters that are not ASCII and control characters are left out of a
name before it is compared, so a name pasted with an invisible character on it
(ENCRYPTION_KEY<U+180E>'…', which DuckDB refuses as an unknown option) still has its value
masked. Two lists of names are used:
- A credential name is one that ends in
password,passwd,pwd,passphrase,secret,token,access_key,secret_key,accountkey,account_key,apikey,api_key,private_key,encryption_key,subscription_key,sig,signature,auth,authorization,credential,credentials,cookie,jwtorbearer, or ispassorpw, or ends in_passor_pw(s3_secret_access_key,X-API-Key,Proxy-Authorization,bearer_token). It masks a setting's, an option's and a named argument's value, and every key in a connection string, a URL or other text. - Some of those words name ordinary data as well (
authfor an authentication method,pwdfor a directory,first_pass), so a column, a struct or MAP key and a name/value pair mask their value only under a name only a credential has: one that ends inpassword,passwd,passphrase,secret,apikeyoraccountkey, or that is (or ends in_and)secret_key,access_key,api_key,private_key,encryption_key,account_key,subscription_key,access_token,refresh_token,auth_token,bearer_token,api_token,id_token,session_tokenorsecurity_token. A column named exactlytokenalso masks its values. A key may also be an HTTP header that carries a credential ({'Authorization': …},MAP {'Cookie': …}).
Statements replaced whole, by their own first words (not by words in a comment or a string). In a request of several statements only that statement is replaced:
| Statement | Logged as |
|---|---|
CREATE [OR REPLACE] [PERSISTENT | TEMPORARY | TEMP] SECRET … |
[REDACTED: secret DDL] |
CREATE USER … / ALTER USER … with a literal or a credential name in it (PASSWORD '…') |
[REDACTED: user DDL] |
SET / PRAGMA [GLOBAL | SESSION | LOCAL] of a setting whose name has password, passwd, pwd, passphrase, secret, token, access_key, accountkey, account_key, apikey, api_key, private_key, encryption_key, signature, credential, bearer, authorization, cookie or jwt in it, or is a credential name, with = or TO (not SET VARIABLE, whose value is masked instead) |
[REDACTED: a credential setting] |
The value given to a name in any other statement. The whole value is replaced, whether it
is one literal or an expression ('a' || 'b', upper('…'), a subquery):
| Form | Names | Example |
|---|---|---|
| a named argument | credential names | f(token => v), f(token := v), f(token = v) |
| an option list | credential names | ATTACH '…' (ENCRYPTION_KEY 'v'), (ENCRYPTION_KEY (SELECT …)), (TOKEN v) with a bare word in an ATTACH; (PASSWORD 'v'), (PASSWORD upper('…')) in COPY and EXPORT DATABASE |
| a struct, MAP or JSON key | only a credential's, or a credential header | {password: v}, {'password': v}, MAP {'api_key': v}, {'Authorization': v} |
SET VARIABLE |
only a credential's | SET VARIABLE my_api_key = v |
| a comparison with a literal or an expression | only a credential's | password = v, ==, <>, !=, <, >, <=, >=, ~, !~, IN (…), [NOT] LIKE, ILIKE, GLOB, REGEXP, SIMILAR TO, BETWEEN … AND …, IS [NOT] DISTINCT FROM; also v = password and upper('…') = password (a literal, a call or a bracket on the left of =, <> or !=), lower(password) = v, trim(lower(password)) = v, password::TEXT = v, CAST(password AS TEXT) = v |
an UPDATE's assignment |
only a credential's | SET password = v |
an INSERT with a column list and VALUES rows |
only a credential's | INSERT INTO users (name, password) VALUES ('eve', v), …, also behind WITH, EXPLAIN or PREPARE … AS, and MERGE's WHEN NOT MATCHED THEN INSERT (…) VALUES (…) |
| a name and its value as two literals | only a credential's, or a credential header | json_object('api_key', 'v'), VALUES ('api_key', 'v'), map_from_entries([('Authorization', 'v')]), MAP(['Authorization'], ['v']); not in an IN (…) list, and not when the second literal is a credential name too (note IN ('password', 'token') is a list of words) |
| DuckDB's key function | PRAGMA add_parquet_key('name', 'v') (all arguments) |
|
| a password clause of another engine | IDENTIFIED BY 'v', IDENTIFIED WITH plugin BY 'v' / AS 'v' |
|
an Authorization value on its own |
a literal that is Bearer <token> or Basic <base64> |
A comparison with what holds no value (no literal, number or placeholder: another column,
a.access_token = b.access_token; a function of columns, lower(a.password) = lower(b.password); a subquery of them, api_key IN (SELECT api_key FROM revoked WHERE id = 3), where a number belongs to the subquery's own clauses), IS NULL, and a name with no value
(SELECT token FROM t, CREATE TABLE t (password VARCHAR)) hide nothing. A bind
placeholder (token => ?, $1, $name) is kept as written; the value bound to it is a
credential for the statement's errors (below).
Inside a string literal, a quoted name and a comment, and in error text:
| Form | What is masked |
|---|---|
a URL's userinfo, scheme://user:password@host |
the password, up to the URL's last @ (so one with @, :, /, quotes, brackets or a space in it goes whole); for http and https the user as well: https://TOKEN@host, https://TOKEN:x-oauth-basic@host. The URL runs to the next white space, or where it is quoted to the quote that closes it (one followed by white space or the text's end, directly or after : , . ; ) ] }); past white space (a password with a space in it) only in a literal that is the URL alone, inside a quote up to that quote's close, or else on the same line before any =, quote or other URL. An authority that is host:port (digits after the colon, then the URL's end, /, ?, # or a closing quote or bracket) has no userinfo: a later @ is the path's or the query's (http://h:8080/users/[email protected] is logged as written, and so is postgresql://u:1234/x@h, which libpq reads as host u, port 1234) |
| a URL's query parameters | the value of a parameter with a credential name (?auth=, ?api-key=, ?jwt=, ?access_token=, ?sig=, ?X-Goog-Signature=), of any X-Amz-… parameter, and of key, sessionid and session_id, up to the next & or # |
key=value with a credential name as the key |
libpq's keyword form (to the next white space, a backslash taking the next character; or '…'), also behind postgres: and ducklake:postgres:; "…" (MySQL); {…} (ODBC); a ;-separated list, to the next ; (ADO, Azure's AccountKey=…;) |
key => value, key := value, 'key': 'value', "key": "value" |
the value (JSON and struct text) |
| a header line | Authorization:, Proxy-Authorization:, Cookie:, Set-Cookie:, X-API-Key:, X-Auth-Token:, X-Amz-Security-Token:, to the end of the line |
| SQL given as text | a literal or a comment that holds a statement (postgres_execute('pg', 'ALTER ROLE app PASSWORD ''v'''), query('…'), a statement commented out) is read again with every rule above, four levels deep (text that begins as a statement does, SELECT, ALTER, INSERT and the like, is read as SQL only, so a literal inside it is read with its quotes resolved at each level); one DuckDB cannot tokenize, or with a backslash before a quote, that names a credential before a quote is masked whole |
| a value built from pieces | when a credential's value runs to the end of a literal that is joined to something ('host=h password=' || x), the rest of the concatenation; when the literal is a function's argument and the value is a placeholder (format('…?token={}', x), %s), the function's other arguments |
An error over 64 KiB, or one whose credential replacements exceed the redaction work budget, is logged as [REDACTED: error details omitted].
Text DuckDB cannot tokenize (an unterminated string literal, quoted identifier, /*
comment or dollar-quoted string, or invalid UTF-8) cannot be searched for values and never
runs: all of it is replaced by [REDACTED: a statement that could not be read: <which>], and
its error by [REDACTED: error of a statement that could not be read: <which>].
Errors. An error is logged and stored without DuckDB's excerpt of the statement
(LINE 1: …), with every value the statement's masking hid replaced wherever the error quotes
it (in any letter case, as the literal's value with its quotes and escapes resolved, joined
when it was written as 'a' || 'b', and each piece of a password that a connection-string
parser split at its punctuation; a value of letters only, which the error's own wording may
use, only where it is a word of its own and written as it was hidden, so password = 'error'
leaves Binder Error: as it is; in a request of several statements, each statement's error
with the values that statement hid), with the values bound to the statement's masked
placeholders replaced the same way (JSON parameters and Arrow parameter rows), and then with
the forms of the table above masked in the error's own text (DuckDB quotes an ATTACH's
connection string in its errors). The reason an error gives is kept. Two errors are replaced
whole, because what they might quote cannot be listed: that of a statement whose credential
value is computed (token => upper('…')), by
[REDACTED: error of a statement that computes a credential value], and that of an execution
that binds more than 1,000 credential values.
Query profiles (capture_query_profile) hold a statement's text and constants: none is
captured for a statement in which a value was masked. An ordinary comment, a join on a
credential-named column and an ordinary escaped literal keep their profile.
A failed init SQL statement stops the server with one line that says why and which:
init SQL failed: <the error, redacted as above> (init SQL statement 2 of 5: <the statement as the log shows it>).
Among what is not masked: an argument given by position (hmac('key', msg)), a value
under a name that is not a credential name (key => …, tokens => […], client_key_pem), a
column, key or pair under an ambiguous credential name (page_token = 'cat',
auth = 'basic', {'token': …}, INSERT INTO t (page_token) VALUES …), a credential in a
URL's path, a URL query's code, an INSERT without a column list or from a SELECT, and a
value an error quotes after the statement transformed it (a substring, a hash, an encoding).
Statements refused before DuckDB parses them
The server checks every text DuckDB is asked to parse, before DuckDB's parser sees it, in one
pass over the text with DuckDB's own tokenizer (so a bracket in a string, a quoted name or a
comment is not one). The check sits in DuckDB's parser hook (allow_parser_override_extension
is fallback on this server), so it sees text however it reaches the parser: a statement, a
request of several, a prepare, the init SQL, the SQL query() and query_table() are given
(written out or computed, query('SELECT ' || repeat('(', 8000))), json_serialize_sql()
and json_serialize_plan() (on any thread, DuckDB's worker threads included), and IMPORT
DATABASE's load.sql. It refuses:
- Parentheses opened and never closed. DuckDB 2.0's parser takes time quadratic in their
number to report the syntax error (8,000 of them: about 20 seconds; 500,000: hours), on one
core, and neither the statement timeout nor a cancel interrupts a parse:
Parser Error: syntax error: 8000 opening parentheses are never closed (the first "(" at position 8), at once. The position is in the text that has them (the statement of a request, the SQL given toquery()). - Brackets nested deeper than
max_sql_nesting((,[and{together):Parser Error: the statement's brackets nest 3000 deep, and this server takes 1000 (its max_sql_nesting option). DuckDB's parser recurses once per level before its own limit is checked: 8,000 nested subqueries stopped the server whatever that limit was. - More than four times
max_sql_nestingtables in oneFROMclause, joined or listed with commas (the parser recurses once per table as well). - A dotted name of more parts than
max_sql_nesting(a.b.c…): DuckDB's binder takes time quadratic in their number (20,000 parts: 45 seconds), and no timeout interrupts it. - More tables in one
FROMclause thanmax_joined_tables(64 by default), joined or listed with commas, and more than eight times that in all a statement'sFROMclauses together:Parser Error: a FROM clause of the statement joins 65 tables, and this server takes 64 in one (its max_joined_tables option): …. DuckDB's time to choose a join order grows steeply with the tables one clause joins, and neither the statement timeout nor a cancel interrupts it. Measured on a busy laptop (planning only): a chain of 64 tables 0.08 s, 128 tables 0.7 s, 256 tables 16 s; a join graph with cycles, 64 tables 0.4 s, 96 tables 1.9 s, 128 tables 7 s, 192 tables 82 s. A derived table or a CTE is one table of the clause that joins it (DuckDB plans its own join on its own: 600 tables in derived tables of ten take about 2.5 s), and a request's statements are counted one by one.
Anything else goes on to DuckDB's parser unchanged: its errors, their positions and EXPLAIN
are what DuckDB says. No session can switch the check off: a SET, RESET or PRAGMA of
allow_parser_override_extension, in any scope, is refused, for an administrator too. An init
SQL that changes it does not outlast startup.
max_sql_nesting (--max-sql-nesting, HARDCHARGER_MAX_SQL_NESTING) is the deepest nesting a
statement may have. DuckDB recurses once per level of a statement's nesting (brackets,
subqueries, chained operators such as a || b || c, joins) on the thread that parses and binds
it, and past what that thread's stack takes the server does not answer with an error: it stops.
The server sets DuckDB's own limit, max_expression_depth, to max_sql_nesting at startup
(after the init SQL), and no session can set it higher, for an administrator too: SET,
PRAGMA or RESET GLOBAL max_expression_depth to anything above the limit is refused (a
session may lower its own). DuckDB then refuses deeper nesting wherever it parses or binds, with
its Max expression depth limit of N exceeded.
The threads that run statements have an 8 MB stack on every platform (the Chargewire SDK
starts them so; a thread gets 512 KB by default on macOS and 1 MB on Windows), and so does the
thread that runs the init SQL. Left at 0, the default, max_sql_nesting is what that stack
takes at 4 KB a level, at most DuckDB's own default: 1000 everywhere. DuckDB counts some
constructs as several levels (a nested scalar subquery as about four). Set it higher only with
stacks to match: DuckDB's own worker threads, which run parts of queries (and parse the SQL
json_serialize_sql() is given row by row), keep the platform's default stack, and were
measured to take twice the default limit on macOS.
max_joined_tables (--max-joined-tables, HARDCHARGER_MAX_JOINED_TABLES, default 64,
0 for no limit) is the most tables one FROM clause may join; all of a statement's FROM
clauses together may join eight times as many. It bounds what DuckDB's join-order search, which
nothing interrupts, is given: raise it only knowing that each table past a hundred or so in one
clause can add seconds to minutes of planning on one core.
DuckDB's autocomplete functions
sql_auto_complete(), sql_tokenize(), check_peg_parser() and duckdb_format_sql() (DuckDB's
autocomplete extension) run DuckDB's SQL matcher, or its formatter, on their argument directly,
not through the parser and its check. sql_auto_complete()'s argument is unfinished SQL by
design, and the matcher's time grows exponentially with the brackets the argument leaves open
(SELECT 1 + ( six times: 1.7 seconds; eight times: over 15; sql_tokenize() ran over two
minutes on 2,000 open parentheses). duckdb_format_sql()'s time and result grow with the square
of its argument (4,000 nested subqueries: 3 seconds and 64 MB). The work is done while DuckDB
binds the call, so neither the statement timeout nor a cancel interrupts it: they take effect
when it returns. No limit on the argument keeps every shape fast, so these functions are off
unless enable_sql_auto_complete is on (--enable-sql-auto-complete,
HARDCHARGER_ENABLE_SQL_AUTO_COMPLETE), and then for administrators only:
- Off (the default), the server refuses
LOAD autocompleteand calls to its functions in sessions and init SQL, including on builds that link it in (iOS, Android, and sanitizer builds). Calls fail with403 permission_deniedwithout automatically installing the extension. - On, the server loads the extension at startup (installing it if
autoinstall_known_extensionsallows), and no later load is allowed. The functions answer administrators; to anyone else, wherever the call is (a statement, a view,query()), they answersql_auto_complete() is for administrators on this server: ….
Nothing in Hardcharger's server, command-line client or web UI calls them.
Credential and system files
With block_sensitive_paths on (the default), no statement can open, list, write, move or
delete the credential and system files on the server host, whoever runs it, the
administrator included:
- the home directory's
.ssh,.aws,.azure,.config/gcloud,.kube,.docker/config.json,.netrc,.pgpass,.git-credentialsand.gnupg, and DuckDB's secret directory (~/.duckdb/stored_secrets, or wherever the init SQL moved it); - the server's own TLS key and certificate, client CA, init SQL file and config file;
/etc/passwd,/etc/shadow,/etc/gshadow,/etc/master.passwd,/etc/sudoersand/etc/sudoers.d,/procand/dev/fd(except/proc/self/cgroup, which DuckDB reads to size its memory limit), and/var/run/secretsand/run/secrets(container and Kubernetes secrets);- on Windows, the account database and registry hives, DPAPI keys, Credential Manager and
the vaults, installer answer files, and the device namespace (
\\.\,\\?\); - and any path listed in
sensitive_paths(comma-separated).
The check sits in DuckDB's file system, so it sees the path DuckDB is about to use, however
the statement arrived at it: a literal, a concatenation, a variable, a prepared statement's
parameter, query('…'), a macro or view, file_search_path, ~, .., a symlink, a second
hard link, or a different letter case where the file system ignores case. A refusal reads
Permission denied: Hardcharger blocked access to '<path>' (<what it is>). A glob that
reaches into a protected directory from above (/home/*/.ssh/*, **/id_rsa) lists its
other matches only; one whose fixed part is protected (~/.ssh/*) is refused. SQL text is
not inspected for paths, so string literals such as '{"a": 1}', '.*' or
'~/.ssh/id_rsa' used as values work as anywhere else. SET secret_directory is refused
after startup, because DuckDB's secret manager reads that directory outside its file system.
Two limits:
- The server's startup is not checked: its own attaches and the operator's init SQL
(
init_sql_commands,init_sql_commands_file) run before the guard switches on, so init SQL may read a mounted credential, for example to create a secret from it. (GizmoSQL 1.x checks init SQL too.) - Extensions that do their own file I/O don't go through DuckDB's file system.
sqlite_scanneris closed separately, at plan time (see the access-control section).postgres_scanneris not: PostgreSQL's client library reads~/.pgpass, and files named bypassfile=,sslkey=and similar connection options, itself. So a statement that mayATTACHa PostgreSQL database (the administrator, or a role grantedMANAGE CATALOGS) can make the server connect with a password or client key it finds there. Keep PostgreSQL credentials off a server host whose users you wouldn't trust with them.
🔍 Introspection
Three SQL functions show what the server is doing, with no instrumentation or metrics
turned on. hardcharger_active_connections() has a row per open session: who (user, role,
tenant, how they signed in), from where (the latest request's address, behind a trusted
proxy the forwarded one with the proxy's in proxy_address, its User-Agent, TLS version and
client certificate), what it runs (state: idle, queued, running, streaming,
idle_in_transaction or idle_in_transaction_aborted; the statement, redacted as the log
redacts it; since when), and its open result streams, partitions, uploads and retained
results:
$ hardcharger --command "SELECT session_id, username, client_info, state, statement FROM hardcharger_active_connections() WHERE NOT is_current"
┌────────────────────────────────────┬─────────────┬────────────────────┬─────────┬──────────────────────────────────────────────────────────┐
│ session_id │ username │ client_info │ state │ statement │
│ varchar │ varchar │ varchar │ varchar │ varchar │
├────────────────────────────────────┼─────────────┼────────────────────┼─────────┼──────────────────────────────────────────────────────────┤
│ s_dx7wohhsyptjqkqgukmrlp3ow5t2gtsa │ hardcharger │ hardcharger-client │ running │ SELECT count(*) FROM range(10000000000) a, range(1000) b │
├────────────────────────────────────┴─────────────┴────────────────────┴─────────┴──────────────────────────────────────────────────────────┤
│ 1 row 5 columns │
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
hardcharger_cancel(session_id) stops what a session runs and keeps the session: its
statement ends cancelled (cancel_reason cancelled), result streams are cut off, uploads
in flight are aborted, and its next statement runs as usual. It returns whether there was
anything to stop. KILL SESSION does the same, then ends the session (killed):
$ hardcharger --command "SELECT hardcharger_cancel(session_id) AS cancelled FROM hardcharger_active_connections() WHERE state = 'running' AND NOT is_current"
┌───────────┐
│ cancelled │
│ boolean │
├───────────┤
│ true │
├───────────┤
│ 1 row │
└───────────┘
A statement's statement_id is its Chargewire id (q_...), the one its client got in
Chargewire-Statement-Id and error responses. With instrumentation on (--enable-instrumentation),
the same id finds it in the history once it is over: sql_executions.execution_id, and
sql_statements.statement_id for a submitted statement (a prepared statement's row is its
p_..., with an execution per request under each request's q_...; the statements of a
script sent in one request are q_....1, q_....2, ...). The query log's statement_id
and prepared_id fields carry the same ids. Here the statement above, cancelled:
$ hardcharger --command "SELECT statement_id, state, statement FROM hardcharger_active_connections() WHERE NOT is_current"
┌────────────────────────────────────┬─────────┬──────────────────────────────────────────────────────────┐
│ statement_id │ state │ statement │
│ varchar │ varchar │ varchar │
├────────────────────────────────────┼─────────┼──────────────────────────────────────────────────────────┤
│ q_n5zugypkhvoe7e6poydlvnsqaqnfzk6d │ running │ SELECT count(*) FROM range(10000000000) a, range(1000) b │
├────────────────────────────────────┴─────────┴──────────────────────────────────────────────────────────┤
│ 1 row 3 columns │
└─────────────────────────────────────────────────────────────────────────────────────────────────────────┘
$ hardcharger --command "SELECT execution_id, status, cancel_reason, sql_text FROM _hardcharger_instr.execution_details WHERE execution_id = 'q_n5zugypkhvoe7e6poydlvnsqaqnfzk6d'"
┌────────────────────────────────────┬───────────┬───────────────┬──────────────────────────────────────────────────────────┐
│ execution_id │ status │ cancel_reason │ sql_text │
│ varchar │ varchar │ varchar │ varchar │
├────────────────────────────────────┼───────────┼───────────────┼──────────────────────────────────────────────────────────┤
│ q_n5zugypkhvoe7e6poydlvnsqaqnfzk6d │ cancelled │ cancelled │ SELECT count(*) FROM range(10000000000) a, range(1000) b │
├────────────────────────────────────┴───────────┴───────────────┴──────────────────────────────────────────────────────────┤
│ 1 row 4 columns │
└───────────────────────────────────────────────────────────────────────────────────────────────────────────────────────────┘
hardcharger_server_info() is one row: the versions, the instance and cluster ids, the
start time and the uptime for everyone; the host (hostname, OS, CPU model and count,
memory), the listen addresses and ports, TLS and mutual TLS, the server certificate's
SHA-256 fingerprint, the web UI, the access-control store and the session count for an
administrator without catalog_access rules (NULL for everyone else):
$ hardcharger --command "SELECT hardcharger_version, CAST(uptime AS VARCHAR) AS uptime, cpu_model, cpu_count, memory_total_bytes, session_count FROM hardcharger_server_info()"
┌─────────────────────┬─────────────────┬──────────────┬───────────┬────────────────────┬───────────────┐
│ hardcharger_version │ uptime │ cpu_model │ cpu_count │ memory_total_bytes │ session_count │
│ varchar │ varchar │ varchar │ integer │ bigint │ integer │
├─────────────────────┼─────────────────┼──────────────┼───────────┼────────────────────┼───────────────┤
│ 0.3.0 │ 00:00:01.097479 │ Apple M5 Max │ 18 │ 68719476736 │ 2 │
├─────────────────────┴─────────────────┴──────────────┴───────────┴────────────────────┴───────────────┤
│ 1 row 6 columns │
└───────────────────────────────────────────────────────────────────────────────────────────────────────┘
Who sees and cancels what: an administrator without catalog_access rules, every session;
anyone else, a restricted administrator included, the sessions of their own principal (the
same user and tenant), and hardcharger_sessions() follows the same rule. Retained
(resumable) results are kept for result_retention_seconds (default 3600) after their
statement ends; the statement document's expires_at says until when.
max_ingest_message_bytes defaults to 67108864 (64 MiB). Each Arrow IPC message
must fit on the wire, including framing and metadata, and its aggregate expanded buffers
must fit before decompression. This applies to ordinary ingest, partitioned-ingest parts,
dictionaries and Arrow prepared parameters. Oversized input returns HTTP 413
payload_too_large before the requested allocation. Split larger uploads into smaller
record batches: the limit is per message, not per upload. Configure this positive startup
setting with YAML, --max-ingest-message-bytes or HARDCHARGER_MAX_INGEST_MESSAGE_BYTES;
it is visible in Server Configuration and takes effect after restarting the server.
A session is evicted within 5 s (the server's sweep interval) after session_idle_timeout
seconds (default 900; 0 never evicts) without a request on it, unless a request is waiting
on one of its statements (Prefer: wait), one of its ingests is in progress, one of its
results is being read (a slow download keeps it to the end of the stream), or it holds a
retained result that hasn't expired. The timeout counts from the end of the session's last
response, so a client that polls with Prefer: wait longer than the timeout keeps its
session. A request queued behind a statement that is still running (metadata, a commit, a
prepare) does not keep the session while it waits for its turn. A statement that is still running with no request
waiting on it does not keep the session: a client that is there polls its statement and is
heard from within the timeout, while one that died mid-write (a pod killed at its deadline)
must not keep the session, and the write's open transaction, alive for the hours the write
runs. The eviction cancels the statement (cancel_reason session_closed) and rolls its
transaction back. With session_idle_timeout 0 a dead client's session and transaction live
until the server restarts (or KILL SESSION). The retained-result rule follows Chargewire
§5.7, so that a result kept for re-reading stays readable until its expires_at: a session
whose statement ran in JSON mode (a retained result) lives up to result_retention_seconds
after the statement ended, then goes at the next sweep. To bound a session's life by the
idle timeout alone, set result_retention_seconds no higher than session_idle_timeout,
or have clients delete statements (or the session) they are done with. An evicted session
answers session_not_found.
idle_in_transaction_session_timeout (default 0, off), as PostgreSQL has it, ends a session
that holds a transaction open (BEGIN, or autocommit off) with nothing running and no
request for that many seconds, and rolls the transaction back; its next request gets
session_ended with reason idle_in_transaction. A startup option, and at runtime SET hardcharger.idle_in_transaction_session_timeout = 300 for one session or SET GLOBAL ...
(administrators) for every session that hasn't set its own. A retained result does not keep
such a session: the transaction's locks are what the limit is for.
With instrumentation on (--enable-instrumentation), the server keeps its history in
tables: instances, sessions, sql_statements and sql_executions, and the views
session_activity, active_sessions, session_stats and execution_details, which only
an administrator can read. By default they live in a DuckDB file next to the database
(instrumentation_db_path), for development or a single server. Use PostgreSQL in
production, and for any cluster of more than one replica: attach it in the init SQL and
name it in instrumentation_catalog (instrumentation_schema picks its schema). Any other
catalog, DuckLake among them, is refused at startup.
init_sql_commands: "INSTALL postgres; LOAD postgres; ATTACH 'host=pg.internal dbname=ops user=hardcharger' AS ops (TYPE postgres);"
enable_instrumentation: true
instrumentation_catalog: ops
instrumentation_schema: hardcharger
Recording never holds up a statement. Records are queued and written by one background
writer in batches, a transaction each, so the tables keep up with tens of thousands of
statements a second however large they grow. A statement appears in sql_executions as
queued or executing from the writer's next batch, usually within milliseconds, and one
that starts and ends within a batch appears once, finished; hardcharger_active_connections()
always shows what runs now. If the catalog falls behind, the queue holds up to 128 MiB of
records and then drops new ones: hardcharger_server_info() counts them
(instrumentation_queued, instrumentation_dropped, instrumentation_failed), as does
/metrics (hardcharger_instrumentation_*), and the log says so at most once a minute. At
shutdown the server writes the backlog for up to 30 seconds, then closes its sessions and
executions in the tables.
👥 Access control
Point rbac_store_uri at a PostgreSQL database, the one every replica of a cluster
shares, and manage access in SQL:
CREATE ROLE analyst;
GRANT SELECT ON SCHEMA analytics TO analyst; -- every table, now and later
GRANT SELECT (email, signup_ts) ON crm.users TO analyst; -- two columns only
CREATE USER joe WITH PASSWORD '…'; -- signs in with it
GRANT analyst TO joe;
CREATE VIEW published.daily AS SELECT … FROM raw.events; -- read with its owner's rights
GRANT SELECT ON published.daily TO analyst;
REVOKE analyst FROM joe; -- reaches joe's open sessions too
Each statement is checked inside DuckDB against its own plan, after binding and again before optimizing, so nested SQL, views and macros can't route around a grant. Anything the check can't classify is refused. Changes reach every replica within about a second.
Some things DuckDB runs while it binds a statement, before there is a plan to check: a table
function's arguments, a PRAGMA's parameters, an AT clause, EXECUTE's values, and the body of
any user macro the statement calls, with the caller's arguments. Those are checked first, on the
parsed statement, by the same rules: nextval() / currval() there need USAGE on the sequence
and setval() DROP SEQUENCE on its schema (for a catalog_access token: write, or read for
currval(), on the sequence's catalog), a readonly session moves no sequence at all, and a macro
that hands the caller's string to query() or read_csv() is checked with that string. A kind of
statement the check has no rule for is refused. Upgrading from 2.13.3: a role that called
range(nextval('s')) or SELECT * FROM t AT (VERSION => setval(...)) without those privileges,
directly or through a macro, now needs them.
Users can call an extension's table function: GRANT EXECUTE ON TABLE FUNCTION read_hl7 (PATH ARGUMENT 2) TO analyst opens it to a role, and the arguments the grant declares as paths go
through the storage privileges as read_csv()'s path does. delta_*() and iceberg_*() read
the files their table's log or manifest names, wherever they are, with a storage client of their
own, so whatever path they are handed they need READ FILESYSTEM, READ OBJECT STORAGE and
READ HTTP everywhere (a location grant can't bound them); grant those to the roles that use them
when upgrading from 2.13.3, where EXECUTE and a location grant were enough. A user's own table
macro named like them is a macro, and is unaffected.
DuckLake's functions act on the whole catalog they name, so besides EXECUTE on the function a
user needs a privilege on that catalog, granted ON CATALOG (a grant on one of its schemas or
tables doesn't reach it). To inspect (ducklake_snapshots, ducklake_table_info,
ducklake_list_files, ducklake_table_changes, ducklake_options, ducklake_settings,
lake.snapshots(), ...):
GRANT EXECUTE ON TABLE FUNCTION ducklake_snapshots TO analyst; -- one GRANT per function used
GRANT SELECT ON CATALOG lake TO analyst;
To maintain (ducklake_expire_snapshots, ducklake_cleanup_old_files,
ducklake_delete_orphaned_files, ducklake_set_option, ducklake_set_commit_message) and to
compact (ducklake_merge_adjacent_files, ducklake_rewrite_data_files,
ducklake_flush_inlined_data):
GRANT EXECUTE ON TABLE FUNCTION ducklake_merge_adjacent_files TO lake_maintenance;
GRANT MAINTAIN ON CATALOG lake TO lake_maintenance; -- no SELECT needed: compaction hands back no rows
GRANT CHECKPOINT TO lake_maintenance; -- for CHECKPOINT lake, which runs all of the above
ducklake_table_changes runs ducklake_table_insertions and ducklake_table_deletions, so it
needs EXECUTE on those two; its rows go through the table's row and masking policies like any
read. A table with row or masking policies is not compacted. The catalog must be written as a
string (ducklake_snapshots('lake')), and a view or macro that wraps a DuckLake function is refused:
call it directly. A token with catalog_access rules needs no grants: its rules decide, read access
to inspect and write access to maintain, compact or CHECKPOINT a DuckLake catalog.
ducklake_add_data_files stays the administrator's for such tokens.
Nested schemas (DuckDB 2.0) are
granted by their path: a grant on sales.payroll covers sales.payroll.* and nothing alike,
one on sales covers its children, and CREATE SCHEMA ON SCHEMA sales lets a role nest
schemas in it.
Users can share macros: GRANT CREATE MACRO, DROP MACRO ON SCHEMA tools TO analyst lets a role
create and drop scalar and table macros in tools (replacing one needs both). A macro is expanded
into the statement that calls it, so its body reads with the caller's rights. So that a user's
macro can't change what anyone else's SQL computes, Hardcharger refuses temporary macros, the name
of a built-in function or of one an extension autoloads, replacing or standing in for a function
that a view, a row or masking policy (or a macro one of them uses) calls, and a body that calls
what its creator may not (query(), files beyond their system privileges).
Types and triggers follow: GRANT CREATE TYPE, DROP TYPE ON SCHEMA tools TO analyst lets a role
create enums, structs and aliases there (never a built-in or extension type's name, nor one a
view, macro, trigger, policy, column default or check constraint names, and dropping or replacing
such a type is refused too). GRANT CREATE TRIGGER, DROP TRIGGER ON SCHEMA tools TO analyst lets a
role put triggers on the tables it owns. A user's trigger runs with its owner's rights, whoever
writes the table, so an administrator's write lends it nothing; an administrator's trigger runs
with the writer's rights, as DuckDB runs it. Triggers chain: a body that writes a table with
triggers of its own fires them, each body with its own owner's rights, and an administrator's
trigger fired that way runs with the rights of the body that fired it. INSERT ... ON CONFLICT
(and INSERT OR IGNORE / OR REPLACE) fires a table's INSERT triggers like any insert.
DuckDB keeps a trigger's action as it was written and looks its names up again in every statement
that fires the trigger, in the writer's session: a table, view or sequence the action names
without its catalog follows the writer's current catalog and search path, the writer's temporary
objects first, and a bare name is taken by a WITH of the firing statement before the catalog.
Under access control a trigger does not depend on that:
CREATE [OR REPLACE] TRIGGERstores the action with its tables, views and sequences named with their schema, as the creator's session resolves them (duckdb_triggers()showsINSERT INTO main.audit_log ...), in a session and in the init SQL alike. The catalog is left out, so renaming a database file, or attaching one under another name, leaves its triggers working. An action that names a sequence (nextval) or aquery_table()table by anything but a plain string is refused, since what it names could not be checked when the trigger fires.- When a trigger fires, each name in its action, and in the macros its action calls, must be, in
the writer's session, the object it is for the trigger's own table (the schema it gives, in that
table's catalog; a bare name in the table's own schema, else in
main), and noWITHfrom outside the trigger's body may stand in for a table or view the body reads. Otherwise the write is refused, saying which trigger and which name, and what to do: drop a temporary object of that name (the temporary catalog's schema ismain, so a temporaryaudit_logis found beforemain.audit_log),USEthe trigger table's database (a trigger on an attached database's table fires for sessions in that database), or give aWITHanother name. A user's trigger fired by an administrator is held to this too; an administrator's own trigger fired by an administrator is not. - A trigger made by an earlier Hardcharger (2.13.1 and before), or one that was already in a
database file, still has its names as written, and keeps firing wherever they resolve to the
objects for its table. Refused for every writer but an administrator, until the trigger's owner
runs
CREATE OR REPLACE TRIGGERonce (with the same text, which then stores the names with their schema): a bare name that is in both the table's schema andmain, and one that only the creator's own search path found. Only an administrator may create a table or view that would put a bare name a trigger uses in both places. After upgrading, try a write as a user: an administrator's own statements are not checked.
The functions those bodies call are not the session's to decide either, and neither are the ones
in a view's query, a row or masking policy, or a table's CHECK constraints, generated columns and
column defaults. DuckDB keeps all of these as written and looks their names up again in whichever
session reads or writes. Under access control each has one schema to look in, fixed by what it
belongs to, and no session's search path, current catalog or temporary objects are consulted:
| Expression | Where its functions, macros and types are found |
|---|---|
A table's CHECK constraints, generated columns, column defaults, index expressions |
the table's schema |
| A trigger's body | its table's schema |
| A view's query | the view's schema |
| A row or masking policy | main of the protected table's database |
| A macro one of them calls | where the caller's are |
A name without a schema is found there, then in main of that same database (never the session's
current one), then among DuckDB's own functions: a view in reports that calls fmt_amount gets
reports.fmt_amount if there is one, else main.fmt_amount. schema.name is found in that schema
of the same database, catalog.schema.name exactly there. A macro is never called as a method
inside one of these (x.is_valid(); DuckDB's own functions are: x.lower()). A macro or type in a
third schema, which only the creator's search path finds, is named with its schema:
DEFAULT util.stamp(). CREATE TABLE, CREATE INDEX and CREATE TRIGGER store the macros they
call that way, as the creating session finds them (duckdb_tables() shows
CHECK(main.is_valid(x)), duckdb_indexes() main.norm("name")); CREATE VIEW,
CREATE ROW POLICY and SET MASKING POLICY refuse a definition whose names would be something
else where it is evaluated, with the name to write. Only an administrator may create a
macro or type that an existing view, trigger, policy or table would then find first. An
administrator's session gets the same answers as anyone's.
Views, triggers, policies and tables from before 2.14 are looked up the same way. One that names
a macro of a third schema without it, or calls a macro as a method, is refused when it is used,
saying which name and how to mend it: CREATE OR REPLACE the view or trigger, re-create the policy,
ALTER TABLE ... ALTER COLUMN ... SET DEFAULT; for a CHECK constraint or generated column, which
DuckDB cannot alter, re-create the table or have an administrator create a macro of that name in
the table's own schema that calls the one meant
(CREATE MACRO app.is_valid(x) AS main.is_valid(x)).
An index over a macro that was made before 2.14 keeps the macro's name as written, and an index's
entries are only right for the macro they were computed with. Such an index is used while its name
can mean one macro only. Where its database has several macros of that name (one in the table's
schema and one in main, say), or the name is in neither place, reads and writes of the table and
CHECKPOINT are refused, saying so, until the index is dropped and created again: CREATE INDEX
then stores the macro with its schema.
On a server without access control every session may do anything anyway and DuckDB's own behaviour stands: name the tables in a trigger's action with their schema.
A write needs the privilege of what it does. INSERT ... ON CONFLICT DO NOTHING and
INSERT OR IGNORE need INSERT; ON CONFLICT ... DO UPDATE and INSERT OR REPLACE need INSERT
and UPDATE; a MERGE INTO needs INSERT, UPDATE or DELETE for each kind of WHEN ... THEN
action it has. Each also needs SELECT on the target's columns it reads, which for the conflict
forms is the key that tells a conflict (GRANT SELECT (id) ON t TO r is enough).
An UPDATE or DELETE needs SELECT on the columns the statement itself reads (in WHERE, a
SET expression, a join, a subquery; on all of them for a RETURNING), as in Postgres, and on the
columns DuckDB has to read to check a constraint or keep an index whose error could name them (a
table's unique keys for a DELETE, for instance). So an unfiltered UPDATE t SET x = 0 or
DELETE FROM t on a table without keys needs none, with triggers on the table or without. With
triggers, a write needs SELECT on the columns of the table's keys and indexes (and an UPDATE on
those of a CHECK over several columns, or of one that calls a macro) even where it would not
without them, and on a table that
also has generated columns, on every column DuckDB reads to hand the triggers their rows.
DuckDB hands a table's triggers the rows a write changes (a transition table, OLD, NEW), and
somebody answers for a writer who may not read those rows itself:
- An administrator's trigger vouches for its body. When an administrator's session creates (or
replaces) a trigger, the writer needs no
SELECTfor that body's reads of the rows: the administrator wrote the body, and so chose where the rows go. An administrator who puts a row-copying trigger on a table is choosing who can see those rows: whoever can read the table the body copies them into, or the error a failing body raises. Everything else the body does (the tables it writes, other tables it reads) still takes the writer's rights. - A user's trigger answers with its owner's rights: the owner needs
SELECTon the table. - Any other trigger answers for nothing, and reading the rows takes the writer's own
SELECT: a trigger that DuckDB statements in the init SQL created or replaced (they run outside access control, so nobody is on record as having made it), and one that was already in a database file. An administrator makes such a trigger vouch by running itsCREATE OR REPLACE TRIGGERonce in a session.
The init SQL (init_sql_commands, init_sql_commands_file) can hold these statements too.
They run as the administrator, in order with the DuckDB statements around them, so a grant
can name a table the init SQL has just created:
CREATE TABLE IF NOT EXISTS sales (amount DECIMAL(12, 2));
CREATE ROLE IF NOT EXISTS readers;
GRANT SELECT ON sales TO readers;
CREATE USER IF NOT EXISTS analyst WITH PASSWORD '…';
GRANT readers TO analyst;
The init SQL runs at every start, and on every replica of a cluster, against a store that
keeps what earlier starts created: write IF NOT EXISTS, or the second start stops at
already exists. CREATE USER IF NOT EXISTS leaves an existing user's password as it is
(ALTER USER … WITH PASSWORD changes it). A failing statement stops the server like any init
SQL error, and its log line leaves out the statement's passwords. Keep
passwords in init_sql_commands_file rather than an environment variable: the server keeps
that file out of SQL's reach (see below). Without rbac_store_uri, an access-control
statement in the init SQL stops the server before anything runs (access control is not enabled on this server).
A password set by CREATE USER or ALTER USER ... WITH PASSWORD needs password_min_length
(12) characters; there are no composition rules and no expiry by default (NIST SP 800-63B).
password_min_length may be set as low as 1; below 8 the server logs a warning at startup
naming the setting, its value and the recommended 12.
password_min_character_classes (0 to 4) asks for that many kinds among lowercase letters,
uppercase letters, digits and other characters, and password_max_age_days (0: never) makes a
password that old one its user must change: it still signs in, held like a temporary password
(below), so the session runs nothing but ALTER USER CURRENT_USER WITH PASSWORD '<new>' REPLACE '<current>' (the password of user joe has expired (password_max_age_days) and must be changed before anything else runs: ...), and the user renews it without an administrator. The rules
are checked only when a password is set: existing passwords keep working, a password set
before 2.14 never expires, and CREATE USER IF NOT EXISTS for a user that exists sets nothing
and checks nothing. The administrator's password (admin_password) is the operator's: one
the policy would refuse is a warning at startup.
Use PostgreSQL in production, and for any cluster of more than one replica. For development, or a server that will only ever run one replica, the store can be a DuckDB file instead:
rbac_store_uri: duckdb:/var/lib/hardcharger/rbac.duckdb # or any path ending in .duckdb
The file is created 0600 (one that other users can read or write is refused), only one
server may open it (a second one on the same file stops at startup), and no SQL statement
reaches it, the administrator's included. Each change is checkpointed into the file at
once, so nothing depends on its write-ahead log. There is no migration between the two
stores: moving to PostgreSQL later means creating the users, roles and grants there again.
The guard above sits in DuckDB's file system, and an extension with file I/O of its own
(sqlite_scanner) does not go through it: ATTACH '<path>' (TYPE sqlite), the sqlite:
path prefix, and the sqlite_scan / sqlite_query / sqlite_attach table functions open
the file with SQLite's own library. So those are refused separately, when the resolved path
names one of the server's files or a sibling (the store, the database, the instrumentation
and log files, and their WAL and temporary siblings): at plan time, after the path has been
worked out, by every spelling — a computed path, .., a relative path, a symlink, a hard
link, a differing case, a Windows 8.3 name. Attaching an unrelated SQLite file still works.
A DuckDB-storage ATTACH of one of these files is left to the file-system guard, which
already covers it (and is how the server attaches its own). This closes the one way SQL
could reach the server's files outside DuckDB's file system; the sqlite_scanner load still
takes the administrator or a role granted MANAGE EXTENSIONS, which belong only to roles you
would trust with the server's files.
Named administrators (SYSTEM ADMIN)
The administrator is the one user the server is started with (admin_username and its
password). SYSTEM ADMIN lets named users do the administrator's work under their own
names, so nobody has to share that password and the audit trail says who did what:
GRANT SYSTEM ADMIN TO alice; -- or TO ROLE dba: the role's members may ask
Holding it changes nothing by itself. alice signs in as herself, with her own roles' rights,
and asks for it in the session where she needs it, as sudo is asked for:
SET ROLE SYSTEM ADMIN; -- this session acts as the administrator
CREATE USER carl WITH PASSWORD '…';
GRANT analyst TO carl;
RESET ROLE; -- alice again (SET ROLE ALL, NONE or a role do the same)
REVOKE SYSTEM ADMIN FROM alice; -- the administrator, or another System Admin
It is written in two words, like the system privileges (READ FILESYSTEM), so it is no
role's name: a role called sysadmin in a store an earlier version made stays the ordinary
role it was, and SET ROLE "SYSTEM ADMIN" (quoted) names a role, never this.
- What the session can do. Between
SET ROLE SYSTEM ADMINandRESET ROLEit does everything the administrator does, and nothing less: users, roles, grants, row and masking policies, tenants, group mappings and scoped tokens for others;ATTACH, secrets, extensions, files,SET GLOBAL,KILL SESSION, the SQL monitor and the server's own catalogs. Its statements are not checked against grants, row policies or masks, in every tenant's catalogs. What it creates belongs to the administrator (no user owns it), and what it grants stands as the administrator's grants do, also once it no longer holdsSYSTEM ADMIN. Back as herself, alice holds nothing on what she made as System Admin. - One session at a time. Another session of the same user, a new session, a reconnect
and a session a client opens to replace a lost one all start as the user. A client that
sends
SET ROLE SYSTEM ADMINagain is asked like the first time. Thehardchargerclient and the web UI's SQL editor need nothing special: it is plain SQL in the session they hold. In the web UI, a tab whose session acts as System Admin says so (a "System Admin" badge in the tab and in the header), and while one does, the UI offers the administrator's pages (Server Configuration, SQL Monitor, everyone's sessions with End): each opens a session of its own that saysSET ROLE SYSTEM ADMINtoo. The UI asks the tab's session (HARDCHARGER_IS_SYSTEM_ADMIN()) afterSET ROLE,RESET ROLE, a refused statement and a refusal on one of those pages, soRESET ROLE, a revoke or a new session closes them again. The role it shows next to the user stays the sign-in's,user. - Who grants it. Only the administrator, or a session acting as System Admin. It has no
ADMIN OPTIONorGRANT OPTION,ALL PRIVILEGESnever includes it, and no owner, tenant admin or holder of a role's admin option can give it. It goes to a user or a role of the server itself: not toPUBLIC, and not to a tenant's user or role. - Through a role. A role granted it carries it to the members the administrator (or a
System Admin) gave the role, to roles they granted it to, and to users whose sign-in token
lists a group mapped to it (
CREATE GROUP MAPPING, which only they create). A membership that the holder of a role'sADMIN OPTIONgranted never carries it, and once a role holdsSYSTEM ADMIN, only the administrator or a System Admin grants, revokes or drops that role, whatever admin option exists on it. - Taken away at the next statement. Whether the user holds it is asked on every
statement, prepared ones included. After
REVOKE SYSTEM ADMIN,DROP ROLEof the role that gave it, taking the user out of that role or unmapping its group, the session's next statement fails withuser alice no longer holds SYSTEM ADMIN, which SET ROLE made active. Run RESET ROLE to go on as alice, and a statement still running is stopped. Disabling or dropping the user ends its sessions. This holds on every replica at once, not after its next poll: a session acting as System Admin asks the store itself (one small read of its version) before every statement, and a change it makes to users, roles or grants asks again inside the change's own store transaction. What the session did before stands: an open transaction is alice's to commit or roll back afterRESET ROLE. - Only on the store's own word. What a server last heard from the store is not enough
to act as System Admin on. While the store does not answer,
SET ROLE SYSTEM ADMINis refused, and a session already acting as one runs nothing more that way (… which is asked of the access control store before every statement, and the store did not answer);RESET ROLEmakes it its user again, served from the last grants like every store user. The administrator is not affected. - Never more than the session's own limits. A session that signed in with a scoped
token, with a token carrying
catalog_accessrules, with thereadonlyrole, or on aread_onlyconnection, and every session of a tenant's user, is refused, and the refusal says which of these it is (Hardcharger blocked SET ROLE SYSTEM ADMIN: this session signed in with scoped token reports, and a scoped token never acts as System Admin). A session acting as System Admin that turnsread_onlystops acting as one. - The administrator stays the way in. It is the server's configuration, not a user of
the store: no statement renames it, changes its password, disables or drops it, and a
System Admin cannot read its credentials (
block_sensitive_pathskeeps the configuration and the environment out of SQL's reach for every role). It needs no grant, so it still signs in and takesSYSTEM ADMINaway from anyone when the store's grants are wrong, and the server starts when they are missing or unreadable (nobody holdsSYSTEM ADMINthen, and the log says so). An external policy service (rbac_opa_url) is asked once, with the actionsystem_admin, when a session asks; like the administrator's, a System Admin's statements are not sent to it.
Who holds it, and which sessions act as one now:
SELECT grantee, grantee_type, privilege, grantor FROM hardcharger_grants() WHERE privilege = 'SYSTEM ADMIN';
grantee | grantee_type | privilege | grantor
alice | USER | SYSTEM ADMIN | administrator
dba | ROLE | SYSTEM ADMIN | administrator
SELECT user_name, privilege, via FROM hardcharger_effective_privileges('dave') WHERE privilege = 'SYSTEM ADMIN';
user_name | privilege | via
dave | SYSTEM ADMIN | dba
SELECT username, role, system_admin FROM hardcharger_sessions() ORDER BY username;
username | role | system_admin
admin | admin | false
alice | user | true
SHOW GRANTS lists it too (one ALL on SERVER row with grantee type SYSTEM ADMIN while
the session acts as one). hardcharger_active_connections() has the same system_admin
column. A session asks about itself with HARDCHARGER_IS_SYSTEM_ADMIN() and
HARDCHARGER_ACTIVE_ROLE() (the role SET ROLE made active, SYSTEM ADMIN, or NULL);
HARDCHARGER_IS_FULL_ADMIN() is true for it as for the administrator, and
HARDCHARGER_ROLE() stays the sign-in's role.
Everything about it is in the access-control audit chain, and every record names the user
by name and by its id in the store (user, user_id), the session (session_id) and, for
what it did as System Admin, acting_as: SYSTEM ADMIN:
Record (message) |
When |
|---|---|
access-control statement, statement: GRANT SYSTEM ADMIN / REVOKE SYSTEM ADMIN |
It is granted or revoked (target, target_ids: the user or role) |
System Admin elevation |
A session starts acting as one (held_through: its own grant, or the role) |
System Admin elevation refused |
SET ROLE SYSTEM ADMIN is refused (error: why) |
System Admin elevation ended |
It stops (reason: RESET ROLE, SYSTEM ADMIN no longer held, session closed, ...) |
access-control statement, access-control statement refused |
Each CREATE USER, GRANT, ... it runs, with target, target_ids, privilege, membership, membership_ids, object, change as they apply |
statement run as System Admin |
Every other statement it runs (sql, as the log shows SQL: credentials masked; administrative: ATTACH, CREATE SECRET, ... when it is one) |
administrative command run as System Admin |
KILL SESSION (target_session), SET GLOBAL hardcharger.* |
{"message":"access-control statement","kind":"access_control","user":"alice","user_id":"5e4d0972-a268-45e8-a071-bb4f78e761ec","session_id":"s_4wa5v2ujjazy3r5avaadvoqslxjxixxb","acting_as":"SYSTEM ADMIN","statement":"GRANT","status":"success","target":"user carl","target_ids":"4c6de293-3ce4-4c13-aa02-ebe0e5ba1940","membership":"role analyst","membership_ids":"5fea80e6-163f-4966-9e73-b0be61c1d98a"}
No record holds a password, a password hash, a token or a secret: ALTER USER … WITH PASSWORD is recorded as change: password, a scoped token by its name. The user_id,
session_id and target fields are on every access-control record from 2.14 on, whoever
runs the statement; a log an earlier version wrote still verifies (--verify-audit-log),
since each record says which fields its digest covers.
The first 2.14 server to open an existing store creates the SYSTEM ADMIN grants table
and adds the user metadata columns in place. A 2.13 replica on the same store
does not read that table, so there nobody holds SYSTEM ADMIN, SET ROLE SYSTEM ADMIN is
a syntax error, and the rules above about roles that carry it are not applied: nothing such
a replica lets a non-administrator write can give anyone SYSTEM ADMIN (a membership it
lets a role's admin-option holder grant does not carry it), but grant it only once every
replica runs 2.14, so that every replica also shows and audits it. The reasons for each
rule are in docs/security-administration-design.md.
Delegated account management (CREATE USER, ...)
A help desk can manage accounts without reading data and without SYSTEM ADMIN. Five system
privileges, each opening one statement, are granted to a role like READ FILESYSTEM:
CREATE ROLE helpdesk;
GRANT CREATE USER, ALTER USER, DROP USER, CREATE ROLE, DROP ROLE TO helpdesk;
GRANT helpdesk TO amy;
amy then creates users, resets their passwords, disables, enables and drops them, and creates and drops roles, under her own name:
CREATE USER eve WITH PASSWORD '…';
ALTER USER eve WITH PASSWORD '…'; -- ends eve's sessions, as an administrator's reset does
ALTER USER eve DISABLE;
DROP USER eve;
What she reaches is limited to what her session is, so none of these statements hands her (or anyone) authority she lacks:
- Users no more powerful than the session.
ALTER USERandDROP USERreach a user only when every role it holds is one the session acts with (SET ROLEnarrows that), and held the same way: a role it holds through a membership the administrator granted (which can carry an account privilege or a policy exemption) amy must hold that way too, not only through one a role's admin-option holder granted (which carries neither); every role it holdsWITH ADMIN OPTIONis one amy could grant, every session attribute it has (which row and masking policies read) amy has with the same value, and, forALTER USER, it owns no table, view or schema. A user who holdsSYSTEM ADMINand the server administrator are never reached (Hardcharger blocked ALTER USER: user bob holds role analyst, which user amy does not hold in this session; only an administrator changes it). That covers a new password,ENABLEof a disabled account,DISABLEandDROP. - No policy attributes.
ALTER USER … SET ATTRIBUTE/UNSET ATTRIBUTEstay the administrator's: an attribute decides which rows and values a user sees. - Roles no more powerful than the session.
DROP ROLEreaches a role only when everything it inherits is held by the session (what it inherits through the administrator's memberships, held the administrator's way), it is held by the session itself or holds no privilege of its own, and no row policy names it and no masking policy exempts it. A new role (CREATE ROLE) holds nothing, and its creator gets no admin option on it: granting a role still needs the roleWITH ADMIN OPTION, as before. A new user holdsPUBLIConly. - The server's own users and roles. A tenant's users and roles stay with that tenant's
tenant_adminrole, as before (acme/tom belongs to tenant acme, and the ALTER USER privilege reaches system-scope users and roles only). - Granted only by an administrator. Only the administrator, or a session acting as
System Admin, grants and revokes them; they have no
ADMIN OPTION, are never part ofALL PRIVILEGES, and go to a role of the server itself, not toPUBLICor a tenant's role. A role carries them only through memberships the administrator gave (and through group mappings): a membership the holder of a role's admin option granted never carries one, and once a role holds one, only the administrator grants membership in it. - Never for a limited sign-in. A scoped token, a token with
catalog_accessrules, areadonlysign-in and aread_onlyconnection never use them (this session's sign-in token carries catalog_access rules, and such a session never uses the CREATE USER privilege). - Taken away at the next statement, on every replica. Each statement asks the store
itself inside its own store transaction, not what the replica last polled, so after
REVOKE CREATE USER FROM helpdesk(or taking amy out of the role) on any replica, amy's nextCREATE USERanywhere is refused. A grant is usable at once on every replica too.
Passwords set this way are checked as any CREATE USER or ALTER USER … WITH PASSWORD
password is, and are temporary (below): amy can hand eve a first password, but cannot keep
using it, and a reset she does shows up the next time the real user signs in.
Temporary passwords and changing your own
A password someone else chose for a user is temporary when a delegate sets it (a holder of
CREATE USER or ALTER USER, or a tenant's tenant_admin), and when an administrator asks
for it with EXPIRE:
ALTER USER carl WITH PASSWORD '…' EXPIRE; -- carl changes it at the next sign-in
CREATE USER dora WITH PASSWORD '…' EXPIRE; -- and dora at her first
ALTER USER erin PASSWORD EXPIRE; -- erin's current password, from her next statement on
ALTER USER carl WITH PASSWORD '…'; -- an administrator's, without EXPIRE: not temporary
A sign-in with a temporary password succeeds, but its session runs nothing (statements,
prepared statements, metadata requests, ingest, partitioned ingest, changes of its session
options) except the change of that password, and says so (it opens where the server's sessions
start, with the options its client asked for left unapplied): Hardcharger blocked this statement: the password of user carl was set by someone else and must be changed before anything else runs: ALTER USER CURRENT_USER WITH PASSWORD '<new>' REPLACE '<current>'. A sign-in that does not use the password (an identity provider's token,
a client certificate) is not held. --verify-credentials verifies a temporary password (a
stopped cluster may start for it) and adds "password_must_change": true to its answer.
A temporary password lasts password_temporary_max_age_hours (72; 0: no limit) from when it
was set. After that it neither signs in nor replaces itself: the temporary password of user carl has expired (it was set more than 72 hours ago): an administrator must set a new one
(said only to whoever gave it; --verify-credentials refuses it the same way).
Every user changes its own password, with no privilege, by giving the current one:
ALTER USER CURRENT_USER WITH PASSWORD 'new password' REPLACE 'current password';
-- or with its own name: ALTER USER carl WITH PASSWORD '…' REPLACE '…'
A connection opened with read_only=true can run this command when its password must be changed.
The current password is required, so a session alone (or an access token someone took) can
never change it, and the new one must differ from it (the new password is the current one; choose a different password), so a temporary or expired password never ends its hold by being
"changed" to itself; ALTER USER <own name> WITH PASSWORD '…' without REPLACE is refused to
everyone but the administrator. The change ends the user's sessions, as any password change
does: sign in again with the new password. The web UI does all of this itself: signed in with
a temporary password, it asks for a new one, changes it and signs in again. The hardcharger
client runs the statement as written. CURRENT_USER is a keyword here: a user actually named
current_user is written quoted (ALTER USER "current_user" …).
A help desk that resets a password and signs in with it can only change it, which is an audit
record under the user's name, and the user's next sign-in then fails with every password they
know. hardcharger_users() shows password_must_change to administrators (and to each user
for its own row); the audit records say password: temporary password set, password changed by the user, password set, password expired or password removed, the
account's after state ends in ; password must be changed while it must, and each statement
refused in such a session is a statement refused until the password is changed record.
A 2.13 replica on the same store does not know temporary passwords: there, such a sign-in is
not held. As with SYSTEM ADMIN, use them once every replica runs 2.14. Each change and each refusal is an access-control audit record with the target
(target, target_ids), the privilege the statement needs (privilege), what authorized it
(authorized_by: administrator, System Admin, tenant_admin of tenant acme, or ALTER USER privilege, through role helpdesk), the session's active_role, the statement's Chargewire id
(statement_id, also on its log lines) and the account before and after, sanitized:
{"message":"access-control statement","user":"amy","user_id":"…","session_id":"s_…","statement_id":"q_…","active_role":"helpdesk","statement":"ALTER USER","status":"success","target":"user eve","target_ids":"…","privilege":"ALTER USER","change":"password","authorized_by":"ALTER USER privilege, through role helpdesk","before":"enabled; password login; roles: none","after":"enabled; password login (new password); roles: none"}
A password appears only as password login, an attribute by its name: no record holds a
password, a hash, a token or an attribute's value. Membership grants (user carl in role clerks: no → yes, WITH ADMIN OPTION) and grants of these privileges carry before and
after too.
Upgrade every replica before granting delegated account privileges. Their enforcement and audit behavior are described in the security administration design.
Tokens with catalog_access rules under access control
Under access control a store user's grants decide what it may read and write; the
catalog_access rules of its sign-in token grant it nothing more. A session that signed in
with such a token also uses none of the system privileges its roles hold, as a scoped
token's session uses none: no READ FILESYSTEM, MANAGE CATALOGS, storage privilege on a
location, account privilege (CREATE USER, ...), policy exemption, or admin option to grant
one. It is told so: Hardcharger blocked ATTACH needs the MANAGE CATALOGS system privilege, which this session does not use: it signed in with a token that carries catalog_access rules .... The same user signed in without the
rules uses them as before (changed in 2.14).
Exemptions from row and masking policies
A trusted job, such as a replication service that keeps a table in step with its source, can read and write tables that have row or masking policies without running as the administrator:
CREATE ROLE replicator;
GRANT EXEMPT ROW POLICIES, EXEMPT MASKING POLICIES TO ROLE replicator;
GRANT SELECT, INSERT, UPDATE, DELETE ON SCHEMA crm TO replicator; -- still needed
GRANT replicator TO etl;
EXEMPT ROW POLICIES reads every table without its row-policy filters, and EXEMPT MASKING POLICIES reads every column unmasked; one grant covers every table, those created later
too (the counterparts of PostgreSQL's BYPASSRLS and Oracle's EXEMPT ACCESS POLICY). A
principal exempt from every row policy and mask on a table writes it as freely as it reads
it: INSERT, UPDATE, MERGE, INSERT ... ON CONFLICT and DELETE ... RETURNING, bulk
ingest included. Everyone else gets today's answer: a write into a table with policies is
refused, and a role exempt from only one kind is refused where the other kind applies. An
exemption grants nothing else: the job still needs SELECT, INSERT and the rest.
- Who grants them. Only the administrator or a session acting as System Admin, and
never
WITH ADMIN OPTION: each takes away every policy of its kind at once. They are granted to roles (notPUBLIC, not a tenant's) and to nothing narrower than the whole server. A role carries them only through memberships the administrator (or a System Admin) granted: a member a role's admin-option holder added gets the role's other privileges, not its exemptions, until the administrator grants the role itself. - Who never holds them. A session signed in with a scoped token or a token with
catalog_accessrules, and a tenant's users. An exemption reaches no catalog the principal can't see. - Definer's rights. A user's trigger body runs with its owner's exemptions, never the writer's. Views and macros apply the reader's policies, as always, so the reader's exemptions: an exempt owner lends a view nothing.
- Revokes. A revoke counts at the session's next statement, prepared ones included, on every replica at once: a session that holds an exemption asks the store before each statement (one small read), and while the store doesn't answer, no exemption applies. The same holds for a trigger owner's exemption in its trigger bodies: while some trigger's owner is exempt, every session asks the store before each statement, and a body run while the store doesn't answer applies its owner's policies.
- Seen and recorded.
SHOW GRANTS,hardcharger_grants()andhardcharger_effective_privileges()list them;hardcharger_policies()says a policy doesn't apply to an exempt session; and the audit record of each statement an exemption let through names it (objects:EXEMPT ROW POLICIES on table crm.main.accounts).
A 2.13 replica on the same store does not read the exemptions (they are kept where it skips privileges it does not know), so there every policy applies to their holders.
Policy functions in plain SQL
The functions a row or masking policy can call give the same answer in any statement, so a user can check what their policies will see:
| Function | Answer |
|---|---|
current_user, session_user, user, hardcharger_user() |
The Hardcharger user (DuckDB's own answer is duckdb) |
is_role_active('hr') |
Whether the role is active in this session (after SET ROLE); false for a role the user doesn't hold and for one that doesn't exist alike |
session_attribute('region') |
The user's attribute (ALTER USER … SET ATTRIBUTE), or NULL |
current_role() |
The role SET ROLE made active, or NULL (policies can't call it: the session changes it) |
Each answer is worked out when the statement runs, so SET ROLE counts at the next
statement, prepared ones included. For the administrator, and on a server without access
control, every role is active and there are no attributes. Like a policy TO a role,
is_role_active() follows SET ROLE: once a user acts with one of its roles, the policies TO
its other roles, restrictive ones included, no longer apply to it, and is_role_active() is
false for them (as in PostgreSQL). A restriction that must hold whatever role a user acts with
is written for everyone (TO PUBLIC, or no TO), with a condition on current_user or
session_attribute(), not on is_role_active().
When the store is down
Access control never lets the store hold up the server, and never fails open on anything it has to write:
- Every store round trip is bounded by
rbac_store_timeout_seconds(default 10). A store that doesn't answer in time fails the statement that needed it withaccess control store unavailable: timed out after N s, and what that statement was doing is rolled back as soon as the store answers again, so aCREATE USERthe client was told failed never appears later. (A timeout while committing says the change may have been applied.) Statements that need the store at the same time (many sessions creating tables, as a dbt run does) take turns in the order they asked, and one waiting its turn fails only when a store statement has been outstanding for the timeout, never because the line ahead of it is long. For a PostgreSQL store the server also adds libpq'sconnect_timeout, TCP keepalives,tcp_user_timeoutand astatement_timeoutto the connection string, each unless the string sets it already. - Access-control statements and DDL fail while the store is unreachable. A
CREATE TABLEorCREATE VIEWrecords its owner in the store before it runs: when that can't be done, the statement fails and creates nothing, so no object is ever left without an owner. - Sign-ins and queries go on with the users, roles and grants the store last gave
(availability), and the server says so: a warning when the store stops answering and
every 30 s after, with the snapshot's age, a line when it answers again, and the metrics
hardcharger_rbac_store_upandhardcharger_rbac_snapshot_age_seconds. A revoke made on another replica during the outage doesn't reach this one until the store answers. Setrbac_max_snapshot_age_secondsto bound that: once the store has not answered for longer, every principal but the administrator is refused (fail closed) until it does. The default, 0, keeps serving; pick a limit when a stale grant is worse than an outage. - Errors never carry the store's credentials: neither the connection string nor any password in it reaches a client, a log line or the audit chain.
One store per cluster
Grants name catalogs, so a store two clusters shared by mistake would apply one cluster's
grants to the other's catalogs of the same names. The store records the cluster_id of
the first server that opens it, and a server with another cluster_id refuses to start
(the access control store belongs to cluster ...). Replicas and restarts of the same
cluster share it as before. To share users, roles and grants between clusters on purpose,
set rbac_store_shared: true on the clusters that join. A server with no cluster_id
opens any store, with a warning when the store belongs to a cluster.
RBAC and instrumentation store formats
Hardcharger 2.14 records a format separately in each enabled store: 2.0 for RBAC and
1.1 for instrumentation. In RBAC, the schema_version key lives in hardcharger_rbac.meta. In instrumentation, it lives
in store_metadata in the configured instrumentation schema. For the default DuckDB
instrumentation file an administrator can read it with:
SELECT value FROM _hardcharger_instr.main.store_metadata WHERE key = 'schema_version';
A missing or NULL version in an existing store means format 1.0. Released RBAC stores
spell it 1. Writable startup migrates the store in place and records its new version
after the migration succeeds. The read-only credential verifier leaves the RBAC
store unchanged. Hardcharger 2.14 refuses an unsupported format and reports which
store needs attention.
Hardcharger 2.13 and earlier refuse an RBAC store that 2.14 has upgraded (the access control store's schema is version 2, newer than this server's (1)). They would otherwise run on it
without 2.14's sign-in protections and fail to create users. Back up the RBAC store before
upgrading if you may need to return to 2.13: a rollback means restoring that backup. The RBAC data_version continues to track changes to grants
and accounts independently of the schema version.
Users from the identity provider
A newly auto-provisioned account stores the verified issuer and subject from its sign-in token
on its RBAC user row. The issuer and subject must both be present. An administrator can also
link an existing account explicitly. Linking preserves the password, grants and ownership.
An administrator can give an SSO user a password with the usual ALTER USER … WITH PASSWORD.
ALTER USER "[email protected]" SET IDENTITY PROVIDER 'https://id.example.com' SUBJECT '00u123abc';
SELECT name, idp_issuer, idp_subject
FROM hardcharger_users()
WHERE enabled AND has_sso_link AND has_password;
The provider fields and has_sso_link are visible to the administrator and sessions acting as
System Admin. Existing users start with NULL provider fields. An SSO sign-in whose name (the
token's email, else sub) matches an enabled, unlinked user signs in as that user, as in 2.13.
Hardcharger records the token's issuer and subject on the account only when the provider vouches
for the name: the email claim matched and the token says email_verified: true (or the string
"true"), or the token has no email claim and its sub is exactly the user's name. Any other
match, such as an unverified email, signs in and records nothing, so a later trustworthy sign-in
can still link the account. Once linked, SSO sign-ins for that name must present the same pair.
The existing password and grants continue to work. A read-only credential check leaves the link
for the first actual sign-in. While the RBAC store is unreachable, nothing is recorded: an
unlinked user signs in from the last snapshot and the link is recorded at a later sign-in, while a
linked user is still held to its pair.
Only the administrator, or a session acting as System Admin, links an account or changes its
link (the ALTER USER privilege does not). To move a user to a new
provider or subject (an identity-provider migration, a wrong first link), set the new pair: it
replaces the old one, and is refused when another user already has that pair. To clear the link,
so that the next trustworthy SSO sign-in records a pair again:
ALTER USER "[email protected]" UNSET IDENTITY PROVIDER;
Each change is an ALTER USER record in the access-control audit chain (SSO identity linked or
SSO identity unlinked) and reaches the other replicas like any other account change. Sessions
the user already has are not ended: disable the user too if they should be. The first writable 2.14 server adds the columns
in place to an existing DuckDB or PostgreSQL RBAC store. Run 2.14 on all replicas before relying on the links.
Earlier DuckDB-store writers use positional inserts and cannot create users on the expanded schema.
Under access control, a sign-in token (token_exchange, browser sign-in, or the token sent as
user token's password) signs in a user of the store, the administrator role aside: an
administrator creates them first (CREATE USER "[email protected]", no password needed), or a
first sign-in is refused with user … is not defined on this server. An administrator creates it with CREATE USER. With token_auto_provision_users: true, the first sign-in creates the user
instead:
token_allowed_issuer: https://login.example.com/oauth2/default
token_allowed_audience: hardcharger
token_auto_provision_users: true
# token_auto_provision_issuer: defaults to token_allowed_issuer
- Only a verified token from
token_auto_provision_issuer(defaulttoken_allowed_issuer) thattoken_authorized_emailsadmits provisions, and only for the rolesuserandreadonly; anadmintoken signs in as an administrator, as before, and creates nothing. - The user is named as the token's user always is (
email, elsesub), has no password and no grants (onlyPUBLIC's), and gets the token's role in itsprovisioned_roleattribute. Grant it roles (GRANT analyst TO USER "[email protected]"), or map its identity-provider groups to roles (CREATE GROUP MAPPING). - A user provisioned from a
readonlytoken signs in readonly with every token from then on, whatever role later tokens carry, until an administrator lifts it withALTER USER "[email protected]" UNSET ATTRIBUTE provisioned_role. A readonly session runs no access-control statement butSHOW …andSET ROLE, so it can't mint itself a scoped token (which signs in as a user). - A user that exists is never changed: a disabled one stays disabled and is refused. A name that
is a role's, the administrator's, or a tenant's user (
acme/pat) in a tenant that doesn't exist is refused. - First sign-ins of the same user on several replicas at once all succeed (the store serializes
them); the user is created once, and each creation is an audit record (
provisioned a user on its first sign-in, with the user, the issuer and the role) in the access-control audit chain.
Startup refuses token_auto_provision_users without rbac_store_uri, without a way to verify
tokens (token_signature_verify_cert_path, token_jwks_uri, or token_allowed_issuer with
token_allowed_audience), or with a token_auto_provision_issuer other than
token_allowed_issuer (whose tokens alone sign in, so it would provision no one). With no
token_allowed_issuer, tokens of any issuer the key verifies sign in, and only
token_auto_provision_issuer's provision.
Read-only sessions
Clients may request the Chargewire connection option read_only: true, independently
of the sign-in token's role. The server confirms the restriction in the session's
options. It is one-way for that session: open a new connection to write again. Ordinary
connections remain read-write subject to the user's existing permissions. The CLI
requests this mode with --read-only; drivers expose their corresponding read-only
connection properties. An older server that does not support the option refuses an
explicit request rather than silently opening a writable connection.
This mode permits queries and metadata while refusing changes to data, temporary
objects, access-control grants, and other sessions. Refusals use Chargewire read_only
and SQLSTATE 25006. Prepared statements are checked at execution, including those
prepared before the connection became read-only. Hardcharger's monitoring tables remain
available with their existing permissions. The session may change its own
hardcharger.query_timeout, hardcharger.idle_in_transaction_session_timeout,
hardcharger.session_tag, and hardcharger.query_tag; global settings, client-selected
profiling changes, KILL SESSION, and administrative mutation functions are refused.
Server-configured instrumentation continues to record reads.
Read-only mode is not a sandbox for administrator-installed extensions or scalar
functions with external side effects. It uses an explicit list of permitted operations
and table functions; unsupported operations are refused even if a particular use would
only read. A statement is refused before DuckDB looks anything of it up when it holds what
DuckDB would evaluate while it binds (a function call as the argument of a table function,
also under EXPLAIN), a PRAGMA outside the supported list, or EXPLAIN of a statement
the connection cannot run, with exceptions for COPY ... TO and CALL. DuckDB enforces the
same sequence and table-function restrictions when it binds views and macros. Commit or roll
back an open transaction that holds work before switching the connection to read-only. The
existing token role below remains available with its existing behavior.
A sign-in token whose role is readonly gives a session that reads and changes nothing but
itself, with or without an access-control store. It may run queries (SELECT, EXPLAIN,
SHOW, DESCRIBE, SUMMARIZE, PIVOT, the PRAGMAs that read such as table_info and
database_list) and the statements that change only its own session: transactions
(BEGIN, START TRANSACTION, COMMIT, END, ROLLBACK, ABORT), SET VARIABLE and
RESET VARIABLE, USE, and SET / RESET of a DuckDB setting kept for the session
(SET SESSION default_order = 'desc', SET TimeZone = '…', SET search_path = '…').
Everything else is refused with User '<name>' has a readonly session and cannot run statements that modify state.: INSERT, UPDATE, DELETE, MERGE, bulk ingest, CREATE
(temporary tables, views and macros too), ALTER, DROP, COPY either way, EXPORT,
IMPORT, CHECKPOINT, VACUUM, ATTACH, DETACH, INSTALL, LOAD, CALL, SQL-level
PREPARE / EXECUTE, SET GLOBAL, a plain SET of a setting whose default scope is global
(SET default_order), and settings that reach the server (threads, memory_limit,
enable_profiling, profiling_output, the extension and secret settings, ...). DuckDB's own
analysis of each statement decides what writes, so a write hidden in a query
(WITH c AS (INSERT … RETURNING *) SELECT * FROM c, EXPLAIN ANALYZE of one), in a
transaction, in a batch or in a prepared statement is refused too. Under access control a
readonly token adds this to the user's grants: it never widens them.
🌐 Browser sign-in (SSO)
People can sign in with your OpenID Connect identity provider in a browser: Chargewire's
oauth_browser flow, on the server's own port and TLS. The hardcharger client
(--auth-type external), the drivers and the web UI all use it. Hardcharger is the
provider's confidential client: the client id and secret stay on the server, and clients get
Hardcharger's own access token, never the provider's tokens.
token_allowed_issuer: https://login.example.com/oauth2/default # found through its OpenID configuration
token_allowed_audience: hardcharger # the ID tokens' audience (the client id)
token_authorized_emails: ["*@example.com"]
token_default_role: user
oauth_client_id: hardcharger
# oauth_client_secret: from HARDCHARGER_OAUTH_CLIENT_SECRET, not the file
oauth_base_url: https://db.example.com # this server's public URL
oauth_provider_name: Okta # "Sign in with Okta"
Register <oauth_base_url>/chargewire/v1/auth/oauth/callback with the identity provider as the
client's redirect URI (here https://db.example.com/chargewire/v1/auth/oauth/callback; the server logs
the one it uses at startup). oauth_redirect_uri overrides it. Earlier builds had a separate
sign-in port (31339, /oauth/callback): that port and its options are gone, so a redirect URI
registered for it must be replaced.
| Option | Default | Meaning |
|---|---|---|
oauth_client_id |
none | Set: browser sign-in is offered (needs token_allowed_issuer and token_allowed_audience) |
oauth_client_secret |
none | The client secret (prefer HARDCHARGER_OAUTH_CLIENT_SECRET) |
oauth_scopes |
openid profile email |
|
oauth_base_url |
http(s)://localhost:PORT |
The server's public URL, for the redirect URI; set, the web UI's return after sign-in is an absolute URL on it |
oauth_redirect_uri |
<oauth_base_url>/chargewire/v1/auth/oauth/callback |
The redirect URI, given whole |
oauth_provider_name |
none | The provider's name for people; without it the UI says "single sign-on" |
oauth_instance_id |
none | Starts every state with <id>., for a proxy on another origin that receives the provider's redirects for several servers and forwards each to its server's callback (set oauth_redirect_uri to the proxy and oauth_base_url to the server) |
oauth_max_flows |
10000 |
Sign-ins in progress at once (also at most 100 per client address); beyond, 429 |
The server sends the provider a code request with state, PKCE (S256) and a nonce, exchanges
the code itself, and signs the user in with the ID token exactly as token_exchange would:
the provider's JWKS, issuer, audience, token_authorized_emails, roles and, under access
control, the store's users (created on first sign-in with token_auto_provision_users). A sign-in is collected once by the client that started it, with a
secret that is never in a URL; sign-ins expire after 10 minutes. hardcharger_server_info()
has oauth_enabled.
A link to the web UI can start the browser sign-in itself: https://db.example.com/ui/?sign_in=browser
(any page under /ui/) goes straight to the identity provider, as if Sign in with
had been clicked, and comes back signed in. The page does it once, only when the server offers
browser sign-in and nobody is signed in in that tab; it takes the parameter out of the address
bar first, so a reload, Back or a failed sign-in doesn't go to the provider again, and a failure
shows the sign-in page with the reason. The flow is still the person's own, in their tab, and
the provider still asks them to sign in or confirm.
Add read_only=1 (/ui/?sign_in=browser&read_only=1, or /ui/?read_only=1 for the password
form) to tick the sign-in page's Start sessions read-only: the person's editor sessions then
open read-only, confirmed by the server. It is a default for their sessions, not a restriction
of their account (they can still choose a writable session); the parameter leaves the address
bar at once, and the choice survives the trip to the identity provider in that tab.
Object lifetimes and access-control records
Dropping a schema removes its grants, ownership and policy bindings, including those on
nested schemas and their objects. Table/view renames carry object grants, ownership and
policy bindings to the new name; permissions are installed before the renamed object can
be exposed. An existing name used with CREATE ... IF NOT EXISTS retains its owner.
Creating a new object first removes stale records for that name, and fails if that cleanup
cannot reach the access-control store.
For ownership rows left by older versions, DROP USER and DROP ROLE check whether each
owned object still exists. Confirmed missing objects in attached catalogs no longer block
the operation. Detached catalogs and failed lookups are treated as unknown: attach the
catalog and retry, or transfer ownership of existing objects. No new table needs to be
created merely to remove a stale owner record.
Who can do what
SHOW GRANTS answers for one user or role. To query, join and filter grants, use the
table functions below. They read the copy of the store the server already holds, and each
one returns only the rows the caller may see:
| Function | Rows |
|---|---|
hardcharger_grants() |
Object, column and system privileges, plus ownerships: grantee, privilege, object, grantor, grant option, tenant |
hardcharger_role_members() |
Who holds each role: users, roles, and identity-provider groups (CREATE GROUP MAPPING) |
hardcharger_roles(), hardcharger_users() |
Names and attributes that aren't secret (never a password hash or a token); a user's last_sign_in_at and failed_sign_ins for the administrator and for the user itself |
hardcharger_policies() |
Row policies and column masks, with their expressions and whether they apply to you |
hardcharger_effective_privileges([user_name]) |
What you hold after role inheritance, ownership, SET ROLE and a scoped token's limits, and the role each privilege comes from |
-- joe: what can I do, and which role gives it to me?
SELECT privilege, object_type, schema_name, object_name, column_name, via
FROM hardcharger_effective_privileges();
privilege | object_type | schema_name | object_name | column_name | via
SELECT | TABLE | crm | users | email | analyst
SELECT | TABLE | crm | users | signup_ts | analyst
SELECT | VIEW | published | daily | NULL | analyst
SELECT | SCHEMA | analytics | NULL | NULL | analyst
With a second role as well (CREATE ROLE finance; GRANT SELECT ON crm.users TO finance; GRANT finance TO ann;):
-- The administrator: who may read crm.users?
SELECT grantee, privilege, column_name FROM hardcharger_grants()
WHERE schema_name = 'crm' AND object_name = 'users';
grantee | privilege | column_name
finance | SELECT | NULL
analyst | SELECT | email
analyst | SELECT | signup_ts
The same query as joe returns only the two analyst rows. The administrator sees
everything, and hardcharger_effective_privileges('ann') answers for any user. A user sees
grants to the roles it holds (directly, inherited, or through its sign-in token's groups),
the memberships that give it those roles, those roles, its own user row, and policies on
tables it can see. It never sees another user's grants, whatever it filters or counts. A
tenant admin (holding its tenant's tenant_admin role) also sees everything of its own tenant:
its users, roles, memberships, grants and policies, and its users' effective privileges, and
nothing of another tenant's. An
administrator token with catalog_access rules sees grants, ownerships and policies only
on objects in the catalogs its rules reach, and no users or memberships. On a server without
an access-control store, every function returns no rows.
DuckDB's information_schema can't be extended, so the SQL standard's privilege views live
in the server's read-only system catalog, under _hardcharger_system.hardcharger_information_schema:
table_privileges, column_privileges, role_table_grants, applicable_roles and
enabled_roles. They keep the standard's column names (grantor, grantee,
table_catalog, table_schema, table_name, privilege_type, is_grantable, …), and a
schema or catalog grant appears once for each table and view in it. A tool that reads
information_schema.table_privileges reads the same columns under this qualified name.
They follow the same visibility rules:
SELECT grantee, table_schema, table_name, privilege_type
FROM _hardcharger_system.hardcharger_information_schema.table_privileges ORDER BY ALL;
grantee | table_schema | table_name | privilege_type
analyst | analytics | orders | SELECT
analyst | published | daily | SELECT
🔏 Client certificates as identity
With mutual TLS (mtls_ca_cert), a client can sign in with its certificate and no
password: Chargewire's client_certificate grant, --auth-type mtls in the hardcharger
client. The certificate proves who the user is; grants decide what they may do.
tls_cert: /etc/hardcharger/server.pem
tls_key: /etc/hardcharger/server.key
mtls_ca_cert: /etc/hardcharger/client-ca.pem # client certificates are verified against it
mtls_certificate_sign_in: true # off by default: certificates only admit connections
mtls_identity_source: san_email # or san_uri (SPIFFE IDs), subject_cn
mtls_admin_identities: [[email protected]] # sign in as the administrator
mtls_crl_file: /etc/hardcharger/client-ca.crl # revocation, reloaded when it changes
| Option | Default | Meaning |
|---|---|---|
mtls_certificate_sign_in |
false |
Offer certificate sign-in at all. Off, mtls_ca_cert only admits connections, and the grant is answered unsupported_grant_type |
mtls_require_client_cert |
true |
Refuse connections without a certificate at the handshake; false lets them connect and sign in another way |
mtls_identity_source |
san_email |
Which part of the certificate is the identity. A certificate with none, or several, values of that kind is refused |
mtls_admin_identities |
none | Identities that sign in as the administrator. Under access control, any other identity must be a user of the store (CREATE USER "[email protected]", a password optional); without it, no other identity signs in |
mtls_crl_file |
none | PEM CRLs, one for every CA of a client's chain (the root's too): every certificate of the chain is checked, so a revoked intermediate revokes what it issued, and a CA without a CRL is refused. A revoked certificate is refused at the handshake. The file is looked at every 5 seconds and reloaded when it changes, and open connections are checked again then and when a CRL passes its nextUpdate (an expired CRL refuses everything) |
mtls_crl_allow_missing_ca_crls |
false |
Accept a CA above the leaf that has no CRL in the file |
mtls_require_identity_match |
false |
A password or token sign-in over a client certificate must be for the certificate's identity |
A browser page on another origin (one of cors_origins) can sign in with the user's
certificate too: allowed origins get Access-Control-Allow-Credentials: true, and the page
calls with credentials: "include" (@gizmodata/chargewire does with authType: "client_certificate"). The browser's CORS preflight carries no credentials and may come
without a certificate, so for such pages set mtls_require_client_cert: false: the
handshake then admits the preflight, and the sign-in still needs the certificate. Pages on
the server's own origin (the embedded UI) send no preflight and need neither.
Tokens from a certificate sign-in are bound to it (RFC 8705's cnf claim): they work only on
connections presenting the same certificate, so a copied token is no use without the private
key. A session opened with such a token, and any scoped token minted from it, stay bound to the
same certificate (a session takes only tokens bound as its opener's was, and a bound session
can't mint scoped tokens FOR USER someone else). Identities are printable ASCII. Every refusal
(a bound token on the wrong connection, another identity's sign-in, a revoked certificate, an
unknown identity) is a security warning in the log and an audit record, with the user, the
token's id, the certificate presented and the client's address. They are rate-limited per source (ten a minute
in full, then one summary that counts the rest), a connection is closed after five failed
sign-ins, and certificates the TLS handshake refuses (revoked, expired, untrusted) are
recorded too. Identities match user names as user names compare (ignoring ASCII case), except URI identities such as
SPIFFE IDs, whose paths are case-sensitive: they must match exactly, case included. Under access
control a SPIFFE ID is a user name like any other:
CREATE USER "spiffe://example.org/ns/etl/sa/loader" (always system scope, never a tenant's).
Of several CRLs from one CA the newest is used; delta CRLs are refused. TLS has to end at Hardcharger (a TCP or TLS-passthrough load balancer) for this; a
proxy that ends TLS takes the certificate with it. Sign-ins with a certificate are written to
the audit log (kind: authentication, method: client_certificate, the identity and the
certificate's thumbprint).
🏗️ Architecture
flowchart LR
subgraph Clients
A[ADBC: Go, Python, C, R, Rust]
J[JDBC: Java, BI tools]
H[Any HTTP client]
end
subgraph Hardcharger
W[Chargewire SDK<br/>HTTP/1.1 + TLS, sessions,<br/>Arrow IPC streaming]
S[Security<br/>sign-in, RBAC, audit]
D[(DuckDB 2.0)]
end
A & J & H -- "Chargewire: HTTP + Arrow IPC" --> W
W --> S --> D
S -. users, roles, grants .-> P[(PostgreSQL)]
D -. instrumentation, logs .-> L[(DuckDB / PostgreSQL)]
🛠️ Build from source
git clone --recurse-submodules https://github.com/gizmodata/hardcharger.git
cd hardcharger/server
./scripts/build-deps.sh # DuckDB 2.0, Arrow C++ and replxx, pinned
OPENSSL_ROOT_DIR=$(brew --prefix openssl@3) cmake -S . -B build -G Ninja
cmake --build build
To embed the web UI, build it first (Node 24 or later) and point the server's build at the tarball it makes:
(cd ../ui && npm ci && npm run build && npm run package) # ui/release/hardcharger-ui-<version>.tar.gz
cmake -S . -B build -G Ninja -DHARDCHARGER_WEB_UI="$(ls "$PWD"/../ui/release/hardcharger-ui-*.tar.gz)"
cmake --build build
CMake checks every file against the tarball's MANIFEST, gzips each one into the binary and
logs the build's content SHA-256. ui/README.md covers the UI's own checks and
its browser tests.
🧪 Test
docker compose -f server/tests/docker-compose.yml up -d --wait # PostgreSQL + S3 for the DuckLake suites
docker run -d --name hardcharger-test-pg -e POSTGRES_USER=hardcharger \
-e POSTGRES_PASSWORD=hardcharger -e POSTGRES_DB=hardcharger \
-p 127.0.0.1:55433:5432 postgres:17-alpine # the access-control store
cd server/tests
uv venv .venv && uv pip install --python .venv/bin/python -r pyproject.toml
.venv/bin/python -m pytest -q # -m "not services" without Docker
# -m "not web_ui" on a build without the UI
The Chargewire conformance suite runs against the same build:
cd third_party/chargewire/conformance
uv venv .venv && uv pip install --python .venv/bin/python -e .
CHARGEWIRE_TEST_SERVER_BINARY=../../../server/build/hardcharger-server \
CHARGEWIRE_TEST_SERVER_PASSWORD_ENV=HARDCHARGER_ADMIN_PASSWORD \
CHARGEWIRE_TEST_SERVER_USERNAME=chargewire HARDCHARGER_ADMIN_USERNAME=chargewire \
CHARGEWIRE_TEST_SERVER_MTLS_FLAG=--mtls-ca-cert CHARGEWIRE_TEST_SERVER_CORS_FLAG=--cors-origins \
CHARGEWIRE_TEST_SERVER_IDLE_FLAG=--session-idle-timeout \
CHARGEWIRE_TEST_SERVER_DRAIN_FLAG=--shutdown-grace-period-seconds \
.venv/bin/python -m pytest -q
Its access-control tests (test_authorization.py) need the CHARGEWIRE_TEST_AUTHZ_* variables
that .github/workflows/server.yml sets (a DuckDB access-control store, privileges granted to a
role); without them they skip, saying so.
The access-control suites run on PostgreSQL by default; HARDCHARGER_TEST_RBAC_STORE=duckdb .venv/bin/python -m pytest -q -m rbac_store runs them again on the DuckDB file store, as CI does.
The web UI's lint, typecheck, unit and browser tests (Chromium and WebKit, against a server build that embeds it) are in ui/README.md.
The client's 1.x shell script runs on its own too (bash server/tests/test_client_shell.sh).
Suites that need PostgreSQL or the S3 gateway fail, never skip, when those aren't there.
BATTERY.md tracks GizmoSQL's test battery as ported, file by file.
🔁 Coming from GizmoSQL
Hardcharger takes only its own names: HARDCHARGER_* variables, hardcharger_* SQL
functions, _hardcharger_* catalogs. docs/migrating-from-gizmosql.md
maps every GizmoSQL name to its Hardcharger name.
💬 Community and support
- Chat with us in the GizmoData Community Slack.
- Report bugs and ask for features in GitHub issues.
- Run it on GizmoData Cloud, fully managed on AWS, Google Cloud or Azure: start free and launch a Hardcharger cluster in minutes, with nothing to install.
- For support plans, write to [email protected].
📄 License
Apache License 2.0; see LICENSE.
The binaries contain third-party open-source software, each part under its own licence:
THIRD_PARTY_NOTICES.md lists every statically linked library (DuckDB
and what it vendors, its built-in extensions, Arrow, Boost, OpenSSL and the rest) with its version
and full licence text. The embedded web UI's JavaScript packages are listed in
THIRD_PARTY_NOTICES-web-ui.txt. Every release archive, the MSI and the container image
(/usr/share/doc/hardcharger/) carry both files, hardcharger-server --licenses and
hardcharger --licenses print them, and the web UI links its own from About (Open-source
licences). The tpch extension's data generator (built in on iOS) is under the TPC's End User
License Agreement, not an open-source licence.

Built by GizmoData™
Hardcharger™ and GizmoData™ are trademarks of GizmoData LLC.
App Store is a service mark of Apple Inc. Google Play and the Google Play logo are trademarks of Google LLC.
Explorer des projets similaires
Chargement…