main.cpp 51 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236
  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 <cerrno>
  18. #include <cstdio>
  19. #include <cstring>
  20. #include <fstream>
  21. #include <iostream>
  22. #include <sstream>
  23. #include <string>
  24. #include <vector>
  25. using json = nlohmann::json;
  26. namespace {
  27. struct Args {
  28. std::string address = "localhost:9004";
  29. // v2.11.0 T6b — needed to exercise relation management against a
  30. // non-default project from the CLI. Empty means the client's own
  31. // "default" (unchanged behaviour for every existing command).
  32. std::string project;
  33. std::string command;
  34. std::vector<std::string> params;
  35. };
  36. // ANSI colors
  37. constexpr auto C_RESET = "\033[0m";
  38. constexpr auto C_BOLD = "\033[1m";
  39. constexpr auto C_DIM = "\033[2m";
  40. constexpr auto C_CYAN = "\033[36m";
  41. constexpr auto C_GREEN = "\033[32m";
  42. constexpr auto C_RED = "\033[31m";
  43. constexpr auto C_YELLOW = "\033[33m";
  44. void printJson(const json& j) {
  45. std::cout << j.dump(2) << "\n";
  46. }
  47. void printError(const std::string& msg) {
  48. std::cerr << C_RED << "error: " << C_RESET << msg << "\n";
  49. }
  50. void printUsage() {
  51. std::cout << C_BOLD << "smartbotic-db-cli" << C_RESET << " — admin tool for smartbotic-database\n\n"
  52. << C_BOLD << "Usage:" << C_RESET << "\n"
  53. << " smartbotic-db-cli [--address HOST:PORT] <command> [args...]\n"
  54. << " smartbotic-db-cli [--address HOST:PORT] " << C_DIM << "# interactive mode" << C_RESET << "\n\n"
  55. << C_BOLD << "Commands:" << C_RESET << "\n"
  56. << " " << C_CYAN << "collections" << C_RESET << " List all collections\n"
  57. << " " << C_CYAN << "info" << C_RESET << " <collection> Collection info\n"
  58. << " " << C_CYAN << "find" << C_RESET << " <collection> List documents\n"
  59. << " " << C_CYAN << "get" << C_RESET << " <collection> <id> Get a document\n"
  60. << " " << C_CYAN << "upsert" << C_RESET << " <collection> <id> '<json>' Insert or update\n"
  61. << " " << C_CYAN << "remove" << C_RESET << " <collection> <id> Delete a document\n"
  62. << " " << C_CYAN << "count" << C_RESET << " <collection> Count documents\n"
  63. << " " << C_CYAN << "lock" << C_RESET << " Lock database (read-only)\n"
  64. << " " << C_CYAN << "unlock" << C_RESET << " Unlock database (accept writes)\n"
  65. << " " << C_CYAN << "status" << C_RESET << " Show read-only + recovery status\n"
  66. << C_BOLD << " Access policy (v2.7.0+)" << C_RESET << "\n"
  67. << " " << C_CYAN << "security" << C_RESET << " [project] Show whether a project enforces policy\n"
  68. << " " << C_CYAN << "indexes" << C_RESET << " <collection>"
  69. << " list secondary indexes\n"
  70. << " " << C_CYAN << "index-create" << C_RESET << " <collection> <field>"
  71. << " declare an index and backfill it\n"
  72. << " " << C_CYAN << "index-drop" << C_RESET << " <collection> <field>"
  73. << " remove an index\n"
  74. << " " << C_CYAN << "index-values" << C_RESET << " <coll> <field> [n] [asc|desc]"
  75. << " distinct values + counts\n"
  76. << C_BOLD << " Relations / referential integrity (v2.11.0+)" << C_RESET << "\n"
  77. << " " << C_CYAN << "relations" << C_RESET
  78. << " List declared relations\n"
  79. << " " << C_CYAN << "relation" << C_RESET << " <name>"
  80. << " Show one relation's declaration\n"
  81. << " " << C_CYAN << "relation-create" << C_RESET
  82. << " <name> <child> <child_field> <parent> [on_delete] [validate_on_write]\n"
  83. << " " << C_CYAN << "relation-drop" << C_RESET << " <name>\n"
  84. << " " << C_CYAN << "relation-check" << C_RESET << " <name>"
  85. << " Report dangling references (read-only)\n"
  86. << " " << C_CYAN << "configure-relations" << C_RESET
  87. << " <collection> <on|off> Enable/disable enforcement for a collection\n"
  88. << " " << C_CYAN << "describe-delete" << C_RESET << " <collection> <id>"
  89. << " What would happen if this document were deleted\n"
  90. << " " << C_CYAN << "security-set" << C_RESET << " <project> <on|off> [enforce|audit]\n"
  91. << " " << C_CYAN << "policies" << C_RESET << " [project] List principals with a policy\n"
  92. << " " << C_CYAN << "policy" << C_RESET << " <project> <principal> Show one policy\n"
  93. << " " << C_CYAN << "policy-set" << C_RESET << " <project> <principal> '<json>'\n"
  94. << " " << C_CYAN << "policy-rm" << C_RESET << " <project> <principal>\n"
  95. << " " << C_CYAN << "help" << C_RESET << " Show this help\n\n"
  96. << C_BOLD << "Offline helpers" << C_RESET << " " << C_DIM << "(no server connection required)" << C_RESET << ":\n"
  97. << " " << C_CYAN << "generate-auth-key" << C_RESET << " Emit a base64 32-byte API key\n"
  98. << " " << C_CYAN << "generate-tls-cert" << C_RESET << " --bind <addr> Generate a self-signed TLS cert + key\n"
  99. << " " << C_DIM << "[--out-cert PATH] [--out-key PATH] [--days N]" << C_RESET << "\n"
  100. << " " << C_CYAN << "verify-subdbs" << C_RESET << " --env <path> Report documents filed under the wrong collection\n"
  101. << " " << C_DIM << "[--project NAME] read-only; safe against a running server" << C_RESET << "\n"
  102. << " " << C_CYAN << "reconcile-subdbs" << C_RESET << " --env <path> Repair misfiled documents (dry run by default)\n"
  103. << " " << C_DIM << "[--project NAME] [--apply] STOP THE SERVICE and back up before --apply" << C_RESET << "\n\n"
  104. << C_BOLD << "Options:" << C_RESET << "\n"
  105. << " --address HOST:PORT Database address (default: localhost:9004)\n"
  106. << " --project NAME Operate as this project namespace (default: default)\n";
  107. }
  108. // ---------------------------------------------------------------------------
  109. // v2.4 Stage F: offline helpers (no server connection required)
  110. // ---------------------------------------------------------------------------
  111. // Base64-encode raw bytes. Uses OpenSSL's EVP_EncodeBlock which emits the
  112. // standard base64 alphabet (no newlines) and pads with '='.
  113. std::string base64Encode(const unsigned char* data, size_t len) {
  114. if (len == 0) return {};
  115. // EVP_EncodeBlock writes ((len + 2) / 3) * 4 bytes + a NUL terminator.
  116. const size_t out_len = 4 * ((len + 2) / 3);
  117. std::string out(out_len, '\0');
  118. int written = EVP_EncodeBlock(
  119. reinterpret_cast<unsigned char*>(out.data()),
  120. data, static_cast<int>(len));
  121. if (written < 0) return {};
  122. out.resize(static_cast<size_t>(written));
  123. return out;
  124. }
  125. // Pull 32 cryptographically random bytes from getentropy() (preferred) or
  126. // /dev/urandom (fallback). Returns true on success.
  127. bool fillRandomBytes(unsigned char* buf, size_t len) {
  128. // getentropy() is limited to 256 bytes per call; our use-case is 32.
  129. if (len <= 256) {
  130. if (getentropy(buf, len) == 0) return true;
  131. }
  132. // Fallback: /dev/urandom.
  133. int fd = ::open("/dev/urandom", O_RDONLY | O_CLOEXEC);
  134. if (fd < 0) return false;
  135. size_t got = 0;
  136. while (got < len) {
  137. ssize_t n = ::read(fd, buf + got, len - got);
  138. if (n <= 0) {
  139. if (errno == EINTR) continue;
  140. ::close(fd);
  141. return false;
  142. }
  143. got += static_cast<size_t>(n);
  144. }
  145. ::close(fd);
  146. return true;
  147. }
  148. int cmdGenerateAuthKey() {
  149. unsigned char key[32];
  150. if (!fillRandomBytes(key, sizeof(key))) {
  151. std::fprintf(stderr, "error: failed to obtain entropy for key\n");
  152. return 1;
  153. }
  154. auto encoded = base64Encode(key, sizeof(key));
  155. if (encoded.empty()) {
  156. std::fprintf(stderr, "error: base64 encoding failed\n");
  157. return 1;
  158. }
  159. std::cout << encoded << "\n";
  160. return 0;
  161. }
  162. namespace {
  163. // Print the topmost OpenSSL error to stderr with a prefix.
  164. void printOpenSslError(const char* prefix) {
  165. unsigned long e = ERR_get_error();
  166. char buf[256] = {0};
  167. if (e != 0) {
  168. ERR_error_string_n(e, buf, sizeof(buf));
  169. std::fprintf(stderr, "error: %s: %s\n", prefix, buf);
  170. } else {
  171. std::fprintf(stderr, "error: %s\n", prefix);
  172. }
  173. }
  174. // Returns true if `s` parses as an IPv4 or IPv6 literal.
  175. bool looksLikeIp(const std::string& s) {
  176. unsigned char buf[16];
  177. if (inet_pton(AF_INET, s.c_str(), buf) == 1) return true;
  178. if (inet_pton(AF_INET6, s.c_str(), buf) == 1) return true;
  179. return false;
  180. }
  181. // Generate an RSA private key as an EVP_PKEY using the modern (3.x) API.
  182. EVP_PKEY* generateRsaKey(int bits) {
  183. EVP_PKEY_CTX* ctx = EVP_PKEY_CTX_new_id(EVP_PKEY_RSA, nullptr);
  184. if (!ctx) return nullptr;
  185. EVP_PKEY* pkey = nullptr;
  186. if (EVP_PKEY_keygen_init(ctx) <= 0) {
  187. EVP_PKEY_CTX_free(ctx);
  188. return nullptr;
  189. }
  190. if (EVP_PKEY_CTX_set_rsa_keygen_bits(ctx, bits) <= 0) {
  191. EVP_PKEY_CTX_free(ctx);
  192. return nullptr;
  193. }
  194. if (EVP_PKEY_keygen(ctx, &pkey) <= 0) {
  195. EVP_PKEY_CTX_free(ctx);
  196. return nullptr;
  197. }
  198. EVP_PKEY_CTX_free(ctx);
  199. return pkey;
  200. }
  201. // Write a string to disk with the given file mode. Truncates existing files.
  202. bool writeFileWithMode(const std::string& path, const std::string& contents, mode_t mode) {
  203. int fd = ::open(path.c_str(),
  204. O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC,
  205. mode);
  206. if (fd < 0) {
  207. std::fprintf(stderr, "error: open %s: %s\n", path.c_str(), std::strerror(errno));
  208. return false;
  209. }
  210. // Re-assert mode in case the file pre-existed with a wider mode and
  211. // O_CREAT was a no-op (open(2) only applies the mode on create).
  212. if (fchmod(fd, mode) != 0) {
  213. std::fprintf(stderr, "error: fchmod %s: %s\n", path.c_str(), std::strerror(errno));
  214. ::close(fd);
  215. return false;
  216. }
  217. size_t off = 0;
  218. while (off < contents.size()) {
  219. ssize_t n = ::write(fd, contents.data() + off, contents.size() - off);
  220. if (n <= 0) {
  221. if (errno == EINTR) continue;
  222. std::fprintf(stderr, "error: write %s: %s\n", path.c_str(), std::strerror(errno));
  223. ::close(fd);
  224. return false;
  225. }
  226. off += static_cast<size_t>(n);
  227. }
  228. if (::close(fd) != 0) {
  229. std::fprintf(stderr, "error: close %s: %s\n", path.c_str(), std::strerror(errno));
  230. return false;
  231. }
  232. return true;
  233. }
  234. // Serialize an X509* to a PEM string.
  235. std::string pemEncodeCert(X509* cert) {
  236. BIO* bio = BIO_new(BIO_s_mem());
  237. if (!bio) return {};
  238. if (PEM_write_bio_X509(bio, cert) != 1) {
  239. BIO_free(bio);
  240. return {};
  241. }
  242. BUF_MEM* mem = nullptr;
  243. BIO_get_mem_ptr(bio, &mem);
  244. std::string out(mem->data, mem->length);
  245. BIO_free(bio);
  246. return out;
  247. }
  248. // Serialize an EVP_PKEY* to an unencrypted PEM string (PKCS#8 format via
  249. // PEM_write_bio_PrivateKey).
  250. std::string pemEncodeKey(EVP_PKEY* key) {
  251. BIO* bio = BIO_new(BIO_s_mem());
  252. if (!bio) return {};
  253. if (PEM_write_bio_PrivateKey(bio, key, nullptr, nullptr, 0, nullptr, nullptr) != 1) {
  254. BIO_free(bio);
  255. return {};
  256. }
  257. BUF_MEM* mem = nullptr;
  258. BIO_get_mem_ptr(bio, &mem);
  259. std::string out(mem->data, mem->length);
  260. BIO_free(bio);
  261. return out;
  262. }
  263. } // anonymous namespace
  264. int cmdGenerateTlsCert(const std::vector<std::string>& params) {
  265. std::string bind;
  266. std::string out_cert = "./server.pem";
  267. std::string out_key = "./server.key";
  268. int days = 3650;
  269. for (size_t i = 0; i < params.size(); ++i) {
  270. const auto& p = params[i];
  271. auto need = [&](const char* flag) -> const std::string* {
  272. if (i + 1 >= params.size()) {
  273. std::fprintf(stderr, "error: %s requires a value\n", flag);
  274. return nullptr;
  275. }
  276. return &params[++i];
  277. };
  278. if (p == "--bind") {
  279. auto* v = need("--bind"); if (!v) return 2; bind = *v;
  280. } else if (p == "--out-cert") {
  281. auto* v = need("--out-cert"); if (!v) return 2; out_cert = *v;
  282. } else if (p == "--out-key") {
  283. auto* v = need("--out-key"); if (!v) return 2; out_key = *v;
  284. } else if (p == "--days") {
  285. auto* v = need("--days"); if (!v) return 2;
  286. try { days = std::stoi(*v); }
  287. catch (...) {
  288. std::fprintf(stderr, "error: --days must be an integer\n");
  289. return 2;
  290. }
  291. if (days <= 0) {
  292. std::fprintf(stderr, "error: --days must be > 0\n");
  293. return 2;
  294. }
  295. } else {
  296. std::fprintf(stderr, "error: unknown argument: %s\n", p.c_str());
  297. return 2;
  298. }
  299. }
  300. if (bind.empty()) {
  301. std::fprintf(stderr,
  302. "usage: generate-tls-cert --bind <addr> "
  303. "[--out-cert PATH] [--out-key PATH] [--days N]\n");
  304. return 2;
  305. }
  306. // 1. RSA 4096-bit key.
  307. EVP_PKEY* pkey = generateRsaKey(4096);
  308. if (!pkey) {
  309. printOpenSslError("RSA key generation failed");
  310. return 1;
  311. }
  312. // 2. X.509 certificate.
  313. X509* cert = X509_new();
  314. if (!cert) {
  315. printOpenSslError("X509_new failed");
  316. EVP_PKEY_free(pkey);
  317. return 1;
  318. }
  319. // Version 3 (the integer field encodes v3 as 2).
  320. if (X509_set_version(cert, 2) != 1) {
  321. printOpenSslError("X509_set_version failed");
  322. X509_free(cert); EVP_PKEY_free(pkey);
  323. return 1;
  324. }
  325. // Random 64-bit serial number.
  326. {
  327. unsigned char serial_bytes[8];
  328. if (RAND_bytes(serial_bytes, sizeof(serial_bytes)) != 1) {
  329. printOpenSslError("RAND_bytes for serial failed");
  330. X509_free(cert); EVP_PKEY_free(pkey);
  331. return 1;
  332. }
  333. // Mask the top bit so the BIGNUM is positive.
  334. serial_bytes[0] &= 0x7F;
  335. BIGNUM* bn = BN_bin2bn(serial_bytes, sizeof(serial_bytes), nullptr);
  336. if (!bn) {
  337. printOpenSslError("BN_bin2bn failed");
  338. X509_free(cert); EVP_PKEY_free(pkey);
  339. return 1;
  340. }
  341. ASN1_INTEGER* ai = BN_to_ASN1_INTEGER(bn, nullptr);
  342. BN_free(bn);
  343. if (!ai) {
  344. printOpenSslError("BN_to_ASN1_INTEGER failed");
  345. X509_free(cert); EVP_PKEY_free(pkey);
  346. return 1;
  347. }
  348. if (X509_set_serialNumber(cert, ai) != 1) {
  349. printOpenSslError("X509_set_serialNumber failed");
  350. ASN1_INTEGER_free(ai);
  351. X509_free(cert); EVP_PKEY_free(pkey);
  352. return 1;
  353. }
  354. ASN1_INTEGER_free(ai);
  355. }
  356. // Validity period.
  357. if (!X509_gmtime_adj(X509_get_notBefore(cert), 0)) {
  358. printOpenSslError("X509_gmtime_adj(notBefore) failed");
  359. X509_free(cert); EVP_PKEY_free(pkey);
  360. return 1;
  361. }
  362. long seconds = static_cast<long>(days) * 24L * 60L * 60L;
  363. if (!X509_gmtime_adj(X509_get_notAfter(cert), seconds)) {
  364. printOpenSslError("X509_gmtime_adj(notAfter) failed");
  365. X509_free(cert); EVP_PKEY_free(pkey);
  366. return 1;
  367. }
  368. // Public key.
  369. if (X509_set_pubkey(cert, pkey) != 1) {
  370. printOpenSslError("X509_set_pubkey failed");
  371. X509_free(cert); EVP_PKEY_free(pkey);
  372. return 1;
  373. }
  374. // Subject + issuer name (self-signed, so identical).
  375. X509_NAME* name = X509_get_subject_name(cert);
  376. if (X509_NAME_add_entry_by_txt(
  377. name, "CN", MBSTRING_UTF8,
  378. reinterpret_cast<const unsigned char*>(bind.c_str()),
  379. -1, -1, 0) != 1) {
  380. printOpenSslError("X509_NAME_add_entry_by_txt(CN) failed");
  381. X509_free(cert); EVP_PKEY_free(pkey);
  382. return 1;
  383. }
  384. if (X509_set_issuer_name(cert, name) != 1) {
  385. printOpenSslError("X509_set_issuer_name failed");
  386. X509_free(cert); EVP_PKEY_free(pkey);
  387. return 1;
  388. }
  389. // SubjectAltName.
  390. {
  391. std::string san = "DNS:localhost,IP:127.0.0.1";
  392. if (bind != "localhost" && bind != "127.0.0.1") {
  393. san += ',';
  394. san += looksLikeIp(bind) ? "IP:" : "DNS:";
  395. san += bind;
  396. }
  397. X509_EXTENSION* ext = X509V3_EXT_conf_nid(
  398. nullptr, nullptr, NID_subject_alt_name, san.c_str());
  399. if (!ext) {
  400. printOpenSslError("X509V3_EXT_conf_nid(SAN) failed");
  401. X509_free(cert); EVP_PKEY_free(pkey);
  402. return 1;
  403. }
  404. if (X509_add_ext(cert, ext, -1) != 1) {
  405. printOpenSslError("X509_add_ext(SAN) failed");
  406. X509_EXTENSION_free(ext);
  407. X509_free(cert); EVP_PKEY_free(pkey);
  408. return 1;
  409. }
  410. X509_EXTENSION_free(ext);
  411. }
  412. // basicConstraints CA:FALSE — a server leaf cert, not a CA.
  413. {
  414. X509_EXTENSION* ext = X509V3_EXT_conf_nid(
  415. nullptr, nullptr, NID_basic_constraints, "critical,CA:FALSE");
  416. if (ext) {
  417. X509_add_ext(cert, ext, -1);
  418. X509_EXTENSION_free(ext);
  419. }
  420. }
  421. // Sign with SHA-256.
  422. if (X509_sign(cert, pkey, EVP_sha256()) == 0) {
  423. printOpenSslError("X509_sign failed");
  424. X509_free(cert); EVP_PKEY_free(pkey);
  425. return 1;
  426. }
  427. // Serialize.
  428. std::string cert_pem = pemEncodeCert(cert);
  429. std::string key_pem = pemEncodeKey(pkey);
  430. X509_free(cert);
  431. EVP_PKEY_free(pkey);
  432. if (cert_pem.empty() || key_pem.empty()) {
  433. std::fprintf(stderr, "error: PEM encoding failed\n");
  434. return 1;
  435. }
  436. // Write key first (0600), then cert (0644). If either fails, the other
  437. // may have been written — that's acceptable; the operator will see the
  438. // error and retry.
  439. if (!writeFileWithMode(out_key, key_pem, 0600)) return 1;
  440. if (!writeFileWithMode(out_cert, cert_pem, 0644)) return 1;
  441. std::cout << "Wrote cert: " << out_cert << "\n"
  442. << "Wrote key: " << out_key << "\n";
  443. return 0;
  444. }
  445. bool execCommand(smartbotic::database::Client& client,
  446. const std::string& cmd, const std::vector<std::string>& params) {
  447. try {
  448. if (cmd == "collections") {
  449. auto collections = client.listCollections();
  450. std::cout << C_BOLD << "Collections:" << C_RESET << "\n";
  451. for (const auto& c : collections) {
  452. auto info = client.getCollectionInfo(c);
  453. int64_t count = 0;
  454. if (info) count = info->documentCount;
  455. std::cout << " " << C_CYAN << c << C_RESET
  456. << C_DIM << " (" << count << " docs)" << C_RESET << "\n";
  457. }
  458. return true;
  459. }
  460. if (cmd == "info") {
  461. if (params.empty()) { printError("usage: info <collection>"); return false; }
  462. auto info = client.getCollectionInfo(params[0]);
  463. if (!info) { printError("collection not found: " + params[0]); return false; }
  464. std::cout << C_BOLD << params[0] << C_RESET << ":\n"
  465. << " documents: " << info->documentCount << "\n"
  466. << " size: " << info->sizeBytes << " bytes\n"
  467. << " encrypted: " << (info->encrypted ? "yes" : "no") << "\n"
  468. << " max_versions: " << info->maxVersions << "\n";
  469. if (info->defaultTtlSeconds > 0)
  470. std::cout << " ttl: " << info->defaultTtlSeconds << "s\n";
  471. return true;
  472. }
  473. if (cmd == "find") {
  474. if (params.empty()) { printError("usage: find <collection> [--limit N] [--exists FIELD]"); return false; }
  475. smartbotic::database::Client::QueryOptions opts;
  476. opts.limit = 100;
  477. for (size_t i = 1; i < params.size(); ++i) {
  478. if (params[i] == "--limit" && i + 1 < params.size()) {
  479. opts.limit = static_cast<uint32_t>(std::stoul(params[++i]));
  480. } else if (params[i] == "--exists" && i + 1 < params.size()) {
  481. opts.filters.emplace_back(params[++i], smartbotic::database::Client::FilterOp::EXISTS, true);
  482. }
  483. }
  484. auto docs = client.find(params[0], opts);
  485. std::cout << C_DIM << "(" << docs.size() << " documents)" << C_RESET << "\n";
  486. for (const auto& doc : docs) {
  487. auto id = doc.value("_id", "");
  488. // Print compact summary line
  489. std::cout << C_GREEN << id << C_RESET;
  490. // Show a few key fields
  491. for (const auto& [k, v] : doc.items()) {
  492. if (k == "_id" || k == "_created_at" || k == "_updated_at") continue;
  493. auto val = v.dump();
  494. if (val.size() > 60) val = val.substr(0, 57) + "...";
  495. std::cout << " " << C_DIM << k << "=" << C_RESET << val;
  496. // Limit to 3 fields per line
  497. static int field_count = 0;
  498. if (++field_count >= 3) { field_count = 0; break; }
  499. }
  500. std::cout << "\n";
  501. }
  502. return true;
  503. }
  504. if (cmd == "get") {
  505. if (params.size() < 2) { printError("usage: get <collection> <id>"); return false; }
  506. auto doc = client.get(params[0], params[1]);
  507. if (!doc) { printError("not found: " + params[0] + "/" + params[1]); return false; }
  508. printJson(*doc);
  509. return true;
  510. }
  511. if (cmd == "upsert") {
  512. if (params.size() < 3) { printError("usage: upsert <collection> <id> '<json>'"); return false; }
  513. auto data = json::parse(params[2], nullptr, false);
  514. if (!data.is_object()) { printError("invalid JSON: " + params[2]); return false; }
  515. client.upsert(params[0], data, params[1]);
  516. std::cout << C_GREEN << "ok" << C_RESET << " " << params[0] << "/" << params[1] << "\n";
  517. return true;
  518. }
  519. if (cmd == "remove" || cmd == "delete") {
  520. if (params.size() < 2) { printError("usage: remove <collection> <id>"); return false; }
  521. // v2.11.0 T6b — the return value used to be discarded and "ok
  522. // removed" printed unconditionally. That was merely sloppy
  523. // before referential integrity: now a delete can be REFUSED (a
  524. // relation with on_delete=restrict/no_action still has children
  525. // referencing it), and the server reports that as a real error,
  526. // not deleted=false. Report the actual outcome, and surface the
  527. // server's message on refusal so an operator learns what
  528. // blocked them rather than being told it worked.
  529. std::string err;
  530. bool deleted = client.remove(params[0], params[1], err);
  531. if (!err.empty()) {
  532. printError("remove " + params[0] + "/" + params[1] + ": " + err);
  533. return false;
  534. }
  535. if (!deleted) {
  536. std::cout << C_YELLOW << "not found" << C_RESET << " "
  537. << params[0] << "/" << params[1] << "\n";
  538. return true;
  539. }
  540. std::cout << C_GREEN << "ok" << C_RESET << " removed " << params[0] << "/" << params[1] << "\n";
  541. return true;
  542. }
  543. if (cmd == "count") {
  544. if (params.empty()) { printError("usage: count <collection>"); return false; }
  545. auto info = client.getCollectionInfo(params[0]);
  546. if (!info) { printError("collection not found: " + params[0]); return false; }
  547. std::cout << info->documentCount << "\n";
  548. return true;
  549. }
  550. // ===== v2.9.0 secondary indexes =====
  551. //
  552. // Declaration is explicit because an index costs write throughput and is
  553. // not always a win: on a low-cardinality field the planner will decline to
  554. // use it, since reading the index and then fetching most of the collection
  555. // by id loses to scanning. `indexes` reports distinct values precisely so
  556. // an operator can see that coming.
  557. if (cmd == "indexes") {
  558. if (params.empty()) { printError("usage: indexes <collection>"); return false; }
  559. auto list = client.listIndexes(params[0]);
  560. if (list.empty()) {
  561. std::cout << "no indexes on " << params[0] << "\n";
  562. return true;
  563. }
  564. std::cout << C_BOLD << "field distinct entries"
  565. << C_RESET << "\n";
  566. for (const auto& i : list) {
  567. std::cout << " " << i.field
  568. << std::string(i.field.size() < 29 ? 29 - i.field.size() : 1, ' ')
  569. << i.distinctValues
  570. << std::string(std::to_string(i.distinctValues).size() < 13
  571. ? 13 - std::to_string(i.distinctValues).size()
  572. : 1, ' ')
  573. << i.entries << "\n";
  574. }
  575. return true;
  576. }
  577. if (cmd == "index-values") {
  578. if (params.size() < 2) {
  579. printError("usage: index-values <collection> <field> [limit] [asc|desc]");
  580. return false;
  581. }
  582. const uint32_t limit = params.size() > 2 ? std::stoul(params[2]) : 20;
  583. const bool asc = params.size() > 3 ? (params[3] != "desc") : true;
  584. auto vals = client.indexValues(params[0], params[1], limit, asc);
  585. if (vals.empty()) {
  586. std::cout << "no values (is " << params[1] << " indexed?)\n";
  587. return true;
  588. }
  589. std::cout << C_BOLD << "rows value" << C_RESET << "\n";
  590. for (const auto& v : vals) {
  591. const std::string c = std::to_string(v.count);
  592. std::cout << " " << c
  593. << std::string(c.size() < 9 ? 9 - c.size() : 1, ' ')
  594. << v.value.dump() << "\n";
  595. }
  596. return true;
  597. }
  598. if (cmd == "index-create") {
  599. if (params.size() < 2) {
  600. printError("usage: index-create <collection> <field>");
  601. return false;
  602. }
  603. uint64_t rows = 0;
  604. if (!client.createIndex(params[0], params[1], rows)) {
  605. printError("could not create the index (see the service log)");
  606. return false;
  607. }
  608. std::cout << "indexed " << rows << " existing row(s) on "
  609. << params[0] << "#" << params[1] << "\n";
  610. return true;
  611. }
  612. if (cmd == "index-drop") {
  613. if (params.size() < 2) {
  614. printError("usage: index-drop <collection> <field>");
  615. return false;
  616. }
  617. if (!client.dropIndex(params[0], params[1])) {
  618. printError("could not drop the index (see the service log)");
  619. return false;
  620. }
  621. std::cout << "dropped " << params[0] << "#" << params[1] << "\n";
  622. return true;
  623. }
  624. // ===== v2.11.0 T6b — relations (referential integrity) =====
  625. //
  626. // Declaration is admin-only: `_relations` is a system collection and a
  627. // relation names another collection's schema, which is not ordinary
  628. // per-collection write access. Follows the `indexes` output shape.
  629. if (cmd == "relations") {
  630. auto list = client.listRelations();
  631. if (list.empty()) {
  632. std::cout << "no relations declared\n";
  633. return true;
  634. }
  635. std::cout << C_BOLD << "name child.field -> parent on_delete enforced-at-write"
  636. << C_RESET << "\n";
  637. for (const auto& r : list) {
  638. std::cout << " " << C_CYAN << r.name << C_RESET
  639. << std::string(r.name.size() < 19 ? 19 - r.name.size() : 1, ' ')
  640. << r.child << "." << r.childField << " -> " << r.parent
  641. << " " << r.onDelete
  642. << (r.validateOnWrite ? " (validate_on_write)" : "") << "\n";
  643. }
  644. return true;
  645. }
  646. if (cmd == "relation") {
  647. if (params.empty()) { printError("usage: relation <name>"); return false; }
  648. auto r = client.getRelationInfo(params[0]);
  649. if (!r) { printError("relation not found: " + params[0]); return false; }
  650. std::cout << C_BOLD << r->name << C_RESET << ":\n"
  651. << " child: " << r->child << "\n"
  652. << " child_field: " << r->childField << "\n"
  653. << " parent: " << r->parent << "\n"
  654. << " on_delete: " << r->onDelete << "\n"
  655. << " validate_on_write: " << (r->validateOnWrite ? "yes" : "no") << "\n";
  656. return true;
  657. }
  658. if (cmd == "relation-create") {
  659. if (params.size() < 4) {
  660. printError("usage: relation-create <name> <child> <child_field> <parent> "
  661. "[on_delete] [validate_on_write]\n"
  662. " on_delete: restrict (default) | cascade | set_null | no_action\n"
  663. " note: cascade/set_null are accepted and persisted but currently "
  664. "behave as permit");
  665. return false;
  666. }
  667. const std::string onDelete = params.size() > 4 ? params[4] : "restrict";
  668. const bool validateOnWrite = params.size() > 5
  669. && (params[5] == "true" || params[5] == "1" || params[5] == "yes");
  670. // v2.11.0 T7 - the server backfills the reverse index over rows
  671. // already in the child collection as part of this call, so
  672. // rowsIndexed reports coverage the same way index-create does.
  673. uint64_t rowsIndexed = 0;
  674. if (!client.createRelation(params[0], params[1], params[2], params[3],
  675. onDelete, validateOnWrite, rowsIndexed)) {
  676. printError("could not create the relation (see the service log)");
  677. return false;
  678. }
  679. std::cout << "declared relation " << params[0] << " (" << params[1] << "."
  680. << params[2] << " -> " << params[3] << ", on_delete=" << onDelete << ")\n"
  681. << "indexed " << rowsIndexed << " existing row(s) in " << params[1] << "\n";
  682. return true;
  683. }
  684. if (cmd == "relation-drop") {
  685. if (params.empty()) { printError("usage: relation-drop <name>"); return false; }
  686. if (!client.dropRelation(params[0])) {
  687. printError("could not drop the relation (see the service log)");
  688. return false;
  689. }
  690. std::cout << "dropped relation " << params[0] << "\n";
  691. return true;
  692. }
  693. // v2.11.0 T7 - "does this relation's reverse index actually match
  694. // live data?" Read-only, changes nothing. Walks the whole reverse
  695. // index (cost is proportional to distinct parents referenced, not to
  696. // the child collection's size) so this is a migration/operator tool,
  697. // not something to run in a loop.
  698. if (cmd == "relation-check") {
  699. if (params.empty()) { printError("usage: relation-check <name>"); return false; }
  700. auto result = client.checkRelation(params[0]);
  701. if (!result.success) {
  702. printError("could not check the relation: " + result.error);
  703. return false;
  704. }
  705. if (result.totalDangling == 0) {
  706. std::cout << C_GREEN << "clean" << C_RESET << " - no dangling references for "
  707. << params[0] << "\n";
  708. return true;
  709. }
  710. std::cout << C_RED << result.totalDangling << " dangling reference(s)" << C_RESET
  711. << " for " << params[0] << ":\n";
  712. for (const auto& d : result.dangling) {
  713. std::cout << " parent " << d.parentId << " does not exist, referenced by "
  714. << d.childCount << " child document(s)";
  715. if (!d.sampleChildIds.empty()) {
  716. std::cout << " (e.g. ";
  717. for (size_t i = 0; i < d.sampleChildIds.size(); ++i) {
  718. if (i) std::cout << ", ";
  719. std::cout << d.sampleChildIds[i];
  720. }
  721. std::cout << ")";
  722. }
  723. std::cout << "\n";
  724. }
  725. if (result.dangling.size() < result.totalDangling) {
  726. std::cout << " ... " << (result.totalDangling - result.dangling.size())
  727. << " more not shown\n";
  728. }
  729. return true;
  730. }
  731. // v2.11.0 T8 — the only reachable path to relations_enforced besides
  732. // grpcurl. A partial update: touches only this one knob.
  733. if (cmd == "configure-relations") {
  734. if (params.size() < 2) {
  735. printError("usage: configure-relations <collection> <on|off>");
  736. return false;
  737. }
  738. if (params[1] != "on" && params[1] != "off") {
  739. printError("expected 'on' or 'off', got: " + params[1]);
  740. return false;
  741. }
  742. const bool enforced = params[1] == "on";
  743. if (!client.setRelationsEnforced(params[0], enforced)) {
  744. printError("could not update relations_enforced (see the service log)");
  745. return false;
  746. }
  747. std::cout << C_GREEN << "ok" << C_RESET << " " << params[0]
  748. << " relations_enforced=" << (enforced ? "on" : "off") << "\n";
  749. return true;
  750. }
  751. // v2.11.0 T5 — DescribeDelete: "what would happen if I deleted this?"
  752. // without deleting anything. A per-collection READ, not admin - any
  753. // caller who can read the collection can ask this. Cheap enough to
  754. // run before every delete: counts come from the reverse index.
  755. if (cmd == "describe-delete") {
  756. if (params.size() < 2) {
  757. printError("usage: describe-delete <collection> <id>");
  758. return false;
  759. }
  760. auto d = client.describeDelete(params[0], params[1]);
  761. if (!d.success) {
  762. printError("could not describe the delete: " + d.error);
  763. return false;
  764. }
  765. if (d.impacts.empty()) {
  766. std::cout << "no relations reference " << params[0] << "/" << params[1]
  767. << " - safe to delete\n";
  768. return true;
  769. }
  770. std::cout << (d.wouldBeBlocked
  771. ? (C_RED + std::string("would be BLOCKED") + C_RESET)
  772. : (C_GREEN + std::string("would proceed") + C_RESET))
  773. << " deleting " << params[0] << "/" << params[1] << ":\n";
  774. for (const auto& imp : d.impacts) {
  775. std::cout << " " << (imp.blocks ? C_RED : C_DIM) << "[" << imp.onDelete << "]"
  776. << C_RESET << " " << imp.relation << ": " << imp.childCount
  777. << " child document(s) in " << imp.childCollection
  778. << " via " << imp.childField;
  779. if (!imp.sampleChildIds.empty()) {
  780. std::cout << " (e.g. ";
  781. for (size_t i = 0; i < imp.sampleChildIds.size(); ++i) {
  782. if (i) std::cout << ", ";
  783. std::cout << imp.sampleChildIds[i];
  784. }
  785. std::cout << ")";
  786. }
  787. std::cout << (imp.blocks ? " BLOCKS" : "") << "\n";
  788. }
  789. return true;
  790. }
  791. // ===== v2.7.0 access policy =====
  792. //
  793. // Policy lives in the `_policies` collection and is managed through the
  794. // ordinary document API, which the server intercepts so edits refresh
  795. // its cache and the `__security__` record goes through the lockout
  796. // guards. These commands are ergonomics over that, not a second
  797. // mechanism - which is why there is no policy RPC to keep in step.
  798. if (cmd == "policies") {
  799. const std::string project = params.empty() ? "default" : params[0];
  800. auto rows = client.find("_policies", smartbotic::database::Client::QueryOptions{.limit = 1000});
  801. std::cout << C_BOLD << "policies in project '" << project << "'" << C_RESET << "\n";
  802. size_t shown = 0;
  803. for (const auto& r : rows) {
  804. const std::string id = r.value("_id", "");
  805. if (id.rfind(project + ":", 0) != 0) continue;
  806. const std::string tail = id.substr(project.size() + 1);
  807. if (tail == "__security__") continue;
  808. std::cout << " " << C_CYAN << tail << C_RESET
  809. << (r.value("admin", false) ? " (admin)" : "") << "\n";
  810. ++shown;
  811. }
  812. if (shown == 0) std::cout << C_DIM << " (none)" << C_RESET << "\n";
  813. return true;
  814. }
  815. if (cmd == "policy") {
  816. if (params.size() < 2) {
  817. printError("usage: policy <project> <principal>");
  818. return false;
  819. }
  820. auto doc = client.get("_policies", params[0] + ":" + params[1]);
  821. if (!doc) { printError("no policy for " + params[0] + ":" + params[1]); return false; }
  822. printJson(*doc);
  823. return true;
  824. }
  825. if (cmd == "policy-set") {
  826. if (params.size() < 3) {
  827. printError("usage: policy-set <project> <principal> '<json>'\n"
  828. " e.g. policy-set acme svc "
  829. "'{\"collections\":{\"users\":{\"read\":true,\"mask\":[\"ssn\"]}}}'\n"
  830. " admin: policy-set acme ops '{\"admin\":true}'");
  831. return false;
  832. }
  833. try {
  834. auto body = json::parse(params[2]);
  835. client.upsert("_policies", body, params[0] + ":" + params[1]);
  836. std::cout << C_GREEN << "ok" << C_RESET << " policy set for "
  837. << params[0] << ":" << params[1] << "\n";
  838. return true;
  839. } catch (const std::exception& e) {
  840. printError(e.what());
  841. return false;
  842. }
  843. }
  844. if (cmd == "policy-rm") {
  845. if (params.size() < 2) { printError("usage: policy-rm <project> <principal>"); return false; }
  846. try {
  847. bool ok = client.remove("_policies", params[0] + ":" + params[1]);
  848. std::cout << (ok ? "removed\n" : "not found\n");
  849. return ok;
  850. } catch (const std::exception& e) {
  851. // The server refuses to remove the last admin of a secured
  852. // project - that refusal is the lockout guard, not an error to
  853. // work around.
  854. printError(e.what());
  855. return false;
  856. }
  857. }
  858. if (cmd == "security") {
  859. const std::string project = params.empty() ? "default" : params[0];
  860. auto doc = client.get("_policies", project + ":__security__");
  861. if (!doc) {
  862. std::cout << "project '" << project << "': security "
  863. << C_GREEN << "disabled" << C_RESET
  864. << C_DIM << " (default - all access allowed)" << C_RESET << "\n";
  865. return true;
  866. }
  867. const bool on = doc->value("enabled", false);
  868. const std::string mode = doc->value("mode", "enforce");
  869. std::cout << "project '" << project << "': security "
  870. << (on ? (mode == "audit" ? C_YELLOW : C_RED) : C_GREEN)
  871. << (on ? (mode == "audit" ? "AUDIT" : "ENFORCED") : "disabled")
  872. << C_RESET << "\n";
  873. if (on && mode == "audit") {
  874. std::cout << C_DIM << " audit mode logs what it would deny and "
  875. "allows the request - watch the service log, then "
  876. "switch to enforce." << C_RESET << "\n";
  877. }
  878. return true;
  879. }
  880. if (cmd == "security-set") {
  881. if (params.size() < 2) {
  882. printError("usage: security-set <project> <on|off> [enforce|audit]\n"
  883. " Enabling is REFUSED unless some policy in the project has "
  884. "admin=true.\n"
  885. " Switch a live project on with 'audit' first.");
  886. return false;
  887. }
  888. const bool on = params[1] == "on" || params[1] == "true";
  889. const std::string mode = params.size() > 2 ? params[2] : "enforce";
  890. if (mode != "enforce" && mode != "audit") {
  891. printError("mode must be 'enforce' or 'audit'");
  892. return false;
  893. }
  894. try {
  895. json body;
  896. body["enabled"] = on;
  897. body["mode"] = mode;
  898. client.upsert("_policies", body, params[0] + ":__security__");
  899. std::cout << C_GREEN << "ok" << C_RESET << " project '" << params[0]
  900. << "' security " << (on ? mode : "disabled") << "\n";
  901. return true;
  902. } catch (const std::exception& e) {
  903. printError(e.what());
  904. return false;
  905. }
  906. }
  907. if (cmd == "lock") {
  908. if (client.setReadOnly(true)) {
  909. std::cout << C_GREEN << "ok" << C_RESET << " Database locked (read-only)\n";
  910. return true;
  911. }
  912. printError("failed to lock database");
  913. return false;
  914. }
  915. if (cmd == "unlock") {
  916. if (client.setReadOnly(false)) {
  917. std::cout << C_GREEN << "ok" << C_RESET << " Database unlocked (writes accepted)\n";
  918. return true;
  919. }
  920. printError("failed to unlock database");
  921. return false;
  922. }
  923. if (cmd == "status") {
  924. auto s = client.getReadOnlyStatus();
  925. std::cout << "Read-only: " << (s.readOnly ? (std::string(C_RED) + "YES" + C_RESET) : "no") << "\n";
  926. if (s.readOnly) {
  927. std::cout << "Reason: " << s.reason << "\n";
  928. }
  929. std::cout << "Recovery outcome: " << s.recoveryOutcome << "\n";
  930. if (!s.expectedSnapshot.empty()) {
  931. std::cout << "Expected snapshot: " << s.expectedSnapshot << "\n";
  932. }
  933. if (!s.snapshotUsed.empty()) {
  934. std::cout << "Snapshot used: " << s.snapshotUsed << "\n";
  935. }
  936. if (!s.failureReason.empty()) {
  937. std::cout << "Failure reason: " << s.failureReason << "\n";
  938. }
  939. std::cout << "WAL replayed: " << s.walEntriesReplayed << " entries\n";
  940. std::cout << "Snapshots tried: " << s.snapshotsAttempted << "\n";
  941. return true;
  942. }
  943. if (cmd == "help" || cmd == "?") {
  944. printUsage();
  945. return true;
  946. }
  947. printError("unknown command: " + cmd + " (try 'help')");
  948. return false;
  949. } catch (const std::exception& e) {
  950. printError(e.what());
  951. return false;
  952. }
  953. }
  954. // Tokenize a line, respecting single/double quotes and JSON braces
  955. std::vector<std::string> tokenize(const std::string& line) {
  956. std::vector<std::string> tokens;
  957. std::string current;
  958. int brace_depth = 0;
  959. char in_quote = 0;
  960. for (size_t i = 0; i < line.size(); ++i) {
  961. char c = line[i];
  962. if (in_quote) {
  963. current += c;
  964. if (c == in_quote && (i == 0 || line[i-1] != '\\')) {
  965. in_quote = 0;
  966. // Strip surrounding quotes for simple string tokens
  967. if (brace_depth == 0 && current.size() >= 2
  968. && (current.front() == '\'' || current.front() == '"')
  969. && current.front() == current.back()) {
  970. current = current.substr(1, current.size() - 2);
  971. }
  972. }
  973. continue;
  974. }
  975. if (c == '\'' || c == '"') {
  976. in_quote = c;
  977. current += c;
  978. continue;
  979. }
  980. if (c == '{') { brace_depth++; current += c; continue; }
  981. if (c == '}') {
  982. brace_depth--;
  983. current += c;
  984. if (brace_depth <= 0) {
  985. brace_depth = 0;
  986. tokens.push_back(current);
  987. current.clear();
  988. }
  989. continue;
  990. }
  991. if (brace_depth > 0) { current += c; continue; }
  992. if (c == ' ' || c == '\t') {
  993. if (!current.empty()) {
  994. tokens.push_back(current);
  995. current.clear();
  996. }
  997. continue;
  998. }
  999. current += c;
  1000. }
  1001. if (!current.empty()) tokens.push_back(current);
  1002. return tokens;
  1003. }
  1004. // v2.4.4 — offline sub-db placement audit / repair.
  1005. //
  1006. // `verify-subdbs` is read-only and safe against a running server.
  1007. // `reconcile-subdbs --apply` rewrites document placement and REQUIRES the
  1008. // service to be stopped: it holds an LMDB write txn over the whole env.
  1009. int cmdSubdbs(const std::string& command, const std::vector<std::string>& params) {
  1010. std::string env_path, project;
  1011. bool apply = false;
  1012. bool stamp = false;
  1013. for (size_t i = 0; i < params.size(); ++i) {
  1014. const std::string& p = params[i];
  1015. if (p == "--env" && i + 1 < params.size()) {
  1016. env_path = params[++i];
  1017. } else if (p == "--project" && i + 1 < params.size()) {
  1018. project = params[++i];
  1019. } else if (p == "--apply") {
  1020. apply = true;
  1021. } else if (p == "--stamp-identity") {
  1022. stamp = true;
  1023. } else {
  1024. printError("unknown argument: " + p);
  1025. return 2;
  1026. }
  1027. }
  1028. if (env_path.empty()) {
  1029. printError("--env <path> is required (e.g. "
  1030. "/var/lib/smartbotic-database/projects/default/env)");
  1031. return 2;
  1032. }
  1033. if (command == "verify-subdbs" && apply) {
  1034. printError("--apply is not valid for verify-subdbs; use reconcile-subdbs");
  1035. return 2;
  1036. }
  1037. try {
  1038. auto report = smartbotic::db::storage::audit(env_path, project);
  1039. smartbotic::db::storage::print_audit(report);
  1040. if (command == "verify-subdbs") {
  1041. return report.misplaced.empty() ? 0 : 1;
  1042. }
  1043. if (!apply) {
  1044. std::cout << "\n" << C_YELLOW << "Dry run." << C_RESET
  1045. << " Re-run with --apply to perform the repair.\n"
  1046. << C_DIM
  1047. << "Stop the service first, and take a backup: the repair "
  1048. "rewrites document placement in place.\n"
  1049. << C_RESET;
  1050. return report.misplaced.empty() ? 0 : 1;
  1051. }
  1052. if (stamp) {
  1053. std::cout << "\n" << C_YELLOW << "--stamp-identity:" << C_RESET
  1054. << " writing sentinels. This REQUIRES the server binary to be"
  1055. " v2.4.4 or newer;\n earlier builds do not skip the sentinel"
  1056. " and will fail on scan.\n";
  1057. }
  1058. std::cout << "\nApplying...\n";
  1059. auto res = smartbotic::db::storage::repair(env_path, report, stamp);
  1060. std::cout << C_GREEN << "done." << C_RESET
  1061. << " moved=" << res.moved
  1062. << " quarantined=" << res.quarantined
  1063. << " stamped=" << res.stamped << "\n";
  1064. for (const auto& e : res.errors) {
  1065. std::cerr << C_RED << " warn: " << C_RESET << e << "\n";
  1066. }
  1067. return res.errors.empty() ? 0 : 1;
  1068. } catch (const std::exception& e) {
  1069. printError(e.what());
  1070. return 1;
  1071. }
  1072. }
  1073. } // anonymous namespace
  1074. int main(int argc, char* argv[]) {
  1075. Args args;
  1076. // Parse flags
  1077. std::vector<std::string> positional;
  1078. for (int i = 1; i < argc; ++i) {
  1079. std::string arg = argv[i];
  1080. if (arg == "--address" && i + 1 < argc) {
  1081. args.address = argv[++i];
  1082. } else if (arg == "--project" && i + 1 < argc) {
  1083. args.project = argv[++i];
  1084. } else if (arg == "--help" || arg == "-h") {
  1085. printUsage();
  1086. return 0;
  1087. } else {
  1088. positional.push_back(arg);
  1089. }
  1090. }
  1091. if (!positional.empty()) {
  1092. args.command = positional[0];
  1093. args.params.assign(positional.begin() + 1, positional.end());
  1094. }
  1095. // Offline helpers — these don't need a running server, so dispatch
  1096. // them before opening the gRPC channel.
  1097. if (args.command == "generate-auth-key") {
  1098. return cmdGenerateAuthKey();
  1099. }
  1100. if (args.command == "generate-tls-cert") {
  1101. return cmdGenerateTlsCert(args.params);
  1102. }
  1103. if (args.command == "verify-subdbs" || args.command == "reconcile-subdbs") {
  1104. return cmdSubdbs(args.command, args.params);
  1105. }
  1106. // Connect
  1107. smartbotic::database::Client::Config clientCfg{.address = args.address};
  1108. if (!args.project.empty()) clientCfg.project = args.project;
  1109. smartbotic::database::Client client(clientCfg);
  1110. client.connect();
  1111. // Scriptable mode: single command
  1112. if (!args.command.empty()) {
  1113. return execCommand(client, args.command, args.params) ? 0 : 1;
  1114. }
  1115. // Interactive mode
  1116. std::cout << C_BOLD << "smartbotic-db-cli" << C_RESET
  1117. << " connected to " << C_CYAN << args.address << C_RESET << "\n"
  1118. << C_DIM << "Type 'help' for commands, 'exit' to quit." << C_RESET << "\n";
  1119. std::string line;
  1120. while (true) {
  1121. std::cout << C_YELLOW << "> " << C_RESET;
  1122. if (!std::getline(std::cin, line)) break;
  1123. // Trim
  1124. auto start = line.find_first_not_of(" \t");
  1125. if (start == std::string::npos) continue;
  1126. line = line.substr(start);
  1127. if (line == "exit" || line == "quit" || line == "q") break;
  1128. if (line.empty()) continue;
  1129. auto tokens = tokenize(line);
  1130. if (tokens.empty()) continue;
  1131. auto cmd = tokens[0];
  1132. std::vector<std::string> params(tokens.begin() + 1, tokens.end());
  1133. execCommand(client, cmd, params);
  1134. }
  1135. return 0;
  1136. }