main.cpp 68 KB

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