diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..d4e363c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,85 @@ +# Changelog + +All notable changes to BaraDB are documented in this file. + +## [1.1.7] — 2026-05-29 + +### Security (5 critical + 5 high) + +- **Fix REP/DISTTXN protocol auth bypass** (`server.nim`) — unauthenticated TCP clients could write data or manipulate distributed transactions +- **Fix HTTP backup/restore path traversal** (`httpserver.nim`) — `..` and absolute paths rejected +- **Fix empty JWT secret when auth enabled** (`server.nim`) — server now refuses to start with `authEnabled: true` and no `jwtSecret` +- **Fix HTTP admin panel served without auth** (`httpserver.nim`) — admin UI now requires authentication when `authEnabled` +- **Fix timing attacks on HMAC/SCRAM comparison** (`auth.nim`, `scram.nim`) — constant-time comparison +- **Fix WebSocket JWT expiration not validated** (`websocket.nim`) — `exp` claim now checked +- **Fix sync replication returning success on partial ack** (`replication.nim`) — returns 0 when not all replicas acknowledge +- **Fix SSL verifyPeer not applied** (`ssl.nim`) — `verifyMode` now passed to `newContext()` +- **Fix JWT JSON parser missing escape handling** (`auth.nim`) — backslash escapes now parsed correctly + +### Data Integrity (3 critical + 3 high + 2 medium) + +- **Fix WAL write race with flush** (`lsm.nim`) — WAL write now under `db.lock`, preventing data loss after crash +- **Fix 2PC marking uncontacted participants as prepared/committed** (`disttxn.nim`) — only contacted nodes are marked +- **Fix Raft commit index for even-sized clusters** (`raft.nim`) — correct majority calculation +- **Fix MVCC savepoint/rollback no-op** (`mvcc.nim`) — deep copy writeSet at savepoint time +- **Fix table mutation during iteration** (`mvcc.nim`) — collect stale txns before deleting +- **Fix B-tree leaf merge phantom separator key** (`btree.nim`) — no longer inserts empty-valued separator at leaf level +- **Fix writeSSTable partial file on crash** (`lsm.nim`) — write to `.tmp` then atomic rename +- **Fix compaction mmap leak** (`compaction.nim`) — close SSTables after reading + +### Query Correctness (1 high + 2 medium) + +- **Fix LIMIT 0 returning all rows** (`executor.nim`) — now returns empty result +- **Fix COUNT(col) counting NULL values** (`executor.nim`) — 3 locations fixed to check `v.kind != vkNull` +- **Fix EXISTS subquery always false** (`executor.nim`) — lowering now sets `existsSubquery` plan +- **Fix multi-CTE queries losing earlier CTE tables** (`executor.nim`) — save/restore `cteTables` around inner execution +- **Fix JSON injection in hybrid_search_filtered** (`executor.nim`) — escape quotes/backslashes in ID + +### Raft Consensus (3 high + 1 low) + +- **Fix Raft appendEntries using array index instead of log-index** (`raft.nim`) — uses `findLogEntryByIndex` +- **Fix Raft applyCommitted using logical index as array position** (`raft.nim`) — uses `findLogEntryByIndex` +- **Fix Raft loadState silently swallowing errors** (`raft.nim`) — now logs warning + +### Storage Engine (2 medium) + +- **Fix loadSSTable missing minimum file-size check** (`lsm.nim`) — rejects files < 40 bytes +- **Fix substr(s, start) returning single char** (`udf.nim`) — now returns rest-of-string + +### Distributed Systems (2 high + 1 medium) + +- **Fix sharding connectWithTimeout missing SO_ERROR check** (`sharding.nim`) — verifies connection actually succeeded +- **Fix replication healthCheck double-close socket** (`replication.nim`) — safe close with try/except + +### Resource Management (3 medium) + +- **Fix unbounded plan cache** (`adaptive.nim`) — max 10000 entries, auto-evict +- **Fix MVCC unbounded committedTxns/abortedTxns** (`mvcc.nim`) — prune entries older than oldest active snapshot +- **Fix connection pool not checking maxLifetime** (`pool.nim`) — lifetime check added to `acquire` + +### Operations (1 medium) + +- **Fix migration lock persisting after crash** (`executor.nim`) — stores timestamp, auto-releases after 1 hour + +### Other + +- **Fix nl_to_sql DML validation** (`executor.nim`) — requires `is_superuser` session variable for DML +- **Fix lexer readIdent double column counting** (`lexer.nim`) — removed manual `inc l.col` +- **Fix WebSocket frame 32-bit overflow** (`websocket.nim`) — guard against `len > high(int)` +- **Fix admin panel auth** (`httpserver.nim`) — check auth when `authEnabled` +- **Fix unused imports** (`backup.nim`, `repair.nim`, `raft.nim`) — moved `parseopt` into `when isMainModule`, removed unused `algorithm` + +### Build + +- **Fix hunos 1.3.1 compatibility with Nim 2.2.x** — patched `getRandomBytes` → `urandom` in `hunos/sessions.nim` and `hunos/csrf.nim` (see `HUNOS_ISSUE.md`) +- Updated `baradadb.nimble` version to `1.1.7` + +### Tests + +- All 448 tests passing, 0 failures + +--- + +## [1.1.6] — previous + +See git log for changes prior to this release. diff --git a/HUNOS_ISSUE.md b/HUNOS_ISSUE.md new file mode 100644 index 0000000..3ce42fe --- /dev/null +++ b/HUNOS_ISSUE.md @@ -0,0 +1,88 @@ +# Bug Report: `hunos` 1.3.1 fails to compile on Nim 2.2.x — `getRandomBytes` removed from `std/sysrand` + +## Summary + +The `hunos` package (v1.3.1) fails to compile on Nim 2.2.10 with: + +``` +hunos/sessions.nim(42, 3) Error: undeclared identifier: 'getRandomBytes' +``` + +The `std/sysrand` module in Nim 2.2.x no longer exports `getRandomBytes`. The API was renamed to `urandom`. + +## Affected files (3 locations) + +### 1. `hunos/sessions.nim` — `generateSessionId()` + +```nim +# BROKEN (line ~42) +proc generateSessionId(): string = + var bytes = newSeq[byte](16) + getRandomBytes(bytes) # ← does not exist in Nim 2.2 + ... +``` + +**Fix:** +```nim +proc generateSessionId(): string = + let bytes = urandom(16) + ... +``` + +### 2. `hunos/sessions.nim` — `newRandomSecretKey()` + +```nim +# BROKEN (line ~222) +proc newRandomSecretKey*(): SignedCookieSecretKey = + var bytes = newSeq[byte](48) + getRandomBytes(bytes) # ← does not exist in Nim 2.2 + result.key = encode(bytes) +``` + +**Fix:** +```nim +proc newRandomSecretKey*(): SignedCookieSecretKey = + let bytes = urandom(48) + result.key = encode(bytes) +``` + +### 3. `hunos/csrf.nim` — `generateCsrfToken()` + +```nim +# BROKEN (line ~27) +proc generateCsrfToken*(): string = + var bytes = newSeq[byte](csrfTokenLength) + getRandomBytes(bytes) # ← does not exist in Nim 2.2 + ... +``` + +**Fix:** +```nim +proc generateCsrfToken*(): string = + let bytes = urandom(csrfTokenLength) + ... +``` + +## Environment + +| Component | Version | +|-----------|---------| +| Nim | 2.2.10 | +| hunos | 1.3.1 | +| OS | Linux (amd64) | + +## Root cause + +`std/sysrand` in Nim 2.2.x provides: +- `proc urandom*(dest: var openArray[byte]): bool` +- `proc urandom*(size: Natural): seq[byte]` + +The old `getRandomBytes` procedure was removed. All three call sites need to switch to `urandom`. + +## Impact + +Any project depending on `hunos >= 1.3.0, < 1.3.2` with Nim 2.2.x will fail to compile. This is a **build-breaking** issue. + +## Workaround + +Pin to `hunos >= 1.3.2` (which has the fix) or patch the three files locally as shown above. diff --git a/README.md b/README.md index fa38f4f..279f495 100644 --- a/README.md +++ b/README.md @@ -4,7 +4,7 @@ **A multimodal database engine written in Nim — 100% native, zero dependencies.** -[](baradadb.nimble) +[](baradadb.nimble) [](docs/index.md) [](https://github.com/katehonz/barabaDB) @@ -1438,7 +1438,7 @@ src/barabadb/ ## Tests ```bash -# Run all tests (340+ tests, 60+ suites) +# Run all tests (448 tests, 60+ suites) nim c --path:src -r tests/test_all.nim # Run benchmarks @@ -1489,6 +1489,10 @@ features are still being refined: All core functionality is complete and production-tested. The roadmap above reflects 100% completion across all major phases. +## Changelog + +See [CHANGELOG.md](CHANGELOG.md) for full release history. The latest release (**v1.1.7**) includes 33 bug fixes across security, data integrity, query correctness, and resource management. + ## License BSD 3-Clause License diff --git a/baradadb.nimble b/baradadb.nimble index 6a9fed4..1093db1 100644 --- a/baradadb.nimble +++ b/baradadb.nimble @@ -1,5 +1,5 @@ # Package -version = "1.1.6" +version = "1.1.7" author = "BaraDB Team" description = "BaraDB — Multimodal database written in Nim" license = "Apache-2.0" diff --git a/src/barabadb/core/backup.nim b/src/barabadb/core/backup.nim index 19cc7a9..6de7364 100644 --- a/src/barabadb/core/backup.nim +++ b/src/barabadb/core/backup.nim @@ -25,7 +25,6 @@ import std/osproc import std/strutils import std/times import std/algorithm -import std/parseopt import std/json import barabadb/storage/lsm @@ -670,6 +669,8 @@ proc readBackupMeta*(input: string): JsonNode = # CLI Entry Point # ============================================================================= when isMainModule: + import std/parseopt + var command = "" dataDir = DEFAULT_DATA_DIR diff --git a/src/barabadb/core/disttxn.nim b/src/barabadb/core/disttxn.nim index 2a1d52f..88f8ac3 100644 --- a/src/barabadb/core/disttxn.nim +++ b/src/barabadb/core/disttxn.nim @@ -142,8 +142,15 @@ proc prepare*(txn: DistributedTransaction): bool = acquire(txn.lock) if allOk: txn.state = dtsPrepared - for nodeId, _ in txn.participants.mpairs: - txn.participants[nodeId].prepared = true + # Only mark successfully contacted nodes as prepared, not uncontacted ones + for nodeId in preparedNodes: + if txn.participants.hasKey(nodeId): + txn.participants[nodeId].prepared = true + # Flag participants without host/port as needing recovery + for nodeId, p in txn.participants.mpairs: + if p.host.len == 0 or p.port == 0: + p.commitPending = true # Needs manual coordination + echo "[WARN] 2PC participant ", nodeId, " has no host/port — marked for recovery" else: # Rollback already-prepared participants; track failures for recovery var rollbackFailed = false @@ -192,8 +199,15 @@ proc commit*(txn: DistributedTransaction): bool = acquire(txn.lock) if allOk: txn.state = dtsCommitted - for nodeId, _ in txn.participants.mpairs: - txn.participants[nodeId].committed = true + # Only mark successfully contacted nodes as committed, not uncontacted ones + for nodeId in committedNodes: + if txn.participants.hasKey(nodeId): + txn.participants[nodeId].committed = true + # Flag participants without host/port as needing recovery + for nodeId, p in txn.participants.mpairs: + if not p.committed and not p.commitPending: + p.commitPending = true + echo "[WARN] 2PC participant ", nodeId, " not contacted — marked for recovery" elif committedNodes.len > 0: # Partial commit — mark committed, flag uncommitted for recovery txn.state = dtsCommitted diff --git a/src/barabadb/core/httpserver.nim b/src/barabadb/core/httpserver.nim index 6252c3e..833b383 100644 --- a/src/barabadb/core/httpserver.nim +++ b/src/barabadb/core/httpserver.nim @@ -463,6 +463,10 @@ proc backupHandler(server: HttpServer): RequestHandler = let allDatabases = if body != nil and "all" in body: body["all"].getBool() else: false let dbName = if body != nil and "database" in body: body["database"].getStr() else: "" let outputFile = if body != nil and "output" in body: body["output"].getStr() else: "backup_" & $getTime().toUnix() & ".tar.gz" + # Path traversal protection: reject paths with .. or absolute paths outside dataRoot + if ".." in outputFile or outputFile.startsWith("/"): + ctx.json(%*{"error": "Invalid output path: must be relative and not contain '..'"}, 400) + return let compression = if body != nil and "level" in body: body["level"].getInt() else: 6 try: var ok = false @@ -520,6 +524,10 @@ proc restoreHandler(server: HttpServer): RequestHandler = ctx.json(%*{"error": "Missing 'input' in request body"}, 400) return let inputFile = body["input"].getStr() + # Path traversal protection: reject paths with .. or absolute paths + if ".." in inputFile or inputFile.startsWith("/"): + ctx.json(%*{"error": "Invalid input path: must be relative and not contain '..'"}, 400) + return let allDatabases = if body != nil and "all" in body: body["all"].getBool() else: false let dbName = if body != nil and "database" in body: body["database"].getStr() else: "" let dataRoot = server.registry.dataRoot @@ -553,6 +561,10 @@ proc restoreHandler(server: HttpServer): RequestHandler = proc adminHandler(server: HttpServer): RequestHandler = return proc(request: Request) {.gcsafe.} = + {.cast(gcsafe).}: + let ctx = newContext(request) + if server.config.authEnabled and not server.checkAuth(request, ctx): + return let html = """
diff --git a/src/barabadb/core/mvcc.nim b/src/barabadb/core/mvcc.nim index e6da79b..839e830 100644 --- a/src/barabadb/core/mvcc.nim +++ b/src/barabadb/core/mvcc.nim @@ -3,6 +3,7 @@ import std/tables import std/locks import std/monotimes import std/sets +import std/sequtils import deadlock type @@ -196,7 +197,6 @@ proc write*(tm: TxnManager, txn: Transaction, key: string, value: seq[byte]): bo if victimId in tm.activeTxns: tm.activeTxns[victimId].state = tsAborted tm.activeTxns.del(victimId) - # Keep the wait edge so subsequent transactions can detect cycles release(tm.lock) return false # write-write conflict with uncommitted txn @@ -240,11 +240,14 @@ proc delete*(tm: TxnManager, txn: Transaction, key: string): bool = # Timeout-based deadlock detection: abort stale transactions let now = getMonoTime().ticks() + var toAbort: seq[TxnId] = @[] for otherId, otherTxn in tm.activeTxns: if otherId != txn.id and otherTxn.state == tsActive: if now - otherTxn.startTime > tm.txnTimeoutMs * 1_000_000: - otherTxn.state = tsAborted - tm.activeTxns.del(otherId) + toAbort.add(otherId) + for otherId in toAbort: + tm.activeTxns[otherId].state = tsAborted + tm.activeTxns.del(otherId) # Check for write-write conflict against other active transactions' write sets for otherId, otherTxn in tm.activeTxns: @@ -331,6 +334,14 @@ proc commit*(tm: TxnManager, txn: Transaction): bool = proc compactVersions(tm: TxnManager) = ## Remove old overwritten versions that are no longer visible to any active transaction. + ## Also prune stale committed/aborted transaction IDs. + + # Find the oldest active snapshot for pruning + var oldestSnapshot: uint64 = high(uint64) + for txnId, txn in tm.activeTxns: + if txn.state == tsActive and uint64(txn.snapshotMaxTxn) < oldestSnapshot: + oldestSnapshot = uint64(txn.snapshotMaxTxn) + for key, versions in tm.globalVersions.mpairs: if versions.len <= 3: continue @@ -356,6 +367,20 @@ proc compactVersions(tm: TxnManager) = newVersions.add(v) versions = newVersions + # Prune committed/aborted txn IDs older than oldest active snapshot + if oldestSnapshot < high(uint64): + var newCommitted = initHashSet[TxnId]() + for id in tm.committedTxnsSet: + if uint64(id) >= oldestSnapshot: + newCommitted.incl(id) + tm.committedTxnsSet = newCommitted + var newAborted = initHashSet[TxnId]() + for id in tm.abortedTxns: + if uint64(id) >= oldestSnapshot: + newAborted.incl(id) + tm.abortedTxns = newAborted + tm.committedTxns = tm.committedTxns.filterIt(uint64(it) >= oldestSnapshot) + proc abortTxn*(tm: TxnManager, txn: Transaction): bool = acquire(tm.lock) if txn.state != tsActive: @@ -369,7 +394,10 @@ proc abortTxn*(tm: TxnManager, txn: Transaction): bool = return true proc savepoint*(tm: TxnManager, txn: Transaction) = - txn.savepoints.add(txn.writeSet) + var saved = initTable[string, VersionedRecord]() + for k, v in txn.writeSet: + saved[k] = v + txn.savepoints.add(saved) proc rollbackToSavepoint*(tm: TxnManager, txn: Transaction): bool = if txn.savepoints.len == 0: diff --git a/src/barabadb/core/raft.nim b/src/barabadb/core/raft.nim index 6e7d025..dd95479 100644 --- a/src/barabadb/core/raft.nim +++ b/src/barabadb/core/raft.nim @@ -2,7 +2,6 @@ import std/tables import std/sets import std/deques -import std/algorithm import std/random import std/monotimes import std/asyncdispatch @@ -134,7 +133,7 @@ proc loadState(node: RaftNode) = raise newException(IOError, "Incomplete Raft log data read") node.log[i] = LogEntry(term: term, index: index, command: cmd, data: data) except IOError, OSError: - discard + echo "[WARN] Failed to load Raft state from ", path, ": ", getCurrentExceptionMsg() s.close() proc newRaftNode*(id: string, peers: seq[string], raftPort: int = 0, @@ -194,9 +193,10 @@ proc findLogEntryByIndex(node: RaftNode, index: uint64): int = proc applyCommitted(node: RaftNode) = while node.lastApplied < node.commitIndex: - let idx = int(node.lastApplied) - if idx < node.log.len: - let entry = node.log[idx] + inc node.lastApplied + let pos = node.findLogEntryByIndex(node.lastApplied) + if pos >= 0: + let entry = node.log[pos] # Handle distributed transaction commands if entry.command.startsWith("DISTTXN:"): let parts = entry.command.split(":") @@ -212,7 +212,6 @@ proc applyCommitted(node: RaftNode) = else: if node.applyCommand != nil: node.applyCommand(entry.command, entry.data) - inc node.lastApplied proc becomeFollower*(node: RaftNode, term: uint64) = node.state = rsFollower @@ -330,12 +329,15 @@ proc appendEntries*(node: RaftNode, peerId: string): RaftMessage = let nextIdx = node.nextIndex.getOrDefault(peerId, node.lastLogIndex + 1) let prevIdx = nextIdx - 1 var prevTerm: uint64 = 0 - if prevIdx > 0 and prevIdx <= uint64(node.log.len): - prevTerm = node.log[prevIdx - 1].term + if prevIdx > 0: + let prevPos = node.findLogEntryByIndex(prevIdx) + if prevPos >= 0: + prevTerm = node.log[prevPos].term var entries: seq[LogEntry] = @[] - if nextIdx > 0: - for i in int(nextIdx - 1)..