Skip to content

About

RNovModularDB is a modular Rust database engine for secure embedded and edge workloads. It combines a SQL execution engine with encrypted single-file storage, explicit memory/disk synchronization, transaction primitives, authorization, row policies, column encryption, audit chains, full-text search, and sandboxed WebAssembly scalar functions.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

444 Commits

Folders and files

Repository files navigation

RNovModularDB

RNovModularDB is a modular Rust database engine for secure embedded and edge workloads. It combines a SQL execution engine with encrypted single-file storage, explicit memory/disk synchronization, transaction primitives, authorization, row policies, column encryption, audit chains, full-text search, and sandboxed WebAssembly scalar functions.

The workspace separates common types, SQL parsing and binding, catalogs, storage, transactions, indexes, planning, execution, full-text search, UDFs, security, instance isolation, embedded runtimes, server support, and CLI tooling into focused crates.

Status

RNovModularDB 1.0 is the first supported production release for controlled embedded and edge deployments. Public Rust APIs follow semantic versioning, and the version 2 encrypted single-file format is the stable durable format for the 1.x release line. It is not a drop-in replacement for SQLite or PostgreSQL, and operators remain responsible for keys, backups, transport security, and deployment access controls.

Implemented product surfaces include:

  • In-memory and encrypted durable LocalSession SQL engines.
  • Explicit BEGIN, COMMIT, and ROLLBACK handling with atomic state rollback.
  • General INNER JOIN and LEFT JOIN execution using hash or nested-loop plans.
  • IN, NOT IN, EXISTS, NOT EXISTS, and scalar subqueries, including supported correlated forms.
  • Single-column foreign keys and AFTER INSERT, AFTER UPDATE, and AFTER DELETE SQL triggers.
  • FLOAT64, TIMESTAMP, UUID, and validated JSON values in addition to integer, text, bytes, array, range, hstore, and text-vector types.
  • B-tree, hash, inverted, range/GiST, summary/BRIN, and multidimensional bounds indexing, with full-text operators integrated into planning and execution.
  • Wasmtime-backed scalar UDF execution with import denial, fuel, epoch, memory, result-size, and module-cache limits.
  • Encrypted single-file inspection, verification, backup, restore, explicit version 1 to version 2 upgrade, authenticated version 2 page-key rotation, and cross-process file coordination.
  • A bounded TCP line protocol for embedded deployments.

Build And Test

RNovModularDB requires Rust 1.95 or newer.

cargo check --workspace
cargo test --workspace
cargo test --workspace --all-features
cargo clippy --workspace --all-targets --all-features -- -D warnings

Run the rnmdb binary without arguments to execute a bounded SQL script from standard input in a temporary in-memory session. Script boundaries are parsed with the SQL lexer, so semicolons inside strings, line comments, block comments, trigger bodies, and procedure bodies are not treated as statement separators:

printf "CREATE TABLE items (id INT64, name TEXT); SELECT id FROM items;" \
  | cargo run -q -p rnmdb-cli --bin rnmdb

Use the explicit run command for scripts from a file or for durable SQL. A durable run requires a page key and checkpoints each successful autocommit change before reporting it as successful:

cargo run -q -p rnmdb-cli --bin rnmdb -- \
  run --memory --file schema.sql

cargo run -q -p rnmdb-cli --bin rnmdb -- \
  run --database data/app.rnmdb \
  --page-key-file /secure/page-key.hex \
  --file migrations/001-bootstrap.sql

When SQL is read from standard input, use --page-key-env or --page-key-file. --page-key-stdin is accepted only with --file, so key material and SQL can never compete for the same input stream. A script that ends with an active transaction is rolled back and exits with an error.

Run rnmdb help for command usage and rnmdb version for the installed version.

Storage CLI

Inspect or structurally verify a single-file database:

cargo run -q -p rnmdb-cli --bin rnmdb -- inspect path/to/database.rnmdb
cargo run -q -p rnmdb-cli --bin rnmdb -- verify path/to/database.rnmdb

Authenticated inspection and verification require a page key. Keys are never accepted as command-line values. Read a 64-character hexadecimal key, with an optional 0x prefix and one optional LF or CRLF terminator, from a protected file or standard input:

