main.cpp 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607
  1. #include <smartbotic/database/client.hpp>
  2. #include <nlohmann/json.hpp>
  3. #include "storage/subdb_placement.hpp"
  4. #include <openssl/bio.h>
  5. #include <openssl/bn.h>
  6. #include <openssl/err.h>
  7. #include <openssl/evp.h>
  8. #include <openssl/pem.h>
  9. #include <openssl/rand.h>
  10. #include <openssl/x509.h>
  11. #include <openssl/x509v3.h>
  12. #include <arpa/inet.h>
  13. #include <fcntl.h>
  14. #include <sys/random.h>
  15. #include <sys/stat.h>
  16. #include <unistd.h>
  17. #include <algorithm>
  18. #include <cerrno>
  19. #include <cstdio>
  20. #include <cstring>
  21. #include <fstream>
  22. #include <iterator>
  23. #include <chrono>
  24. #include <iostream>
  25. #include <sstream>
  26. #include <string>
  27. #include <vector>
  28. using json = nlohmann::json;
  29. namespace {
  30. struct Args {
  31. std::string address = "localhost:9004";
  32. // v2.11.0 T6b — needed to exercise relation management against a
  33. // non-default project from the CLI. Empty means the client's own
  34. // "default" (unchanged behaviour for every existing command).
  35. std::string project;
  36. std::string command;
  37. std::vector<std::string> params;
  38. };
  39. // ANSI colors
  40. constexpr auto C_RESET = "\033[0m";
  41. constexpr auto C_BOLD = "\033[1m";
  42. constexpr auto C_DIM = "\033[2m";
  43. constexpr auto C_CYAN = "\033[36m";
  44. constexpr auto C_GREEN = "\033[32m";
  45. constexpr auto C_RED = "\033[31m";
  46. constexpr auto C_YELLOW = "\033[33m";
  47. void printJson(const json& j) {
  48. std::cout << j.dump(2) << "\n";
  49. }
  50. void printError(const std::string& msg) {
  51. std::cerr << C_RED << "error: " << C_RESET << msg << "\n";
  52. }
  53. void printUsage() {
  54. std::cout << C_BOLD << "smartbotic-db-cli" << C_RESET << " — admin tool for smartbotic-database\n\n"
  55. << C_BOLD << "Usage:" << C_RESET << "\n"
  56. << " smartbotic-db-cli [--address HOST:PORT] <command> [args...]\n"
  57. << " smartbotic-db-cli [--address HOST:PORT] " << C_DIM << "# interactive mode" << C_RESET << "\n\n"
  58. << C_BOLD << "Commands:" << C_RESET << "\n"
  59. << " " << C_CYAN << "collections" << C_RESET << " List all collections\n"
  60. << " " << C_CYAN << "info" << C_RESET << " <collection> Collection info\n"
  61. << " " << C_CYAN << "find" << C_RESET << " <collection> List documents\n"
  62. << " " << C_DIM << "[--limit N] [--offset N] [--exists FIELD] [--eq FIELD VALUE]" << C_RESET << "\n"
  63. << " " << C_CYAN << "get" << C_RESET << " <collection> <id> Get a document\n"
  64. << " " << C_CYAN << "upsert" << C_RESET << " <collection> <id> '<json>' Insert or update\n"
  65. << " " << C_CYAN << "remove" << C_RESET << " <collection> <id> Delete a document\n"
  66. << " " << C_CYAN << "count" << C_RESET << " <collection> Count documents\n"
  67. << " " << C_CYAN << "lock" << C_RESET << " Lock database (read-only)\n"
  68. << " " << C_CYAN << "unlock" << C_RESET << " Unlock database (accept writes)\n"
  69. << " " << C_CYAN << "status" << C_RESET << " Show read-only + recovery status\n"
  70. << " " << C_CYAN << "server-info" << C_RESET << " Server version, commit and feature names (2.15.0+)\n"
  71. << " " << C_CYAN << "configure" << C_RESET << " <collection> [--versioning on|off] [--max-versions N]\n"
  72. << " " << C_DIM << "versioning off stops NEW history; --max-versions N prunes existing history to the newest N" << C_RESET << "\n"
  73. << " " << C_DIM << "per document (writes recording history in that collection wait while it runs)" << C_RESET << "\n"
  74. << " " << C_CYAN << "encryption-verify" << C_RESET << " [collection] Audit encryption at rest (exit 1 on any finding).\n"
  75. << " Against a 2.17.0 SERVER it stalls history-recording writes\n"
  76. << " server-wide while it reads history; 2.17.1+ does not.\n"
  77. << C_BOLD << " Collection schema (v2.16.0+)" << C_RESET << "\n"
  78. << " " << C_CYAN << "schema" << C_RESET << " <collection> Show the schema, mode and counters\n"
  79. << " " << C_CYAN << "schema-set" << C_RESET << " <collection> <json|@file> [--audit]\n"
  80. << " " << C_DIM << "existing rows are checked first; enforce refuses if any violates it" << C_RESET << "\n"
  81. << " " << C_CYAN << "schema-drop" << C_RESET << " <collection> Remove the schema\n"
  82. << " " << C_CYAN << "schema-suggest" << C_RESET << " <collection> [limit] Suggest a schema from the rows\n"
  83. << C_BOLD << " Access policy (v2.7.0+)" << C_RESET << "\n"
  84. << " " << C_CYAN << "security" << C_RESET << " [project] Show whether a project enforces policy\n"
  85. << " " << C_CYAN << "indexes" << C_RESET << " <collection>"
  86. << " list secondary indexes\n"
  87. << " " << C_CYAN << "index-create" << C_RESET << " <collection> <field>"
  88. << " declare an index and backfill it\n"
  89. << " " << C_DIM << "[--unique] also enforce uniqueness; refused, with examples, if duplicates exist"
  90. << C_RESET << "\n"
  91. << " " << C_CYAN << "index-drop" << C_RESET << " <collection> <field>"
  92. << " remove an index\n"
  93. << " " << C_CYAN << "unique-create" << C_RESET << " <collection> <field> <field> [...]"
  94. << " Composite unique constraint\n"
  95. << " " << C_CYAN << "unique-drop" << C_RESET << " <collection> <field> <field> [...]"
  96. << " Drop a composite unique constraint\n"
  97. << " " << C_CYAN << "index-values" << C_RESET << " <coll> <field> [n] [asc|desc]"
  98. << " distinct values + counts\n"
  99. << C_BOLD << " Relations / referential integrity (v2.11.0+)" << C_RESET << "\n"
  100. << " " << C_CYAN << "relations" << C_RESET
  101. << " List declared relations (every project; --project narrows)\n"
  102. << " " << C_CYAN << "relation" << C_RESET << " <name>"
  103. << " Show one relation's declaration\n"
  104. << " " << C_CYAN << "relation-create" << C_RESET
  105. << " <name> <child> <child_field> <parent> [on_delete] [validate_on_write]\n"
  106. << " " << C_CYAN << "relation-drop" << C_RESET << " <name>\n"
  107. << " " << C_CYAN << "relation-check" << C_RESET << " <name>"
  108. << " Report dangling references (read-only)\n"
  109. << " " << C_CYAN << "configure-relations" << C_RESET
  110. << " <collection> [on|off] Show, or enable/disable, enforcement for a collection\n"
  111. << " " << C_CYAN << "describe-delete" << C_RESET << " <collection> <id>"
  112. << " What would happen if this document were deleted\n"
  113. << " " << C_CYAN << "security-set" << C_RESET << " <project> <on|off> [enforce|audit]\n"
  114. << " " << C_CYAN << "policies" << C_RESET << " [project] List principals with a policy\n"
  115. << " " << C_CYAN << "policy" << C_RESET << " <project> <principal> Show one policy\n"
  116. << " " << C_CYAN << "policy-set" << C_RESET << " <project> <principal> '<json>'\n"
  117. << " " << C_CYAN << "policy-rm" << C_RESET << " <project> <principal>\n"
  118. << " " << C_CYAN << "help" << C_RESET << " Show this help\n\n"
  119. << C_BOLD << "Offline helpers" << C_RESET << " " << C_DIM << "(no server connection required)" << C_RESET << ":\n"
  120. << " " << C_CYAN << "generate-auth-key" << C_RESET << " Emit a base64 32-byte API key\n"
  121. << " " << C_CYAN << "generate-tls-cert" << C_RESET << " --bind <addr> Generate a self-signed TLS cert + key\n"
  122. << " " << C_DIM << "[--out-cert PATH] [--out-key PATH] [--days N]" << C_RESET << "\n"
  123. << " " << C_CYAN << "verify-subdbs" << C_RESET << " --env <path> Report documents filed under the wrong collection\n"
  124. << " " << C_DIM << "[--project NAME] read-only; safe against a running server" << C_RESET << "\n"
  125. << " " << C_CYAN << "reconcile-subdbs" << C_RESET << " --env <path> Repair misfiled documents (dry run by default)\n"
  126. << " " << C_DIM << "[--project NAME] [--apply] STOP THE SERVICE and back up before --apply" << C_RESET << "\n\n"
  127. << C_BOLD << "Options:" << C_RESET << "\n"
  128. << " --address HOST:PORT Database address (default: localhost:9004)\n"
  129. << " --project NAME Operate as this project namespace (default: default)\n"
  130. << " --version Print version and build commit, then exit\n";
  131. }
  132. // ---------------------------------------------------------------------------
  133. // v2.4 Stage F: offline helpers (no server connection required)
  134. // ---------------------------------------------------------------------------
  135. // Base64-encode raw bytes. Uses OpenSSL's EVP_EncodeBlock which emits the
  136. // standard base64 alphabet (no newlines) and pads with '='.
  137. std::string base64Encode(const unsigned char* data, size_t len) {
  138. if (len == 0) return {};
  139. // EVP_EncodeBlock writes ((len + 2) / 3) * 4 bytes + a NUL terminator.
  140. const size_t out_len = 4 * ((len + 2) / 3);
  141. std::string out(out_len, '\0');
  142. int written = EVP_EncodeBlock(
  143. reinterpret_cast<unsigned char*>(out.data()),
  144. data, static_cast<int>(len));
  145. if (written < 0) return {};
  146. out.resize(static_cast<size_t>(written));
  147. return out;
  148. }
  149. // Pull 32 cryptographically random bytes from getentropy() (preferred) or
  150. // /dev/urandom (fallback). Returns true on success.
  151. bool fillRandomBytes(unsigned char* buf, size_t len) {
  152. // getentropy() is limited to 256 bytes per call; our use-case is 32.
  153. if (len <= 256) {
  154. if (getentropy(buf, len) == 0) return true;
  155. }
  156. // Fallback: /dev/urandom.
  157. int fd = ::open("/dev/urandom", O_RDONLY | O_CLOEXEC);
  158. if (fd < 0) return false;
  159. size_t got = 0;
  160. while (got < len) {
  161. ssize_t n = ::read(fd, buf + got, len - got);
  162. if (n <= 0) {
  163. if (errno == EINTR) continue;
  164. ::close(fd);
  165. return false;
  166. }
  167. got += static_cast<size_t>(n);
  168. }
  169. ::close(fd);
  170. return true;
  171. }
  172. int cmdGenerateAuthKey() {
  173. unsigned char key[32];
  174. if (!fillRandomBytes(key, sizeof(key))) {
  175. std::fprintf(stderr, "error: failed to obtain entropy for key\n");
  176. return 1;
  177. }
  178. auto encoded = base64Encode(key, sizeof(key));
  179. if (encoded.empty()) {
  180. std::fprintf(stderr, "error: base64 encoding failed\n");
  181. return 1;
  182. }
  183. std::cout << encoded << "\n";
  184. return 0;
  185. }
  186. namespace {
  187. // Print the topmost OpenSSL error to stderr with a prefix.
  188. void printOpenSslError(const char* prefix) {
  189. unsigned long e = ERR_get_error();
  190. char buf[256] = {0};
  191. if (e != 0) {
  192. ERR_error_string_n(e, buf, sizeof(buf));
  193. std::fprintf(stderr, "error: %s: %s\n", prefix, buf);
  194. } else {
  195. std::fprintf(stderr, "error: %s\n", prefix);
  196. }
  197. }
  198. // Returns true if `s` parses as an IPv4 or IPv6 literal.
  199. bool looksLikeIp(const std::string& s) {
  200. unsigned char buf[16];
  201. if (inet_pton(AF_INET, s.c_str(), buf) == 1) return true;
  202. if (inet_pton(AF_INET6, s.c_str(), buf) == 1) return true;
  203. return false;
  204. }
  205. // Generate an RSA private key as an EVP_PKEY using the modern (3.x) API.
  206. EVP_PKEY* generateRsaKey(int bits) {
  207. EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr);
  208. if (!ctx) return nullptr;
  209. EVP_PKEY* pkey = nullptr;
  210. if (EVP_PKEY_keygen_init(ctx) <= 0) {
  211. EVP_PKEY_CTX_free(ctx);
  212. return nullptr;
  213. }
  214. if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, bits) <= 0) {
  215. EVP_PKEY_CTX_free(ctx);
  216. return nullptr;
  217. }
  218. if (EVP_PKEY_keygen(ctx, &pkey) <= 0) {
  219. EVP_PKEY_CTX_free(ctx);
  220. return nullptr;
  221. }
  222. EVP_PKEY_CTX_free(ctx);
  223. return pkey;
  224. }
  225. // Write a string to disk with the given file mode. Truncates existing files.
  226. bool writeFileWithMode(const std::string& path, const std::string& contents, mode_t mode) {
  227. int fd = ::open(path.c_str(),
  228. O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
  229. mode);
  230. if (fd < 0) {
  231. std::fprintf(stderr, "error: open %s: %s\n", path.c_str(), std::strerror(errno));
  232. return false;
  233. }
  234. // Re-assert mode in case the file pre-existed with a wider mode and
  235. // O_CREAT was a no-op (open(2) only applies the mode on create).
  236. if (fchmod(fd, mode) != 0) {
  237. std::fprintf(stderr, "error: fchmod %s: %s\n", path.c_str(), std::strerror(errno));
  238. ::close(fd);
  239. return false;
  240. }
  241. size_t off = 0;
  242. while (off < contents.size()) {
  243. ssize_t n = ::write(fd, contents.data() + off, contents.size() - off);
  244. if (n <= 0) {
  245. if (errno == EINTR) continue;
  246. std::fprintf(stderr, "error: write %s: %s\n", path.c_str(), std::strerror(errno));
  247. ::close(fd);
  248. return false;
  249. }
  250. off += static_cast<size_t>(n);
  251. }
  252. if (::close(fd) != 0) {
  253. std::fprintf(stderr, "error: close %s: %s\n", path.c_str(), std::strerror(errno));
  254. return false;
  255. }
  256. return true;
  257. }
  258. // Serialize an X509* to a PEM string.
  259. std::string pemEncodeCert(X509* cert) {
  260. BIO* bio = BIO_new(BIO_s_mem());
  261. if (!bio) return {};
  262. if (PEM_write_bio_X509(bio, cert) != 1) {
  263. BIO_free(bio);
  264. return {};
  265. }
  266. BUF_MEM* mem = nullptr;
  267. BIO_get_mem_ptr(bio, &mem);
  268. std::string out(mem->data, mem->length);
  269. BIO_free(bio);
  270. return out;
  271. }
  272. // Serialize an EVP_PKEY* to an unencrypted PEM string (PKCS#8 format via
  273. // PEM_write_bio_PrivateKey).
  274. std::string pemEncodeKey(EVP_PKEY* key) {
  275. BIO* bio = BIO_new(BIO_s_mem());
  276. if (!bio) return {};
  277. if (PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr, nullptr) != 1) {
  278. BIO_free(bio);
  279. return {};
  280. }
  281. BUF_MEM* mem = nullptr;
  282. BIO_get_mem_ptr(bio, &mem);
  283. std::string out(mem->data, mem->length);
  284. BIO_free(bio);
  285. return out;
  286. }
  287. } // anonymous namespace
  288. int cmdGenerateTlsCert(const std::vector<std::string>& params) {
  289. std::string bind;
  290. std::string out_cert = "./server.pem";
  291. std::string out_key = "./server.key";
  292. int days = 3650;
  293. for (size_t i = 0; i < params.size(); ++i) {
  294. const auto& p = params[i];
  295. auto need = [&](const char* flag) -> const std::string* {
  296. if (i + 1 >= params.size()) {
  297. std::fprintf(stderr, "error: %s requires a value\n", flag);
  298. return nullptr;
  299. }
  300. return &params[++i];
  301. };
  302. if (p == "--bind") {
  303. auto* v = need("--bind"); if (!v) return 2; bind = *v;
  304. } else if (p == "--out-cert") {
  305. auto* v = need("--out-cert"); if (!v) return 2; out_cert = *v;
  306. } else if (p == "--out-key") {
  307. auto* v = need("--out-key"); if (!v) return 2; out_key = *v;
  308. } else if (p == "--days") {
  309. auto* v = need("--days"); if (!v) return 2;
  310. try { days = std::stoi(*v); }
  311. catch (...) {
  312. std::fprintf(stderr, "error: --days must be an integer\n");
  313. return 2;
  314. }
  315. if (days <= 0) {
  316. std::fprintf(stderr, "error: --days must be > 0\n");
  317. return 2;
  318. }
  319. } else {
  320. std::fprintf(stderr, "error: unknown argument: %s\n", p.c_str());
  321. return 2;
  322. }
  323. }
  324. if (bind.empty()) {
  325. std::fprintf(stderr,
  326. "usage: generate-tls-cert --bind <addr> "
  327. "[--out-cert PATH] [--out-key PATH] [--days N]\n");
  328. return 2;
  329. }
  330. // 1. RSA 4096-bit key.
  331. EVP_PKEY* pkey = generateRsaKey(4096);
  332. if (!pkey) {
  333. printOpenSslError("RSA key generation failed");
  334. return 1;
  335. }
  336. // 2. X.509 certificate.
  337. X509* cert = X509_new();
  338. if (!cert) {
  339. printOpenSslError("X509_new failed");
  340. EVP_PKEY_free(pkey);
  341. return 1;
  342. }
  343. // Version 3 (the integer field encodes v3 as 2).
  344. if (X509_set_version(cert, 2) != 1) {
  345. printOpenSslError("X509_set_version failed");
  346. X509_free(cert); EVP_PKEY_free(pkey);
  347. return 1;
  348. }
  349. // Random 64-bit serial number.
  350. {
  351. unsigned char serial_bytes[8];
  352. if (RAND_bytes(serial_bytes, sizeof(serial_bytes)) != 1) {
  353. printOpenSslError("RAND_bytes for serial failed");
  354. X509_free(cert); EVP_PKEY_free(pkey);
  355. return 1;
  356. }
  357. // Mask the top bit so the BIGNUM is positive.
  358. serial_bytes[0] &= 0x7F;
  359. BIGNUM* bn = BN_bin2bn(serial_bytes, sizeof(serial_bytes), nullptr);
  360. if (!bn) {
  361. printOpenSslError("BN_bin2bn failed");
  362. X509_free(cert); EVP_PKEY_free(pkey);
  363. return 1;
  364. }
  365. ASN1_INTEGER* ai = BN_to_ASN1_INTEGER(bn, nullptr);
  366. BN_free(bn);
  367. if (!ai) {
  368. printOpenSslError("BN_to_ASN1_INTEGER failed");
  369. X509_free(cert); EVP_PKEY_free(pkey);
  370. return 1;
  371. }
  372. if (X509_set_serialNumber(cert, ai) != 1) {
  373. printOpenSslError("X509_set_serialNumber failed");
  374. ASN1_INTEGER_free(ai);
  375. X509_free(cert); EVP_PKEY_free(pkey);
  376. return 1;
  377. }
  378. ASN1_INTEGER_free(ai);
  379. }
  380. // Validity period.
  381. if (!X509_gmtime_adj(X509_get_notBefore(cert), 0)) {
  382. printOpenSslError("X509_gmtime_adj(notBefore) failed");
  383. X509_free(cert); EVP_PKEY_free(pkey);
  384. return 1;
  385. }
  386. long seconds = static_cast<long>(days) * 24L * 60L * 60L;
  387. if (!X509_gmtime_adj(X509_get_notAfter(cert), seconds)) {
  388. printOpenSslError("X509_gmtime_adj(notAfter) failed");
  389. X509_free(cert); EVP_PKEY_free(pkey);
  390. return 1;
  391. }
  392. // Public key.
  393. if (X509_set_pubkey(cert, pkey) != 1) {
  394. printOpenSslError("X509_set_pubkey failed");
  395. X509_free(cert); EVP_PKEY_free(pkey);
  396. return 1;
  397. }
  398. // Subject + issuer name (self-signed, so identical).
  399. X509_NAME* name = X509_get_subject_name(cert);
  400. if (X509_NAME_add_entry_by_txt(
  401. name, "CN", MBSTRING_UTF8,
  402. reinterpret_cast<const unsigned char*>(bind.c_str()),
  403. -1, -1, 0) != 1) {
  404. printOpenSslError("X509_NAME_add_entry_by_txt(CN) failed");
  405. X509_free(cert); EVP_PKEY_free(pkey);
  406. return 1;
  407. }
  408. if (X509_set_issuer_name(cert, name) != 1) {
  409. printOpenSslError("X509_set_issuer_name failed");
  410. X509_free(cert); EVP_PKEY_free(pkey);
  411. return 1;
  412. }
  413. // SubjectAltName.
  414. {
  415. std::string san = "DNS:localhost,IP:127.0.0.1";
  416. if (bind != "localhost" && bind != "127.0.0.1") {
  417. san += ',';
  418. san += looksLikeIp(bind) ? "IP:" : "DNS:";
  419. san += bind;
  420. }
  421. X509_EXTENSION* ext = X509V3_EXT_conf_nid(
  422. nullptr, nullptr, NID_subject_alt_name, san.c_str());
  423. if (!ext) {
  424. printOpenSslError("X509V3_EXT_conf_nid(SAN) failed");
  425. X509_free(cert); EVP_PKEY_free(pkey);
  426. return 1;
  427. }
  428. if (X509_add_ext(cert, ext, -1) != 1) {
  429. printOpenSslError("X509_add_ext(SAN) failed");
  430. X509_EXTENSION_free(ext);
  431. X509_free(cert); EVP_PKEY_free(pkey);
  432. return 1;
  433. }
  434. X509_EXTENSION_free(ext);
  435. }
  436. // basicConstraints CA:FALSE — a server leaf cert, not a CA.
  437. {
  438. X509_EXTENSION* ext = X509V3_EXT_conf_nid(
  439. nullptr, nullptr, NID_basic_constraints, "critical,CA:FALSE");
  440. if (ext) {
  441. X509_add_ext(cert, ext, -1);
  442. X509_EXTENSION_free(ext);
  443. }
  444. }
  445. // Sign with SHA-256.
  446. if (X509_sign(cert, pkey, EVP_sha256()) == 0) {
  447. printOpenSslError("X509_sign failed");
  448. X509_free(cert); EVP_PKEY_free(pkey);
  449. return 1;
  450. }
  451. // Serialize.
  452. std::string cert_pem = pemEncodeCert(cert);
  453. std::string key_pem = pemEncodeKey(pkey);
  454. X509_free(cert);
  455. EVP_PKEY_free(pkey);
  456. if (cert_pem.empty() || key_pem.empty()) {
  457. std::fprintf(stderr, "error: PEM encoding failed\n");
  458. return 1;
  459. }
  460. // Write key first (0600), then cert (0644). If either fails, the other
  461. // may have been written — that's acceptable; the operator will see the
  462. // error and retry.
  463. if (!writeFileWithMode(out_key, key_pem, 0600)) return 1;
  464. if (!writeFileWithMode(out_cert, cert_pem, 0644)) return 1;
  465. std::cout << "Wrote cert: " << out_cert << "\n"
  466. << "Wrote key: " << out_key << "\n";
  467. return 0;
  468. }
  469. bool execCommand(smartbotic::database::Client& client,
  470. const std::string& cmd, const std::vector<std::string>& params,
  471. // v2.11.1 — empty when the operator passed no --project, which
  472. // for `relations` means "every project" rather than "default".
  473. const std::string& explicitProject) {
  474. try {
  475. if (cmd == "server-info") {
  476. const auto si = client.serverInfo(true);
  477. if (!si) {
  478. std::cout << "server predates 2.15.0 (no GetServerInfo); this client is "
  479. << smartbotic::database::clientLibraryVersion() << "\n";
  480. return true;
  481. }
  482. std::cout << "server: " << si->version << " (commit " << si->commit << ")\n"
  483. << "client: " << smartbotic::database::clientLibraryVersion()
  484. << " (the server saw '" << si->clientVersionSeen << "')\n"
  485. << "features:";
  486. for (const auto& c : si->capabilities) std::cout << " " << c;
  487. std::cout << "\n";
  488. return true;
  489. }
  490. if (cmd == "encryption-verify") {
  491. const auto r = client.verifyEncryption(params.empty() ? "" : params[0]);
  492. if (!r.encryptionEnabled) {
  493. std::cout << "encryption is DISABLED on this server: nothing is encrypted at rest\n";
  494. return false;
  495. }
  496. std::cout << "at-rest migration sealed: " << (r.atRestSealed ? "yes" : "NO (restart pending)") << "\n";
  497. for (const auto& c : r.collections) {
  498. const bool bad = c.plaintextRequired || c.doubleEncrypted || c.undecryptable ||
  499. c.historyPlaintextRequired || c.historyDoubleEncrypted;
  500. std::cout << (bad ? "FAIL " : "ok ") << c.collection
  501. << (c.collectionEncrypted ? " [encrypted]" : "")
  502. << " rows " << c.rows << ", ciphertext values " << c.encryptedValues
  503. << ", plaintext-required " << c.plaintextRequired
  504. << ", double " << c.doubleEncrypted << ", undecryptable " << c.undecryptable
  505. << ", history " << c.historyVersions << " (plaintext-required "
  506. << c.historyPlaintextRequired << ", double " << c.historyDoubleEncrypted << ")\n";
  507. for (const auto& s : c.samples) std::cout << " plaintext at " << s << "\n";
  508. }
  509. // v2.17.2 - CLEAN describes the live store; while a reseal is
  510. // pending the old plaintext is still on disk (WAL, older
  511. // snapshots, LMDB free pages), so the verdict must say so rather
  512. // than read as "nothing in plaintext on this disk".
  513. if (!r.clean()) std::cout << "FINDINGS - see FAIL lines\n";
  514. else if (!r.atRestSealed) std::cout << "CLEAN (UNSEALED: old plaintext copies remain on disk until the next restart)\n";
  515. else std::cout << "CLEAN\n";
  516. return r.clean() && r.atRestSealed;
  517. }
  518. if (cmd == "schema" || cmd == "schema-drop" || cmd == "schema-suggest") {
  519. if (params.empty()) {
  520. printError("usage: " + cmd + " <collection>");
  521. return false;
  522. }
  523. if (cmd == "schema") {
  524. const auto s = client.getCollectionSchema(params[0]);
  525. if (!s) {
  526. std::cout << "no schema on " << params[0] << "\n";
  527. return true;
  528. }
  529. std::cout << "mode: " << (s->mode == smartbotic::database::Client::SchemaMode::Audit ? "audit" : "enforce")
  530. << (s->armed ? "" : " (NOT ARMED: the stored schema does not compile)") << "\n"
  531. << "refusals: " << s->refusals << " audit violations: " << s->auditViolations
  532. << " (since armed)\n"
  533. << s->schema.dump(2) << "\n";
  534. return true;
  535. }
  536. if (cmd == "schema-suggest") {
  537. const uint64_t limit = params.size() > 1 ? std::stoull(params[1]) : 0;
  538. const auto s = client.suggestCollectionSchema(params[0], limit);
  539. std::cerr << "scanned " << s.rowsScanned << " row(s)" << (s.complete ? "" : " (a sample)")
  540. << "\n";
  541. std::cout << s.schema.dump(2) << "\n";
  542. return true;
  543. }
  544. const auto r = client.removeCollectionSchema(params[0]);
  545. if (!r.success) {
  546. printError(r.error);
  547. return false;
  548. }
  549. std::cout << C_GREEN << "ok" << C_RESET << " schema removed\n";
  550. return true;
  551. }
  552. if (cmd == "schema-set") {
  553. if (params.size() < 2) {
  554. printError("usage: schema-set <collection> <json|@file> [--audit]");
  555. return false;
  556. }
  557. std::string text = params[1];
  558. if (!text.empty() && text[0] == '@') {
  559. std::ifstream in(text.substr(1));
  560. if (!in) {
  561. printError("cannot read " + text.substr(1));
  562. return false;
  563. }
  564. text.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
  565. }
  566. nlohmann::json schema;
  567. try {
  568. schema = nlohmann::json::parse(text);
  569. } catch (const std::exception& e) {
  570. printError(std::string("not valid JSON: ") + e.what());
  571. return false;
  572. }
  573. const bool audit = std::find(params.begin(), params.end(), "--audit") != params.end();
  574. const auto r = client.setCollectionSchema(params[0], schema,
  575. audit ? smartbotic::database::Client::SchemaMode::Audit : smartbotic::database::Client::SchemaMode::Enforce);
  576. std::cout << "checked " << r.rowsChecked << " existing row(s), " << r.violatingRows
  577. << " not conforming\n";
  578. for (const auto& ex : r.examples) std::cout << " " << ex.id << ": " << ex.message << "\n";
  579. if (!r.success) {
  580. printError(r.error + (r.reason.empty() ? "" : " [" + r.reason + "]"));
  581. return false;
  582. }
  583. std::cout << C_GREEN << "ok" << C_RESET << " schema set (" << (audit ? "audit" : "enforce") << ")\n";
  584. return true;
  585. }
  586. if (cmd == "collections") {
  587. auto collections = client.listCollections();
  588. std::cout << C_BOLD << "Collections:" << C_RESET << "\n";
  589. for (const auto& c : collections) {
  590. auto info = client.getCollectionInfo(c);
  591. int64_t count = 0;
  592. if (info) count = info->documentCount;
  593. std::cout << " " << C_CYAN << c << C_RESET
  594. << C_DIM << " (" << count << " docs)" << C_RESET << "\n";
  595. }
  596. return true;
  597. }
  598. // v2.18.1 - collection administration an operator could not reach
  599. // from the CLI (asked by smartbotic-vectorapi before a production
  600. // prune): versioning on/off, and maxVersions with its history prune.
  601. if (cmd == "configure") {
  602. if (params.size() < 3) {
  603. printError("usage: configure <collection> [--versioning on|off] [--max-versions N]");
  604. return false;
  605. }
  606. const std::string coll = params[0];
  607. std::optional<bool> versioning;
  608. std::optional<uint32_t> maxVersions;
  609. for (size_t i = 1; i < params.size(); ++i) {
  610. if (params[i] == "--versioning" && i + 1 < params.size()) {
  611. const std::string v = params[++i];
  612. if (v != "on" && v != "off") { printError("--versioning takes on or off"); return false; }
  613. versioning = (v == "on");
  614. } else if (params[i] == "--max-versions" && i + 1 < params.size()) {
  615. long long n = 0;
  616. try { n = std::stoll(params[++i]); } catch (...) { n = -1; }
  617. if (n < 1 || n > 1000000) {
  618. printError("--max-versions takes 1..1000000. 0 means UNLIMITED history, not off: "
  619. "to stop recording history use --versioning off");
  620. return false;
  621. }
  622. maxVersions = static_cast<uint32_t>(n);
  623. } else {
  624. printError("unknown option " + params[i]);
  625. return false;
  626. }
  627. }
  628. if (!versioning && !maxVersions) { printError("nothing to change"); return false; }
  629. const auto before = client.getCollectionInfo(coll);
  630. if (!before) { printError("collection not found: " + coll); return false; }
  631. if (versioning) {
  632. smartbotic::database::Client::CollectionConfig cfg;
  633. cfg.timestampPrecision = ""; // "" = leave precision unchanged
  634. cfg.versioningEnabled = *versioning;
  635. if (!client.configureCollection(coll, cfg)) { printError("configureCollection failed"); return false; }
  636. std::cout << "versioning: " << (*versioning ? "on" : "OFF (no new history is recorded; "
  637. "history already written stays, see --max-versions)") << "\n";
  638. }
  639. if (maxVersions) {
  640. // createCollection on an existing collection re-applies its
  641. // options, and a default TTL of 0 is a real value: pass the
  642. // current one back so the prune cannot clear it. encrypted=false
  643. // never downgrades; a vector dimension of 0 is ignored.
  644. const bool prunes = before->maxVersions == 0 || *maxVersions < before->maxVersions;
  645. const auto t0 = std::chrono::steady_clock::now();
  646. (void)client.createCollection(coll, before->defaultTtlSeconds, false, *maxVersions, 0);
  647. const auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  648. std::chrono::steady_clock::now() - t0).count();
  649. const auto after = client.getCollectionInfo(coll);
  650. std::cout << "max_versions: " << before->maxVersions
  651. << (before->maxVersions == 0 ? " (unlimited)" : "") << " -> "
  652. << (after ? after->maxVersions : *maxVersions) << "\n"
  653. << "default_ttl_seconds kept: " << before->defaultTtlSeconds
  654. << (after && after->defaultTtlSeconds != before->defaultTtlSeconds ? " ⚠ CHANGED" : "") << "\n"
  655. << (prunes ? "history pruned to the newest " + std::to_string(*maxVersions) +
  656. " version(s) per document"
  657. : std::string("cap raised: nothing pruned"))
  658. << " in " << ms << " ms\n"
  659. << " (the history file's size is not visible over the API: compare "
  660. "<data_directory>/history/<collection>.hlog before and after)\n";
  661. }
  662. return true;
  663. }
  664. if (cmd == "info") {
  665. if (params.empty()) { printError("usage: info <collection>"); return false; }
  666. auto info = client.getCollectionInfo(params[0]);
  667. if (!info) { printError("collection not found: " + params[0]); return false; }
  668. std::cout << C_BOLD << params[0] << C_RESET << ":\n"
  669. << " documents: " << info->documentCount << "\n"
  670. << " size: " << info->sizeBytes << " bytes\n"
  671. << " encrypted: " << (info->encrypted ? "yes" : "no") << "\n"
  672. << " max_versions: " << info->maxVersions
  673. << (info->maxVersions == 0 ? " (unlimited)" : "") << "\n"
  674. // v2.18.1 - always printed: `configure --max-versions`
  675. // re-applies it, and an operator must be able to see it.
  676. << " default_ttl_seconds: " << info->defaultTtlSeconds
  677. << (info->defaultTtlSeconds == 0 ? " (none)" : "") << "\n";
  678. // v2.11.4 - relations_enforced is not part of CollectionInfo (it
  679. // is a changeable setting, served by GetCollectionConfig), and
  680. // its absence here read as "the server cannot report it". Always
  681. // printed, since the default is ON and an operator should not
  682. // have to know that to learn a delete may be refused. A failed
  683. // read says so rather than printing the default.
  684. // v2.17.1 - versioning on/off: a collection whose history stopped
  685. // was otherwise visible only as a config field nobody reads.
  686. try {
  687. const auto cfg = client.getCollectionConfig(params[0]);
  688. std::cout << " versioning: "
  689. << (!cfg.versioningEnabled ? "unknown" : *cfg.versioningEnabled ? "on" : "OFF (no history is recorded)")
  690. << "\n";
  691. } catch (const std::exception&) {
  692. std::cout << " versioning: unknown (could not be read)\n";
  693. }
  694. const auto enforced = client.tryGetRelationsEnforced(params[0]);
  695. std::cout << " relations_enforced: "
  696. << (!enforced ? "unknown (could not be read)" : *enforced ? "on" : "off")
  697. << "\n";
  698. return true;
  699. }
  700. if (cmd == "find") {
  701. if (params.empty()) {
  702. printError("usage: find <collection> [--limit N] [--offset N] [--exists FIELD] [--eq FIELD VALUE]");
  703. return false;
  704. }
  705. smartbotic::database::Client::QueryOptions opts;
  706. opts.limit = 100;
  707. for (size_t i = 1; i < params.size(); ++i) {
  708. if (params[i] == "--limit" && i + 1 < params.size()) {
  709. opts.limit = static_cast<uint32_t>(std::stoul(params[++i]));
  710. } else if (params[i] == "--offset" && i + 1 < params.size()) {
  711. // v2.11.1 — paging from the CLI. Without it, walking a
  712. // collection larger than one page meant deleting as you go,
  713. // which is not available when you only want to read.
  714. opts.offset = static_cast<uint32_t>(std::stoul(params[++i]));
  715. } else if (params[i] == "--eq" && i + 2 < params.size()) {
  716. // v2.11.1 — the commonest filter, so cleanup and inspection
  717. // do not need a client program. The value is taken as JSON
  718. // when it parses as JSON and as a string otherwise, so
  719. // --eq status completed and --eq attempts 3 both work.
  720. const std::string field = params[++i];
  721. const std::string raw = params[++i];
  722. nlohmann::json val;
  723. try {
  724. val = nlohmann::json::parse(raw);
  725. } catch (const std::exception&) {
  726. val = raw;
  727. }
  728. opts.filters.emplace_back(field, smartbotic::database::Client::FilterOp::EQ, val);
  729. } else if (params[i] == "--exists" && i + 1 < params.size()) {
  730. opts.filters.emplace_back(params[++i], smartbotic::database::Client::FilterOp::EXISTS, true);
  731. }
  732. }
  733. auto docs = client.find(params[0], opts);
  734. std::cout << C_DIM << "(" << docs.size() << " documents)" << C_RESET << "\n";
  735. for (const auto& doc : docs) {
  736. auto id = doc.value("_id", "");
  737. // Print compact summary line
  738. std::cout << C_GREEN << id << C_RESET;
  739. // Show a few key fields
  740. for (const auto& [k, v] : doc.items()) {
  741. if (k == "_id" || k == "_created_at" || k == "_updated_at") continue;
  742. auto val = v.dump();
  743. if (val.size() > 60) val = val.substr(0, 57) + "...";
  744. std::cout << " " << C_DIM << k << "=" << C_RESET << val;
  745. // Limit to 3 fields per line
  746. static int field_count = 0;
  747. if (++field_count >= 3) { field_count = 0; break; }
  748. }
  749. std::cout << "\n";
  750. }
  751. return true;
  752. }
  753. if (cmd == "get") {
  754. if (params.size() < 2) { printError("usage: get <collection> <id>"); return false; }
  755. auto doc = client.get(params[0], params[1]);
  756. if (!doc) { printError("not found: " + params[0] + "/" + params[1]); return false; }
  757. printJson(*doc);
  758. return true;
  759. }
  760. if (cmd == "upsert") {
  761. if (params.size() < 3) { printError("usage: upsert <collection> <id> '<json>'"); return false; }
  762. auto data = json::parse(params[2], nullptr, false);
  763. if (!data.is_object()) { printError("invalid JSON: " + params[2]); return false; }
  764. client.upsert(params[0], data, params[1]);
  765. std::cout << C_GREEN << "ok" << C_RESET << " " << params[0] << "/" << params[1] << "\n";
  766. return true;
  767. }
  768. if (cmd == "remove" || cmd == "delete") {
  769. if (params.size() < 2) { printError("usage: remove <collection> <id>"); return false; }
  770. // v2.11.0 T6b — the return value used to be discarded and "ok
  771. // removed" printed unconditionally. That was merely sloppy
  772. // before referential integrity: now a delete can be REFUSED (a
  773. // relation with on_delete=restrict/no_action still has children
  774. // referencing it), and the server reports that as a real error,
  775. // not deleted=false. Report the actual outcome, and surface the
  776. // server's message on refusal so an operator learns what
  777. // blocked them rather than being told it worked.
  778. std::string err;
  779. bool deleted = client.remove(params[0], params[1], err);
  780. if (!err.empty()) {
  781. printError("remove " + params[0] + "/" + params[1] + ": " + err);
  782. return false;
  783. }
  784. if (!deleted) {
  785. std::cout << C_YELLOW << "not found" << C_RESET << " "
  786. << params[0] << "/" << params[1] << "\n";
  787. return true;
  788. }
  789. std::cout << C_GREEN << "ok" << C_RESET << " removed " << params[0] << "/" << params[1] << "\n";
  790. return true;
  791. }
  792. if (cmd == "count") {
  793. if (params.empty()) { printError("usage: count <collection>"); return false; }
  794. auto info = client.getCollectionInfo(params[0]);
  795. if (!info) { printError("collection not found: " + params[0]); return false; }
  796. std::cout << info->documentCount << "\n";
  797. return true;
  798. }
  799. // ===== v2.9.0 secondary indexes =====
  800. //
  801. // Declaration is explicit because an index costs write throughput and is
  802. // not always a win: on a low-cardinality field the planner will decline to
  803. // use it, since reading the index and then fetching most of the collection
  804. // by id loses to scanning. `indexes` reports distinct values precisely so
  805. // an operator can see that coming.
  806. if (cmd == "indexes") {
  807. if (params.empty()) { printError("usage: indexes <collection>"); return false; }
  808. std::vector<bool> uniqueFlags;
  809. auto list = client.listIndexes(params[0], uniqueFlags);
  810. // v2.12.0 - composite unique constraints are listed separately: they
  811. // are constraints over several fields, not indexes on one.
  812. const auto composites = client.listCompositeUniqueIndexes(params[0]);
  813. if (list.empty() && composites.empty()) {
  814. std::cout << "no indexes on " << params[0] << "\n";
  815. return true;
  816. }
  817. if (!composites.empty()) {
  818. std::cout << C_BOLD << "composite unique constraints" << C_RESET << "\n";
  819. for (const auto& cf : composites) {
  820. std::cout << " (";
  821. for (size_t i = 0; i < cf.size(); ++i) std::cout << (i ? ", " : "") << cf[i];
  822. std::cout << ")\n";
  823. }
  824. if (list.empty()) return true;
  825. }
  826. std::cout << C_BOLD << "field distinct entries unique"
  827. << C_RESET << "\n";
  828. for (size_t idx = 0; idx < list.size(); ++idx) {
  829. const auto& i = list[idx];
  830. const bool unique = idx < uniqueFlags.size() && uniqueFlags[idx];
  831. std::cout << " " << i.field
  832. << std::string(i.field.size() < 29 ? 29 - i.field.size() : 1, ' ')
  833. << i.distinctValues
  834. << std::string(std::to_string(i.distinctValues).size() < 13
  835. ? 13 - std::to_string(i.distinctValues).size()
  836. : 1, ' ')
  837. << i.entries
  838. << std::string(std::to_string(i.entries).size() < 9
  839. ? 9 - std::to_string(i.entries).size()
  840. : 1, ' ')
  841. << (unique ? "yes" : "no") << "\n";
  842. }
  843. return true;
  844. }
  845. if (cmd == "index-values") {
  846. if (params.size() < 2) {
  847. printError("usage: index-values <collection> <field> [limit] [asc|desc]");
  848. return false;
  849. }
  850. const uint32_t limit = params.size() > 2 ? std::stoul(params[2]) : 20;
  851. const bool asc = params.size() > 3 ? (params[3] != "desc") : true;
  852. auto vals = client.indexValues(params[0], params[1], limit, asc);
  853. if (vals.empty()) {
  854. std::cout << "no values (is " << params[1] << " indexed?)\n";
  855. return true;
  856. }
  857. std::cout << C_BOLD << "rows value" << C_RESET << "\n";
  858. for (const auto& v : vals) {
  859. const std::string c = std::to_string(v.count);
  860. std::cout << " " << c
  861. << std::string(c.size() < 9 ? 9 - c.size() : 1, ' ')
  862. << v.value.dump() << "\n";
  863. }
  864. return true;
  865. }
  866. if (cmd == "index-create") {
  867. if (params.size() < 2) {
  868. printError("usage: index-create <collection> <field> [--unique]");
  869. return false;
  870. }
  871. // A flag is never a field name. `index-create "users email" --unique`
  872. // (collection and field quoted as one argument) used to declare a
  873. // unique index on a field named `--unique` of a collection named
  874. // `users email` - found on a production instance, rebuilt with a WARN at every boot.
  875. if (params[0].rfind("--", 0) == 0 || params[1].rfind("--", 0) == 0) {
  876. printError("usage: index-create <collection> <field> [--unique] - '" +
  877. (params[1].rfind("--", 0) == 0 ? params[1] : params[0]) +
  878. "' is a flag, not a name (were the collection and field quoted together?)");
  879. return false;
  880. }
  881. const bool unique = std::find(params.begin(), params.end(), "--unique") != params.end();
  882. if (unique) {
  883. // v2.11.0 T11 — a duplicate-refusal is not a generic failure:
  884. // surface the examples so the operator can go fix the data
  885. // rather than guess what "could not create the index" meant.
  886. auto result = client.createUniqueIndex(params[0], params[1]);
  887. if (!result.success) {
  888. printError(result.error);
  889. if (!result.duplicateExamples.empty()) {
  890. std::cout << " colliding document ids: ";
  891. for (size_t i = 0; i < result.duplicateExamples.size(); ++i) {
  892. if (i) std::cout << ", ";
  893. std::cout << result.duplicateExamples[i];
  894. }
  895. std::cout << "\n";
  896. }
  897. return false;
  898. }
  899. std::cout << "indexed " << result.rowsIndexed << " existing row(s) on "
  900. << params[0] << "#" << params[1] << " (unique)\n";
  901. return true;
  902. }
  903. uint64_t rows = 0;
  904. if (!client.createIndex(params[0], params[1], rows)) {
  905. printError("could not create the index (see the service log)");
  906. return false;
  907. }
  908. std::cout << "indexed " << rows << " existing row(s) on "
  909. << params[0] << "#" << params[1] << "\n";
  910. return true;
  911. }
  912. // v2.12.0 - composite unique constraints.
  913. if (cmd == "unique-create" || cmd == "unique-drop") {
  914. if (params.size() < 3) {
  915. printError("usage: " + cmd + " <collection> <field> <field> [field...]");
  916. return false;
  917. }
  918. const std::vector<std::string> fields(params.begin() + 1, params.end());
  919. if (cmd == "unique-drop") {
  920. if (!client.dropCompositeUniqueIndex(params[0], fields)) {
  921. printError("could not drop the constraint (see the service log)");
  922. return false;
  923. }
  924. std::cout << C_GREEN << "ok" << C_RESET << " dropped\n";
  925. return true;
  926. }
  927. auto r = client.createCompositeUniqueIndex(params[0], fields);
  928. if (!r.success) {
  929. printError(r.error);
  930. return false;
  931. }
  932. std::cout << C_GREEN << "ok" << C_RESET << " " << (r.alreadyExisted ? "already declared" : "declared")
  933. << ", " << r.rowsIndexed << " row(s) constrained\n";
  934. return true;
  935. }
  936. if (cmd == "index-drop") {
  937. if (params.size() < 2) {
  938. printError("usage: index-drop <collection> <field>");
  939. return false;
  940. }
  941. if (!client.dropIndex(params[0], params[1])) {
  942. printError("could not drop the index (see the service log)");
  943. return false;
  944. }
  945. std::cout << "dropped " << params[0] << "#" << params[1] << "\n";
  946. return true;
  947. }
  948. // ===== v2.11.0 T6b — relations (referential integrity) =====
  949. //
  950. // Declaration is admin-only: `_relations` is a system collection and a
  951. // relation names another collection's schema, which is not ordinary
  952. // per-collection write access. Follows the `indexes` output shape.
  953. if (cmd == "relations") {
  954. // v2.11.1 — an operator asking "what is enforced on this database"
  955. // means the whole database. Scoping this to the client's own project
  956. // made it print "no relations declared" on an instance with active
  957. // enforcement in another project, while `relation <name>` (never
  958. // project-scoped) happily showed that same relation. --project
  959. // narrows it back down.
  960. auto list = client.listRelations(explicitProject);
  961. if (list.empty()) {
  962. std::cout << (explicitProject.empty()
  963. ? "no relations declared in any project\n"
  964. : "no relations declared in project '" +
  965. explicitProject + "'\n");
  966. return true;
  967. }
  968. std::cout << C_BOLD << "name child.field -> parent on_delete enforced-at-write"
  969. << C_RESET << "\n";
  970. for (const auto& r : list) {
  971. std::cout << " " << C_CYAN << r.name << C_RESET
  972. << std::string(r.name.size() < 19 ? 19 - r.name.size() : 1, ' ')
  973. << r.child << "." << r.childField << " -> " << r.parent
  974. << " " << r.onDelete
  975. << (r.validateOnWrite ? " (validate_on_write)" : "") << "\n";
  976. }
  977. return true;
  978. }
  979. if (cmd == "relation") {
  980. if (params.empty()) { printError("usage: relation <name>"); return false; }
  981. auto r = client.getRelationInfo(params[0]);
  982. if (!r) { printError("relation not found: " + params[0]); return false; }
  983. std::cout << C_BOLD << r->name << C_RESET << ":\n"
  984. << " child: " << r->child << "\n"
  985. << " child_field: " << r->childField << "\n"
  986. << " parent: " << r->parent << "\n"
  987. << " on_delete: " << r->onDelete << "\n"
  988. << " validate_on_write: " << (r->validateOnWrite ? "yes" : "no") << "\n";
  989. return true;
  990. }
  991. if (cmd == "relation-create") {
  992. if (params.size() < 4) {
  993. printError("usage: relation-create <name> <child> <child_field> <parent> "
  994. "[on_delete] [validate_on_write]\n"
  995. " on_delete: restrict (default) | cascade | set_null | no_action\n"
  996. " note (v2.11.0+): cascade deletes the referencing document "
  997. "(scalar reference) or pulls the id from the array and keeps the "
  998. "document (array reference - cascade and set_null are the same "
  999. "for arrays); set_null nulls the scalar field. no_action permits "
  1000. "the delete and leaves the reference dangling.");
  1001. return false;
  1002. }
  1003. const std::string onDelete = params.size() > 4 ? params[4] : "restrict";
  1004. const bool validateOnWrite = params.size() > 5
  1005. && (params[5] == "true" || params[5] == "1" || params[5] == "yes");
  1006. // v2.11.0 T7 - the server backfills the reverse index over rows
  1007. // already in the child collection as part of this call, so
  1008. // rowsIndexed reports coverage the same way index-create does.
  1009. uint64_t rowsIndexed = 0;
  1010. if (!client.createRelation(params[0], params[1], params[2], params[3],
  1011. onDelete, validateOnWrite, rowsIndexed)) {
  1012. printError("could not create the relation (see the service log)");
  1013. return false;
  1014. }
  1015. std::cout << "declared relation " << params[0] << " (" << params[1] << "."
  1016. << params[2] << " -> " << params[3] << ", on_delete=" << onDelete << ")\n"
  1017. << "indexed " << rowsIndexed << " existing row(s) in " << params[1] << "\n";
  1018. return true;
  1019. }
  1020. if (cmd == "relation-drop") {
  1021. if (params.empty()) { printError("usage: relation-drop <name>"); return false; }
  1022. if (!client.dropRelation(params[0])) {
  1023. printError("could not drop the relation (see the service log)");
  1024. return false;
  1025. }
  1026. std::cout << "dropped relation " << params[0] << "\n";
  1027. return true;
  1028. }
  1029. // v2.11.0 T7 - "does this relation's reverse index actually match
  1030. // live data?" Read-only, changes nothing. Walks the whole reverse
  1031. // index (cost is proportional to distinct parents referenced, not to
  1032. // the child collection's size) so this is a migration/operator tool,
  1033. // not something to run in a loop.
  1034. if (cmd == "relation-check") {
  1035. if (params.empty()) { printError("usage: relation-check <name>"); return false; }
  1036. auto result = client.checkRelation(params[0]);
  1037. if (!result.success) {
  1038. printError("could not check the relation: " + result.error);
  1039. return false;
  1040. }
  1041. if (result.totalDangling == 0) {
  1042. std::cout << C_GREEN << "clean" << C_RESET << " - no dangling references for "
  1043. << params[0] << "\n";
  1044. return true;
  1045. }
  1046. std::cout << C_RED << result.totalDangling << " dangling reference(s)" << C_RESET
  1047. << " for " << params[0] << ":\n";
  1048. for (const auto& d : result.dangling) {
  1049. std::cout << " parent " << d.parentId << " does not exist, referenced by "
  1050. << d.childCount << " child document(s)";
  1051. if (!d.sampleChildIds.empty()) {
  1052. std::cout << " (e.g. ";
  1053. for (size_t i = 0; i < d.sampleChildIds.size(); ++i) {
  1054. if (i) std::cout << ", ";
  1055. std::cout << d.sampleChildIds[i];
  1056. }
  1057. std::cout << ")";
  1058. }
  1059. std::cout << "\n";
  1060. }
  1061. if (result.dangling.size() < result.totalDangling) {
  1062. std::cout << " ... " << (result.totalDangling - result.dangling.size())
  1063. << " more not shown\n";
  1064. }
  1065. return true;
  1066. }
  1067. // v2.11.0 T8 — the only reachable path to relations_enforced besides
  1068. // grpcurl. A partial update: touches only this one knob.
  1069. //
  1070. // v2.11.4 - with no value it READS the setting. Until then this
  1071. // command could change a flag no command could show, so the state
  1072. // after `configure-relations x off` was something you had to
  1073. // remember rather than something you could check.
  1074. if (cmd == "configure-relations") {
  1075. if (params.empty()) {
  1076. printError("usage: configure-relations <collection> [on|off]");
  1077. return false;
  1078. }
  1079. if (params.size() == 1) {
  1080. const auto current = client.tryGetRelationsEnforced(params[0]);
  1081. if (!current) {
  1082. printError("could not read relations_enforced for " + params[0]);
  1083. return false;
  1084. }
  1085. std::cout << params[0] << " relations_enforced="
  1086. << (*current ? "on" : "off") << "\n";
  1087. return true;
  1088. }
  1089. if (params[1] != "on" && params[1] != "off") {
  1090. printError("expected 'on' or 'off', got: " + params[1]);
  1091. return false;
  1092. }
  1093. const bool enforced = params[1] == "on";
  1094. if (!client.setRelationsEnforced(params[0], enforced)) {
  1095. printError("could not update relations_enforced (see the service log)");
  1096. return false;
  1097. }
  1098. std::cout << C_GREEN << "ok" << C_RESET << " " << params[0]
  1099. << " relations_enforced=" << (enforced ? "on" : "off") << "\n";
  1100. return true;
  1101. }
  1102. // v2.11.0 T5 — DescribeDelete: "what would happen if I deleted this?"
  1103. // without deleting anything. A per-collection READ, not admin - any
  1104. // caller who can read the collection can ask this. Cheap enough to
  1105. // run before every delete: counts come from the reverse index.
  1106. if (cmd == "describe-delete") {
  1107. if (params.size() < 2) {
  1108. printError("usage: describe-delete <collection> <id>");
  1109. return false;
  1110. }
  1111. auto d = client.describeDelete(params[0], params[1]);
  1112. if (!d.success) {
  1113. printError("could not describe the delete: " + d.error);
  1114. return false;
  1115. }
  1116. if (d.impacts.empty()) {
  1117. std::cout << "no relations reference " << params[0] << "/" << params[1]
  1118. << " - safe to delete\n";
  1119. return true;
  1120. }
  1121. std::cout << (d.wouldBeBlocked
  1122. ? (C_RED + std::string("would be BLOCKED") + C_RESET)
  1123. : (C_GREEN + std::string("would proceed") + C_RESET))
  1124. << " deleting " << params[0] << "/" << params[1] << ":\n";
  1125. for (const auto& imp : d.impacts) {
  1126. std::cout << " " << (imp.blocks ? C_RED : C_DIM) << "[" << imp.onDelete << "]"
  1127. << C_RESET << " " << imp.relation << ": " << imp.childCount
  1128. << " child document(s) in " << imp.childCollection
  1129. << " via " << imp.childField;
  1130. if (!imp.sampleChildIds.empty()) {
  1131. std::cout << " (e.g. ";
  1132. for (size_t i = 0; i < imp.sampleChildIds.size(); ++i) {
  1133. if (i) std::cout << ", ";
  1134. std::cout << imp.sampleChildIds[i];
  1135. }
  1136. std::cout << ")";
  1137. }
  1138. std::cout << (imp.blocks ? " BLOCKS" : "") << "\n";
  1139. }
  1140. return true;
  1141. }
  1142. // ===== v2.7.0 access policy =====
  1143. //
  1144. // Policy lives in the `_policies` collection and is managed through the
  1145. // ordinary document API, which the server intercepts so edits refresh
  1146. // its cache and the `__security__` record goes through the lockout
  1147. // guards. These commands are ergonomics over that, not a second
  1148. // mechanism - which is why there is no policy RPC to keep in step.
  1149. if (cmd == "policies") {
  1150. const std::string project = params.empty() ? "default" : params[0];
  1151. auto rows = client.find("_policies", smartbotic::database::Client::QueryOptions{.limit = 1000});
  1152. std::cout << C_BOLD << "policies in project '" << project << "'" << C_RESET << "\n";
  1153. size_t shown = 0;
  1154. for (const auto& r : rows) {
  1155. const std::string id = r.value("_id", "");
  1156. if (id.rfind(project + ":", 0) != 0) continue;
  1157. const std::string tail = id.substr(project.size() + 1);
  1158. if (tail == "__security__") continue;
  1159. std::cout << " " << C_CYAN << tail << C_RESET
  1160. << (r.value("admin", false) ? " (admin)" : "") << "\n";
  1161. ++shown;
  1162. }
  1163. if (shown == 0) std::cout << C_DIM << " (none)" << C_RESET << "\n";
  1164. return true;
  1165. }
  1166. if (cmd == "policy") {
  1167. if (params.size() < 2) {
  1168. printError("usage: policy <project> <principal>");
  1169. return false;
  1170. }
  1171. auto doc = client.get("_policies", params[0] + ":" + params[1]);
  1172. if (!doc) { printError("no policy for " + params[0] + ":" + params[1]); return false; }
  1173. printJson(*doc);
  1174. return true;
  1175. }
  1176. if (cmd == "policy-set") {
  1177. if (params.size() < 3) {
  1178. printError("usage: policy-set <project> <principal> '<json>'\n"
  1179. " e.g. policy-set acme svc "
  1180. "'{\"collections\":{\"users\":{\"read\":true,\"mask\":[\"ssn\"]}}}'\n"
  1181. " admin: policy-set acme ops '{\"admin\":true}'");
  1182. return false;
  1183. }
  1184. try {
  1185. auto body = json::parse(params[2]);
  1186. client.upsert("_policies", body, params[0] + ":" + params[1]);
  1187. std::cout << C_GREEN << "ok" << C_RESET << " policy set for "
  1188. << params[0] << ":" << params[1] << "\n";
  1189. return true;
  1190. } catch (const std::exception& e) {
  1191. printError(e.what());
  1192. return false;
  1193. }
  1194. }
  1195. if (cmd == "policy-rm") {
  1196. if (params.size() < 2) { printError("usage: policy-rm <project> <principal>"); return false; }
  1197. try {
  1198. bool ok = client.remove("_policies", params[0] + ":" + params[1]);
  1199. std::cout << (ok ? "removed\n" : "not found\n");
  1200. return ok;
  1201. } catch (const std::exception& e) {
  1202. // The server refuses to remove the last admin of a secured
  1203. // project - that refusal is the lockout guard, not an error to
  1204. // work around.
  1205. printError(e.what());
  1206. return false;
  1207. }
  1208. }
  1209. if (cmd == "security") {
  1210. const std::string project = params.empty() ? "default" : params[0];
  1211. auto doc = client.get("_policies", project + ":__security__");
  1212. if (!doc) {
  1213. std::cout << "project '" << project << "': security "
  1214. << C_GREEN << "disabled" << C_RESET
  1215. << C_DIM << " (default - all access allowed)" << C_RESET << "\n";
  1216. return true;
  1217. }
  1218. const bool on = doc->value("enabled", false);
  1219. const std::string mode = doc->value("mode", "enforce");
  1220. std::cout << "project '" << project << "': security "
  1221. << (on ? (mode == "audit" ? C_YELLOW : C_RED) : C_GREEN)
  1222. << (on ? (mode == "audit" ? "AUDIT" : "ENFORCED") : "disabled")
  1223. << C_RESET << "\n";
  1224. if (on && mode == "audit") {
  1225. std::cout << C_DIM << " audit mode logs what it would deny and "
  1226. "allows the request - watch the service log, then "
  1227. "switch to enforce." << C_RESET << "\n";
  1228. }
  1229. return true;
  1230. }
  1231. if (cmd == "security-set") {
  1232. if (params.size() < 2) {
  1233. printError("usage: security-set <project> <on|off> [enforce|audit]\n"
  1234. " Enabling is REFUSED unless some policy in the project has "
  1235. "admin=true.\n"
  1236. " Switch a live project on with 'audit' first.");
  1237. return false;
  1238. }
  1239. const bool on = params[1] == "on" || params[1] == "true";
  1240. const std::string mode = params.size() > 2 ? params[2] : "enforce";
  1241. if (mode != "enforce" && mode != "audit") {
  1242. printError("mode must be 'enforce' or 'audit'");
  1243. return false;
  1244. }
  1245. try {
  1246. json body;
  1247. body["enabled"] = on;
  1248. body["mode"] = mode;
  1249. client.upsert("_policies", body, params[0] + ":__security__");
  1250. std::cout << C_GREEN << "ok" << C_RESET << " project '" << params[0]
  1251. << "' security " << (on ? mode : "disabled") << "\n";
  1252. return true;
  1253. } catch (const std::exception& e) {
  1254. printError(e.what());
  1255. return false;
  1256. }
  1257. }
  1258. if (cmd == "lock") {
  1259. if (client.setReadOnly(true)) {
  1260. std::cout << C_GREEN << "ok" << C_RESET << " Database locked (read-only)\n";
  1261. return true;
  1262. }
  1263. printError("failed to lock database");
  1264. return false;
  1265. }
  1266. if (cmd == "unlock") {
  1267. if (client.setReadOnly(false)) {
  1268. std::cout << C_GREEN << "ok" << C_RESET << " Database unlocked (writes accepted)\n";
  1269. return true;
  1270. }
  1271. printError("failed to unlock database");
  1272. return false;
  1273. }
  1274. if (cmd == "status") {
  1275. auto s = client.getReadOnlyStatus();
  1276. std::cout << "Read-only: " << (s.readOnly ? (std::string(C_RED) + "YES" + C_RESET) : "no") << "\n";
  1277. if (s.readOnly) {
  1278. std::cout << "Reason: " << s.reason << "\n";
  1279. }
  1280. std::cout << "Recovery outcome: " << s.recoveryOutcome << "\n";
  1281. if (!s.expectedSnapshot.empty()) {
  1282. std::cout << "Expected snapshot: " << s.expectedSnapshot << "\n";
  1283. }
  1284. if (!s.snapshotUsed.empty()) {
  1285. std::cout << "Snapshot used: " << s.snapshotUsed << "\n";
  1286. }
  1287. if (!s.failureReason.empty()) {
  1288. std::cout << "Failure reason: " << s.failureReason << "\n";
  1289. }
  1290. std::cout << "WAL replayed: " << s.walEntriesReplayed << " entries\n";
  1291. std::cout << "Snapshots tried: " << s.snapshotsAttempted << "\n";
  1292. return true;
  1293. }
  1294. if (cmd == "help" || cmd == "?") {
  1295. printUsage();
  1296. return true;
  1297. }
  1298. printError("unknown command: " + cmd + " (try 'help')");
  1299. return false;
  1300. } catch (const std::exception& e) {
  1301. printError(e.what());
  1302. return false;
  1303. }
  1304. }
  1305. // Tokenize a line, respecting single/double quotes and JSON braces
  1306. std::vector<std::string> tokenize(const std::string& line) {
  1307. std::vector<std::string> tokens;
  1308. std::string current;
  1309. int brace_depth = 0;
  1310. char in_quote = 0;
  1311. for (size_t i = 0; i < line.size(); ++i) {
  1312. char c = line[i];
  1313. if (in_quote) {
  1314. current += c;
  1315. if (c == in_quote && (i == 0 || line[i-1] != '\\')) {
  1316. in_quote = 0;
  1317. // Strip surrounding quotes for simple string tokens
  1318. if (brace_depth == 0 && current.size() >= 2
  1319. && (current.front() == '\'' || current.front() == '"')
  1320. && current.front() == current.back()) {
  1321. current = current.substr(1, current.size() - 2);
  1322. }
  1323. }
  1324. continue;
  1325. }
  1326. if (c == '\'' || c == '"') {
  1327. in_quote = c;
  1328. current += c;
  1329. continue;
  1330. }
  1331. if (c == '{') { brace_depth++; current += c; continue; }
  1332. if (c == '}') {
  1333. brace_depth--;
  1334. current += c;
  1335. if (brace_depth <= 0) {
  1336. brace_depth = 0;
  1337. tokens.push_back(current);
  1338. current.clear();
  1339. }
  1340. continue;
  1341. }
  1342. if (brace_depth > 0) { current += c; continue; }
  1343. if (c == ' ' || c == '\t') {
  1344. if (!current.empty()) {
  1345. tokens.push_back(current);
  1346. current.clear();
  1347. }
  1348. continue;
  1349. }
  1350. current += c;
  1351. }
  1352. if (!current.empty()) tokens.push_back(current);
  1353. return tokens;
  1354. }
  1355. // v2.4.4 — offline sub-db placement audit / repair.
  1356. //
  1357. // `verify-subdbs` is read-only and safe against a running server.
  1358. // `reconcile-subdbs --apply` rewrites document placement and REQUIRES the
  1359. // service to be stopped: it holds an LMDB write txn over the whole env.
  1360. int cmdSubdbs(const std::string& command, const std::vector<std::string>& params) {
  1361. std::string env_path, project;
  1362. bool apply = false;
  1363. bool stamp = false;
  1364. for (size_t i = 0; i < params.size(); ++i) {
  1365. const std::string& p = params[i];
  1366. if (p == "--env" && i + 1 < params.size()) {
  1367. env_path = params[++i];
  1368. } else if (p == "--project" && i + 1 < params.size()) {
  1369. project = params[++i];
  1370. } else if (p == "--apply") {
  1371. apply = true;
  1372. } else if (p == "--stamp-identity") {
  1373. stamp = true;
  1374. } else {
  1375. printError("unknown argument: " + p);
  1376. return 2;
  1377. }
  1378. }
  1379. if (env_path.empty()) {
  1380. printError("--env <path> is required (e.g. "
  1381. "/var/lib/smartbotic-database/projects/default/env)");
  1382. return 2;
  1383. }
  1384. if (command == "verify-subdbs" && apply) {
  1385. printError("--apply is not valid for verify-subdbs; use reconcile-subdbs");
  1386. return 2;
  1387. }
  1388. try {
  1389. auto report = smartbotic::db::storage::audit(env_path, project);
  1390. smartbotic::db::storage::print_audit(report);
  1391. if (command == "verify-subdbs") {
  1392. return report.misplaced.empty() ? 0 : 1;
  1393. }
  1394. if (!apply) {
  1395. std::cout << "\n" << C_YELLOW << "Dry run." << C_RESET
  1396. << " Re-run with --apply to perform the repair.\n"
  1397. << C_DIM
  1398. << "Stop the service first, and take a backup: the repair "
  1399. "rewrites document placement in place.\n"
  1400. << C_RESET;
  1401. return report.misplaced.empty() ? 0 : 1;
  1402. }
  1403. if (stamp) {
  1404. std::cout << "\n" << C_YELLOW << "--stamp-identity:" << C_RESET
  1405. << " writing sentinels. This REQUIRES the server binary to be"
  1406. " v2.4.4 or newer;\n earlier builds do not skip the sentinel"
  1407. " and will fail on scan.\n";
  1408. }
  1409. std::cout << "\nApplying...\n";
  1410. auto res = smartbotic::db::storage::repair(env_path, report, stamp);
  1411. std::cout << C_GREEN << "done." << C_RESET
  1412. << " moved=" << res.moved
  1413. << " quarantined=" << res.quarantined
  1414. << " stamped=" << res.stamped << "\n";
  1415. for (const auto& e : res.errors) {
  1416. std::cerr << C_RED << " warn: " << C_RESET << e << "\n";
  1417. }
  1418. return res.errors.empty() ? 0 : 1;
  1419. } catch (const std::exception& e) {
  1420. printError(e.what());
  1421. return 1;
  1422. }
  1423. }
  1424. } // anonymous namespace
  1425. int main(int argc, char* argv[]) {
  1426. Args args;
  1427. // Parse flags
  1428. std::vector<std::string> positional;
  1429. for (int i = 1; i < argc; ++i) {
  1430. std::string arg = argv[i];
  1431. if (arg == "--address" && i + 1 < argc) {
  1432. args.address = argv[++i];
  1433. } else if (arg == "--project" && i + 1 < argc) {
  1434. args.project = argv[++i];
  1435. } else if (arg == "--help" || arg == "-h") {
  1436. printUsage();
  1437. return 0;
  1438. } else if (arg == "--version" || arg == "-V") {
  1439. // Offline, and before anything else: a version check must not need a
  1440. // reachable server. Same format as the service binary so the two can
  1441. // be compared at a glance.
  1442. std::cout << "smartbotic-db-cli version " << SMARTBOTIC_DB_VERSION_STRING
  1443. << " (commit " << SMARTBOTIC_DB_GIT_COMMIT_STRING << ")\n"
  1444. // The LOADED client library, which can differ from the
  1445. // binary's own version if only one package was upgraded.
  1446. // That divergence is exactly what an operator is trying to
  1447. // diagnose when they ask a binary for its version.
  1448. << "libsmartbotic-db-client "
  1449. << smartbotic::database::clientLibraryVersion()
  1450. << " (commit " << smartbotic::database::clientLibraryCommit() << ")\n";
  1451. return 0;
  1452. } else {
  1453. positional.push_back(arg);
  1454. }
  1455. }
  1456. if (!positional.empty()) {
  1457. args.command = positional[0];
  1458. args.params.assign(positional.begin() + 1, positional.end());
  1459. }
  1460. // Offline helpers — these don't need a running server, so dispatch
  1461. // them before opening the gRPC channel.
  1462. if (args.command == "generate-auth-key") {
  1463. return cmdGenerateAuthKey();
  1464. }
  1465. if (args.command == "generate-tls-cert") {
  1466. return cmdGenerateTlsCert(args.params);
  1467. }
  1468. if (args.command == "verify-subdbs" || args.command == "reconcile-subdbs") {
  1469. return cmdSubdbs(args.command, args.params);
  1470. }
  1471. // Connect
  1472. smartbotic::database::Client::Config clientCfg{.address = args.address};
  1473. if (!args.project.empty()) clientCfg.project = args.project;
  1474. smartbotic::database::Client client(clientCfg);
  1475. client.connect();
  1476. // Scriptable mode: single command
  1477. if (!args.command.empty()) {
  1478. return execCommand(client, args.command, args.params, args.project) ? 0 : 1;
  1479. }
  1480. // Interactive mode
  1481. std::cout << C_BOLD << "smartbotic-db-cli" << C_RESET
  1482. << " connected to " << C_CYAN << args.address << C_RESET << "\n"
  1483. << C_DIM << "Type 'help' for commands, 'exit' to quit." << C_RESET << "\n";
  1484. std::string line;
  1485. while (true) {
  1486. std::cout << C_YELLOW << "> " << C_RESET;
  1487. if (!std::getline(std::cin, line)) break;
  1488. // Trim
  1489. auto start = line.find_first_not_of(" \t");
  1490. if (start == std::string::npos) continue;
  1491. line = line.substr(start);
  1492. if (line == "exit" || line == "quit" || line == "q") break;
  1493. if (line.empty()) continue;
  1494. auto tokens = tokenize(line);
  1495. if (tokens.empty()) continue;
  1496. auto cmd = tokens[0];
  1497. std::vector<std::string> params(tokens.begin() + 1, tokens.end());
  1498. execCommand(client, cmd, params, args.project);
  1499. }
  1500. return 0;
  1501. }