main.cpp 65 KB

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