cargo run -q -p rnmdb-cli --bin rnmdb -- \
  verify --page-key-file /secure/page-key.hex path/to/database.rnmdb

cargo run -q -p rnmdb-cli --bin rnmdb -- \
  inspect --page-key-stdin path/to/database.rnmdb < /secure/page-key.hex

--page-key-env reads the fixed RNMDB_PAGE_KEY_HEX environment variable. Standard input or a permission-restricted file is preferable where environment variables may be exposed to process inspection or inherited by child processes. The legacy --page-key-hex option is rejected.

Back up and restore a database:

cargo run -q -p rnmdb-cli --bin rnmdb -- \
  backup path/to/database.rnmdb path/to/database.backup.rnmdb
cargo run -q -p rnmdb-cli --bin rnmdb -- \
  restore --dry-run path/to/database.backup.rnmdb path/to/restored.rnmdb
cargo run -q -p rnmdb-cli --bin rnmdb -- \
  restore path/to/database.backup.rnmdb path/to/restored.rnmdb

Upgrade a version 1 single-file database into a new version 2 target:

cargo run -q -p rnmdb-cli --bin rnmdb -- \
  upgrade path/to/legacy-v1.rnmdb path/to/upgraded-v2.rnmdb
cargo run -q -p rnmdb-cli --bin rnmdb -- \
  upgrade --page-key-file /secure/page-key.hex \
  path/to/legacy-v1.rnmdb path/to/upgraded-v2.rnmdb

The upgrade never modifies the source and refuses an existing target. The library-level SingleFileUpgradeOptions API can use separate source and target keys for key rotation.

Rotate the page key of an existing version 2 database through the embedded storage API while the database is offline:

use std::path::Path;

use rnmdb_storage::{PageCryptoKey, rekey_single_file};

fn rotate_page_key(
    path: &Path,
    old_key: PageCryptoKey,
    fresh_key: PageCryptoKey,
) -> rnmdb_common::Result<()> {
    let report = rekey_single_file(path, old_key, fresh_key)?;
    assert!(report.key_rotated());
    Ok(())
}

rekey_single_file authenticates every source page with the old key, writes and verifies a same-directory temporary database with the fresh key, then atomically replaces the original pathname. It rejects a target key equal to the current source key, symbolic or hard-linked sources, and live local backends. The file format does not track historical key identities, so other processes must be quiesced and callers must supply a key that has never been used for this database's page-nonce domain.

Embedded API

Use LocalSession::memory for temporary execution:

use rnmdb_cli::{CommandOutput, LocalSession};

fn run() -> rnmdb_common::Result<()> {
    let mut session = LocalSession::memory()?;
    session.execute("CREATE TABLE items (id INT64, name TEXT);")?;
    session.execute("INSERT INTO items (id, name) VALUES (1, 'alpha');")?;

    if let CommandOutput::Rows(rows) = session.execute("SELECT id, name FROM items;")? {
        println!("{:?}", rows.rows());
    }
    Ok(())
}

Use LocalSession::single_file_with_key for durable SQL state. Call checkpoint after autocommit changes; a successful explicit transaction COMMIT checkpoints a durable session automatically.

use std::path::Path;

use rnmdb_cli::LocalSession;
use rnmdb_storage::PageCryptoKey;

fn write_event(path: &Path, page_key: PageCryptoKey) -> rnmdb_common::Result<()> {
    let mut session = LocalSession::single_file_with_key(path, page_key)?;
    session.execute("CREATE TABLE events (id INT64, payload TEXT);")?;
    session.execute("INSERT INTO events (id, payload) VALUES (1, 'created');")?;
    session.checkpoint()?;
    Ok(())
}

Column encryption requires the embedder to provide column key material through LocalSession::configure_column_encryption. Column keys are not persisted with the database and must be reinjected after reopening a session.

LocalSession::memory_parallel and LocalSession::memory_with_execution configure local parallel execution. The optional tokio-runtime feature adds Tokio wrappers without coupling the storage core to a specific async executor.

TCP Server

rnmdb_server::SqlTcpServer exposes an embedded, newline-delimited protocol. It supports optional local credential authentication and applies the authenticated catalog role to authorization and column decryption. The server limits active clients, command size, and socket I/O time, and isolates client errors from the accept loop.

The rnmdbd binary provides an operational entry point. It binds to 127.0.0.1:7432 by default, requires authentication unless --allow-unauthenticated is explicit, and refuses non-loopback listeners unless the operator explicitly accepts the unencrypted transport with --allow-remote-plaintext:

cargo run -q -p rnmdb-server --bin rnmdbd -- \
  serve --database data/app.rnmdb \
  --page-key-file /secure/page-key.hex \
  --auth-user app \
  --auth-password-file /secure/app-password.txt

Use --auth-role-id <ID> to bind the credential to an existing catalog role. Omitting it creates an authenticated administrative connection. Passwords and page keys are never accepted as command-line values. --shutdown-on-stdin stops accepting after one stdin line or EOF, signals active clients, and uses a bounded five-second graceful drain period; embedded hosts can call SqlTcpServer::serve_until with their own shutdown signal.

Production limits can be set without rebuilding the server:

rnmdbd serve --memory --allow-unauthenticated \
  --max-clients 128 \
  --max-command-bytes 262144 \
  --client-io-timeout-ms 15000 \
  --graceful-drain-timeout-ms 10000 \
  --forced-drain-timeout-ms 2000

The defaults remain 64 clients, 65,536 command bytes, a 30-second client I/O timeout, a five-second graceful drain, and a one-second forced drain. The library equivalent is SqlTcpServer::bind_with_options with a validated SqlServerOptions; SqlTcpServer::bind retains these defaults. Configured client counts are capped at 4,096 and SQL command sizes at 16 MiB to prevent an accidental configuration from removing the server's admission boundary. The SQL limit may be as small as one byte; bounded protocol control commands use a separate limit sized for the documented credential boundaries. Usernames are limited to 256 UTF-8 bytes and cannot contain whitespace or control characters. Passwords are limited to 4,096 UTF-8 bytes, must fit on one line, and cannot start or end with whitespace. Client I/O and drain timeouts must be greater than zero and no longer than 24 hours.

Each connection has independent authentication and transaction state, while all connections share one committed database state. Autocommit changes become visible to later commands and connections after a successful durable checkpoint. Explicit transactions publish atomically at COMMIT; if another connection committed since BEGIN, the commit is rejected with a transaction conflict and the client can roll back and retry. PING returns OK pong without authentication for local health checks, and QUIT closes a session after rolling back any active transaction.

Protocol version 3 adds unauthenticated HELLO capability discovery and version-range negotiation. HELLO selects the latest server version, while HELLO <MIN> <MAX> selects the highest common version or returns an error without closing the connection. Its stable key-value response contains only protocol capabilities, authentication policy, and configured admission limits. It does not expose database state or runtime metrics.

Protocol version 2 adds STATUS. In authenticated deployments it is available only after AUTH; unauthenticated deployments can use it directly. A client that negotiates protocol version 1 receives a version error for STATUS. The single-line response reports lifecycle, database health, runtime mode, authentication policy, active clients, committed generation, and the same process-local counters exposed by SqlServerHandle::metrics. This keeps PING as the minimal anonymous liveness probe while reserving operational detail for an authenticated session. failed_client_sessions counts every client handler that returns an error, including setup, protocol, I/O, and session-close failures.

Embedded service managers can retain SqlTcpServer::management_handle before moving the server into a worker thread. The cloneable handle reports protocol limits, active connections, authentication and storage mode, the process-local committed generation, and whether an indeterminate durable commit requires a restart. It can also request shutdown of SqlTcpServer::serve; the server then uses the same bounded drain path as serve_until.

Management status also reports the lifecycle as Idle, Serving, ShuttingDown, or Stopped. is_ready is true only while the accept loop is serving and the shared database is available. Status collection can briefly block on database synchronization and is a best-effort view rather than an atomic reservation. A server admits only one accept loop at a time and cannot be restarted after shutdown; create and bind a new server for a clean restart. The same handle exposes a lock-free metrics snapshot with current active clients and monotonic counters for accepted, capacity-rejected, and completed clients, received commands, and client handlers that returned setup, protocol, I/O, or session-close errors. These counters are process-local and saturate instead of wrapping.

This protocol is not PostgreSQL, MySQL, or SQLite wire compatible. It is a small operational interface for controlled embedded deployments, not a general database proxy protocol. It does not provide TLS; expose it remotely only behind an authenticated encrypted tunnel or a transport-security terminator.

SQL Support

Supported statement families include:

  • CREATE TABLE, ALTER TABLE ADD COLUMN, column encryption changes, DROP TABLE, single-column REFERENCES, and table-level single-column FOREIGN KEY declarations.
  • CREATE INDEX, CREATE UNIQUE INDEX, DROP INDEX, CREATE TRIGGER, and DROP TRIGGER.
  • CREATE FUNCTION, CREATE PROCEDURE, CALL, CREATE OPERATOR, roles, grants, row policies, and their corresponding drop statements.
  • INSERT, UPDATE, DELETE, and SELECT with filtering, grouping, grouping sets, ROLLUP, CUBE, ordering, limits, windows, and set operations.
  • INNER JOIN, LEFT JOIN, restricted JOIN LATERAL, recursive CTEs, expression subqueries, and explain output.

Supported scalar types are BOOL, INT64/BIGINT/INTEGER, UINT64, FLOAT64/DOUBLE PRECISION, TEXT/VARCHAR, BYTES/BYTEA, TIMESTAMP, UUID, JSON/JSONB, HSTORE, TEXTVECTOR/TSVECTOR, arrays, and ranges.

Important SQL limits include no DECIMAL/NUMERIC, RIGHT JOIN, FULL JOIN, generated columns, or PostgreSQL-compatible procedural language. JSON values are validated and persistable, but a complete JSON operator and path-query surface is not provided.

Storage Compatibility

The encrypted single-file format uses SINGLE_FILE_FORMAT_VERSION = 2. Opening, inspection, verification, backup, restore, and upgrade reject unknown versions rather than attempting partial decoding.

  • Version 1 files can be detected and explicitly upgraded to version 2.
  • Version 2 files can be re-encrypted in place with a fresh page key through an offline, verified atomic replacement.
  • Upgrade and restore create new targets and never overwrite existing files.
  • Backup sources are held under a shared OS file lock for inspection and copy.
  • Writes, sync, checkpoints, restore targets, and upgrade targets use exclusive file locks and process-local cursor serialization.
  • Backend operations remain attached to the originally opened file handle if a pathname is renamed or replaced.
  • Page records use authenticated encryption and checksums; keyed verification authenticates and decodes every present page.
  • Memory-to-disk checkpoint export requires an explicit page encryption key.

Storage mode reports distinguish metadata-only switching, pre-synchronized switching, and full data movement. Millisecond switching is only claimed for metadata-only or already synchronized state changes.

Security Model

Security-sensitive primitives use reviewed Rust crates:

  • Argon2 for local credential password hashing.
  • ChaCha20-Poly1305 for page encryption, column values, and wrapped keys.
  • HMAC-SHA256 for wrapped-key authentication metadata.
  • SHA-256 hash chains for tamper-evident audit records.
  • Operating-system randomness for salts and generated secret material.

RBAC grants, active roles, row policies, foreign keys, triggers, and configured column encryption are enforced in the local execution path. Audit verification detects insertion, deletion, reordering, sequence gaps, instance mismatch, and digest tampering within an inspected chain.

Page keys, column keys, credential lifecycle, backups, and deployment access remain the embedder's responsibility. RNovModularDB does not include a KMS, certificate authority, replication layer, or high-availability coordinator.

License

RNovModularDB is licensed under the Aperip Heimdall Commons License 1.2. AHCL includes source and history disclosure duties for internal use, builds, deployment, network operation, modified versions, and dependent projects. See LICENSE and the complete AHCL notice set.

Separate commercial licenses are available from licensing@aperip.com. Contact information does not itself grant a commercial license or change the AHCL terms.

About

RNovModularDB is a modular Rust database engine for secure embedded and edge workloads. It combines a SQL execution engine with encrypted single-file storage, explicit memory/disk synchronization, transaction primitives, authorization, row policies, column encryption, audit chains, full-text search, and sandboxed WebAssembly scalar functions.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Contributors

Languages