main.cpp 68 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527
  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. std::cout << (r.clean() ? "CLEAN\n" : "FINDINGS - see FAIL lines\n");
  506. return r.clean() && r.atRestSealed;
  507. }
  508. if (cmd == "schema" || cmd == "schema-drop" || cmd == "schema-suggest") {
  509. if (params.empty()) {
  510. printError("usage: " + cmd + " <collection>");
  511. return false;
  512. }
  513. if (cmd == "schema") {
  514. const auto s = client.getCollectionSchema(params[0]);
  515. if (!s) {
  516. std::cout << "no schema on " << params[0] << "\n";
  517. return true;
  518. }
  519. std::cout << "mode: " << (s->mode == smartbotic::database::Client::SchemaMode::Audit ? "audit" : "enforce")
  520. << (s->armed ? "" : " (NOT ARMED: the stored schema does not compile)") << "\n"
  521. << "refusals: " << s->refusals << " audit violations: " << s->auditViolations
  522. << " (since armed)\n"
  523. << s->schema.dump(2) << "\n";
  524. return true;
  525. }
  526. if (cmd == "schema-suggest") {
  527. const uint64_t limit = params.size() > 1 ? std::stoull(params[1]) : 0;
  528. const auto s = client.suggestCollectionSchema(params[0], limit);
  529. std::cerr << "scanned " << s.rowsScanned << " row(s)" << (s.complete ? "" : " (a sample)")
  530. << "\n";
  531. std::cout << s.schema.dump(2) << "\n";
  532. return true;
  533. }
  534. const auto r = client.removeCollectionSchema(params[0]);
  535. if (!r.success) {
  536. printError(r.error);
  537. return false;
  538. }
  539. std::cout << C_GREEN << "ok" << C_RESET << " schema removed\n";
  540. return true;
  541. }
  542. if (cmd == "schema-set") {
  543. if (params.size() < 2) {
  544. printError("usage: schema-set <collection> <json|@file> [--audit]");
  545. return false;
  546. }
  547. std::string text = params[1];
  548. if (!text.empty() && text[0] == '@') {
  549. std::ifstream in(text.substr(1));
  550. if (!in) {
  551. printError("cannot read " + text.substr(1));
  552. return false;
  553. }
  554. text.assign(std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>());
  555. }
  556. nlohmann::json schema;
  557. try {
  558. schema = nlohmann::json::parse(text);
  559. } catch (const std::exception& e) {
  560. printError(std::string("not valid JSON: ") + e.what());
  561. return false;
  562. }
  563. const bool audit = std::find(params.begin(), params.end(), "--audit") != params.end();
  564. const auto r = client.setCollectionSchema(params[0], schema,
  565. audit ? smartbotic::database::Client::SchemaMode::Audit : smartbotic::database::Client::SchemaMode::Enforce);
  566. std::cout << "checked " << r.rowsChecked << " existing row(s), " << r.violatingRows
  567. << " not conforming\n";
  568. for (const auto& ex : r.examples) std::cout << " " << ex.id << ": " << ex.message << "\n";
  569. if (!r.success) {
  570. printError(r.error + (r.reason.empty() ? "" : " [" + r.reason + "]"));
  571. return false;
  572. }
  573. std::cout << C_GREEN << "ok" << C_RESET << " schema set (" << (audit ? "audit" : "enforce") << ")\n";
  574. return true;
  575. }
  576. if (cmd == "collections") {
  577. auto collections = client.listCollections();
  578. std::cout << C_BOLD << "Collections:" << C_RESET << "\n";
  579. for (const auto& c : collections) {
  580. auto info = client.getCollectionInfo(c);
  581. int64_t count = 0;
  582. if (info) count = info->documentCount;
  583. std::cout << " " << C_CYAN << c << C_RESET
  584. << C_DIM << " (" << count << " docs)" << C_RESET << "\n";
  585. }
  586. return true;
  587. }
  588. if (cmd == "info") {
  589. if (params.empty()) { printError("usage: info <collection>"); return false; }
  590. auto info = client.getCollectionInfo(params[0]);
  591. if (!info) { printError("collection not found: " + params[0]); return false; }
  592. std::cout << C_BOLD << params[0] << C_RESET << ":\n"
  593. << " documents: " << info->documentCount << "\n"
  594. << " size: " << info->sizeBytes << " bytes\n"
  595. << " encrypted: " << (info->encrypted ? "yes" : "no") << "\n"
  596. << " max_versions: " << info->maxVersions << "\n";
  597. if (info->defaultTtlSeconds > 0)
  598. std::cout << " ttl: " << info->defaultTtlSeconds << "s\n";
  599. // v2.11.4 - relations_enforced is not part of CollectionInfo (it
  600. // is a changeable setting, served by GetCollectionConfig), and
  601. // its absence here read as "the server cannot report it". Always
  602. // printed, since the default is ON and an operator should not
  603. // have to know that to learn a delete may be refused. A failed
  604. // read says so rather than printing the default.
  605. // v2.17.1 - versioning on/off: a collection whose history stopped
  606. // was otherwise visible only as a config field nobody reads.
  607. try {
  608. const auto cfg = client.getCollectionConfig(params[0]);
  609. std::cout << " versioning: "
  610. << (!cfg.versioningEnabled ? "unknown" : *cfg.versioningEnabled ? "on" : "OFF (no history is recorded)")
  611. << "\n";
  612. } catch (const std::exception&) {
  613. std::cout << " versioning: unknown (could not be read)\n";
  614. }
  615. const auto enforced = client.tryGetRelationsEnforced(params[0]);
  616. std::cout << " relations_enforced: "
  617. << (!enforced ? "unknown (could not be read)" : *enforced ? "on" : "off")
  618. << "\n";
  619. return true;
  620. }
  621. if (cmd == "find") {
  622. if (params.empty()) {
  623. printError("usage: find <collection> [--limit N] [--offset N] [--exists FIELD] [--eq FIELD VALUE]");
  624. return false;
  625. }
  626. smartbotic::database::Client::QueryOptions opts;
  627. opts.limit = 100;
  628. for (size_t i = 1; i < params.size(); ++i) {
  629. if (params[i] == "--limit" && i + 1 < params.size()) {
  630. opts.limit = static_cast<uint32_t>(std::stoul(params[++i]));
  631. } else if (params[i] == "--offset" && i + 1 < params.size()) {
  632. // v2.11.1 — paging from the CLI. Without it, walking a
  633. // collection larger than one page meant deleting as you go,
  634. // which is not available when you only want to read.
  635. opts.offset = static_cast<uint32_t>(std::stoul(params[++i]));
  636. } else if (params[i] == "--eq" && i + 2 < params.size()) {
  637. // v2.11.1 — the commonest filter, so cleanup and inspection
  638. // do not need a client program. The value is taken as JSON
  639. // when it parses as JSON and as a string otherwise, so
  640. // --eq status completed and --eq attempts 3 both work.
  641. const std::string field = params[++i];
  642. const std::string raw = params[++i];
  643. nlohmann::json val;
  644. try {
  645. val = nlohmann::json::parse(raw);
  646. } catch (const std::exception&) {
  647. val = raw;
  648. }
  649. opts.filters.emplace_back(field, smartbotic::database::Client::FilterOp::EQ, val);
  650. } else if (params[i] == "--exists" && i + 1 < params.size()) {
  651. opts.filters.emplace_back(params[++i], smartbotic::database::Client::FilterOp::EXISTS, true);
  652. }
  653. }
  654. auto docs = client.find(params[0], opts);
  655. std::cout << C_DIM << "(" << docs.size() << " documents)" << C_RESET << "\n";
  656. for (const auto& doc : docs) {
  657. auto id = doc.value("_id", "");
  658. // Print compact summary line
  659. std::cout << C_GREEN << id << C_RESET;
  660. // Show a few key fields
  661. for (const auto& [k, v] : doc.items()) {
  662. if (k == "_id" || k == "_created_at" || k == "_updated_at") continue;
  663. auto val = v.dump();
  664. if (val.size() > 60) val = val.substr(0, 57) + "...";
  665. std::cout << " " << C_DIM << k << "=" << C_RESET << val;
  666. // Limit to 3 fields per line
  667. static int field_count = 0;
  668. if (++field_count >= 3) { field_count = 0; break; }
  669. }
  670. std::cout << "\n";
  671. }
  672. return true;
  673. }
  674. if (cmd == "get") {
  675. if (params.size() < 2) { printError("usage: get <collection> <id>"); return false; }
  676. auto doc = client.get(params[0], params[1]);
  677. if (!doc) { printError("not found: " + params[0] + "/" + params[1]); return false; }
  678. printJson(*doc);
  679. return true;
  680. }
  681. if (cmd == "upsert") {
  682. if (params.size() < 3) { printError("usage: upsert <collection> <id> '<json>'"); return false; }
  683. auto data = json::parse(params[2], nullptr, false);
  684. if (!data.is_object()) { printError("invalid JSON: " + params[2]); return false; }
  685. client.upsert(params[0], data, params[1]);
  686. std::cout << C_GREEN << "ok" << C_RESET << " " << params[0] << "/" << params[1] << "\n";
  687. return true;
  688. }
  689. if (cmd == "remove" || cmd == "delete") {
  690. if (params.size() < 2) { printError("usage: remove <collection> <id>"); return false; }
  691. // v2.11.0 T6b — the return value used to be discarded and "ok
  692. // removed" printed unconditionally. That was merely sloppy
  693. // before referential integrity: now a delete can be REFUSED (a
  694. // relation with on_delete=restrict/no_action still has children
  695. // referencing it), and the server reports that as a real error,
  696. // not deleted=false. Report the actual outcome, and surface the
  697. // server's message on refusal so an operator learns what
  698. // blocked them rather than being told it worked.
  699. std::string err;
  700. bool deleted = client.remove(params[0], params[1], err);
  701. if (!err.empty()) {
  702. printError("remove " + params[0] + "/" + params[1] + ": " + err);
  703. return false;
  704. }
  705. if (!deleted) {
  706. std::cout << C_YELLOW << "not found" << C_RESET << " "
  707. << params[0] << "/" << params[1] << "\n";
  708. return true;
  709. }
  710. std::cout << C_GREEN << "ok" << C_RESET << " removed " << params[0] << "/" << params[1] << "\n";
  711. return true;
  712. }
  713. if (cmd == "count") {
  714. if (params.empty()) { printError("usage: count <collection>"); return false; }
  715. auto info = client.getCollectionInfo(params[0]);
  716. if (!info) { printError("collection not found: " + params[0]); return false; }
  717. std::cout << info->documentCount << "\n";
  718. return true;
  719. }
  720. // ===== v2.9.0 secondary indexes =====
  721. //
  722. // Declaration is explicit because an index costs write throughput and is
  723. // not always a win: on a low-cardinality field the planner will decline to
  724. // use it, since reading the index and then fetching most of the collection
  725. // by id loses to scanning. `indexes` reports distinct values precisely so
  726. // an operator can see that coming.
  727. if (cmd == "indexes") {
  728. if (params.empty()) { printError("usage: indexes <collection>"); return false; }
  729. std::vector<bool> uniqueFlags;
  730. auto list = client.listIndexes(params[0], uniqueFlags);
  731. // v2.12.0 - composite unique constraints are listed separately: they
  732. // are constraints over several fields, not indexes on one.
  733. const auto composites = client.listCompositeUniqueIndexes(params[0]);
  734. if (list.empty() && composites.empty()) {
  735. std::cout << "no indexes on " << params[0] << "\n";
  736. return true;
  737. }
  738. if (!composites.empty()) {
  739. std::cout << C_BOLD << "composite unique constraints" << C_RESET << "\n";
  740. for (const auto& cf : composites) {
  741. std::cout << " (";
  742. for (size_t i = 0; i < cf.size(); ++i) std::cout << (i ? ", " : "") << cf[i];
  743. std::cout << ")\n";
  744. }
  745. if (list.empty()) return true;
  746. }
  747. std::cout << C_BOLD << "field distinct entries unique"
  748. << C_RESET << "\n";
  749. for (size_t idx = 0; idx < list.size(); ++idx) {
  750. const auto& i = list[idx];
  751. const bool unique = idx < uniqueFlags.size() && uniqueFlags[idx];
  752. std::cout << " " << i.field
  753. << std::string(i.field.size() < 29 ? 29 - i.field.size() : 1, ' ')
  754. << i.distinctValues
  755. << std::string(std::to_string(i.distinctValues).size() < 13
  756. ? 13 - std::to_string(i.distinctValues).size()
  757. : 1, ' ')
  758. << i.entries
  759. << std::string(std::to_string(i.entries).size() < 9
  760. ? 9 - std::to_string(i.entries).size()
  761. : 1, ' ')
  762. << (unique ? "yes" : "no") << "\n";
  763. }
  764. return true;
  765. }
  766. if (cmd == "index-values") {
  767. if (params.size() < 2) {
  768. printError("usage: index-values <collection> <field> [limit] [asc|desc]");
  769. return false;
  770. }
  771. const uint32_t limit = params.size() > 2 ? std::stoul(params[2]) : 20;
  772. const bool asc = params.size() > 3 ? (params[3] != "desc") : true;
  773. auto vals = client.indexValues(params[0], params[1], limit, asc);
  774. if (vals.empty()) {
  775. std::cout << "no values (is " << params[1] << " indexed?)\n";
  776. return true;
  777. }
  778. std::cout << C_BOLD << "rows value" << C_RESET << "\n";
  779. for (const auto& v : vals) {
  780. const std::string c = std::to_string(v.count);
  781. std::cout << " " << c
  782. << std::string(c.size() < 9 ? 9 - c.size() : 1, ' ')
  783. << v.value.dump() << "\n";
  784. }
  785. return true;
  786. }
  787. if (cmd == "index-create") {
  788. if (params.size() < 2) {
  789. printError("usage: index-create <collection> <field> [--unique]");
  790. return false;
  791. }
  792. // A flag is never a field name. `index-create "users email" --unique`
  793. // (collection and field quoted as one argument) used to declare a
  794. // unique index on a field named `--unique` of a collection named
  795. // `users email` - found on a production instance, rebuilt with a WARN at every boot.
  796. if (params[0].rfind("--", 0) == 0 || params[1].rfind("--", 0) == 0) {
  797. printError("usage: index-create <collection> <field> [--unique] - '" +
  798. (params[1].rfind("--", 0) == 0 ? params[1] : params[0]) +
  799. "' is a flag, not a name (were the collection and field quoted together?)");
  800. return false;
  801. }
  802. const bool unique = std::find(params.begin(), params.end(), "--unique") != params.end();
  803. if (unique) {
  804. // v2.11.0 T11 — a duplicate-refusal is not a generic failure:
  805. // surface the examples so the operator can go fix the data
  806. // rather than guess what "could not create the index" meant.
  807. auto result = client.createUniqueIndex(params[0], params[1]);
  808. if (!result.success) {
  809. printError(result.error);
  810. if (!result.duplicateExamples.empty()) {
  811. std::cout << " colliding document ids: ";
  812. for (size_t i = 0; i < result.duplicateExamples.size(); ++i) {
  813. if (i) std::cout << ", ";
  814. std::cout << result.duplicateExamples[i];
  815. }
  816. std::cout << "\n";
  817. }
  818. return false;
  819. }
  820. std::cout << "indexed " << result.rowsIndexed << " existing row(s) on "
  821. << params[0] << "#" << params[1] << " (unique)\n";
  822. return true;
  823. }
  824. uint64_t rows = 0;
  825. if (!client.createIndex(params[0], params[1], rows)) {
  826. printError("could not create the index (see the service log)");
  827. return false;
  828. }
  829. std::cout << "indexed " << rows << " existing row(s) on "
  830. << params[0] << "#" << params[1] << "\n";
  831. return true;
  832. }
  833. // v2.12.0 - composite unique constraints.
  834. if (cmd == "unique-create" || cmd == "unique-drop") {
  835. if (params.size() < 3) {
  836. printError("usage: " + cmd + " <collection> <field> <field> [field...]");
  837. return false;
  838. }
  839. const std::vector<std::string> fields(params.begin() + 1, params.end());
  840. if (cmd == "unique-drop") {
  841. if (!client.dropCompositeUniqueIndex(params[0], fields)) {
  842. printError("could not drop the constraint (see the service log)");
  843. return false;
  844. }
  845. std::cout << C_GREEN << "ok" << C_RESET << " dropped\n";
  846. return true;
  847. }
  848. auto r = client.createCompositeUniqueIndex(params[0], fields);
  849. if (!r.success) {
  850. printError(r.error);
  851. return false;
  852. }
  853. std::cout << C_GREEN << "ok" << C_RESET << " " << (r.alreadyExisted ? "already declared" : "declared")
  854. << ", " << r.rowsIndexed << " row(s) constrained\n";
  855. return true;
  856. }
  857. if (cmd == "index-drop") {
  858. if (params.size() < 2) {
  859. printError("usage: index-drop <collection> <field>");
  860. return false;
  861. }
  862. if (!client.dropIndex(params[0], params[1])) {
  863. printError("could not drop the index (see the service log)");
  864. return false;
  865. }
  866. std::cout << "dropped " << params[0] << "#" << params[1] << "\n";
  867. return true;
  868. }
  869. // ===== v2.11.0 T6b — relations (referential integrity) =====
  870. //
  871. // Declaration is admin-only: `_relations` is a system collection and a
  872. // relation names another collection's schema, which is not ordinary
  873. // per-collection write access. Follows the `indexes` output shape.
  874. if (cmd == "relations") {
  875. // v2.11.1 — an operator asking "what is enforced on this database"
  876. // means the whole database. Scoping this to the client's own project
  877. // made it print "no relations declared" on an instance with active
  878. // enforcement in another project, while `relation <name>` (never
  879. // project-scoped) happily showed that same relation. --project
  880. // narrows it back down.
  881. auto list = client.listRelations(explicitProject);
  882. if (list.empty()) {
  883. std::cout << (explicitProject.empty()
  884. ? "no relations declared in any project\n"
  885. : "no relations declared in project '" +
  886. explicitProject + "'\n");
  887. return true;
  888. }
  889. std::cout << C_BOLD << "name child.field -> parent on_delete enforced-at-write"
  890. << C_RESET << "\n";
  891. for (const auto& r : list) {
  892. std::cout << " " << C_CYAN << r.name << C_RESET
  893. << std::string(r.name.size() < 19 ? 19 - r.name.size() : 1, ' ')
  894. << r.child << "." << r.childField << " -> " << r.parent
  895. << " " << r.onDelete
  896. << (r.validateOnWrite ? " (validate_on_write)" : "") << "\n";
  897. }
  898. return true;
  899. }
  900. if (cmd == "relation") {
  901. if (params.empty()) { printError("usage: relation <name>"); return false; }
  902. auto r = client.getRelationInfo(params[0]);
  903. if (!r) { printError("relation not found: " + params[0]); return false; }
  904. std::cout << C_BOLD << r->name << C_RESET << ":\n"
  905. << " child: " << r->child << "\n"
  906. << " child_field: " << r->childField << "\n"
  907. << " parent: " << r->parent << "\n"
  908. << " on_delete: " << r->onDelete << "\n"
  909. << " validate_on_write: " << (r->validateOnWrite ? "yes" : "no") << "\n";
  910. return true;
  911. }
  912. if (cmd == "relation-create") {
  913. if (params.size() < 4) {
  914. printError("usage: relation-create <name> <child> <child_field> <parent> "
  915. "[on_delete] [validate_on_write]\n"
  916. " on_delete: restrict (default) | cascade | set_null | no_action\n"
  917. " note (v2.11.0+): cascade deletes the referencing document "
  918. "(scalar reference) or pulls the id from the array and keeps the "
  919. "document (array reference - cascade and set_null are the same "
  920. "for arrays); set_null nulls the scalar field. no_action permits "
  921. "the delete and leaves the reference dangling.");
  922. return false;
  923. }
  924. const std::string onDelete = params.size() > 4 ? params[4] : "restrict";
  925. const bool validateOnWrite = params.size() > 5
  926. && (params[5] == "true" || params[5] == "1" || params[5] == "yes");
  927. // v2.11.0 T7 - the server backfills the reverse index over rows
  928. // already in the child collection as part of this call, so
  929. // rowsIndexed reports coverage the same way index-create does.
  930. uint64_t rowsIndexed = 0;
  931. if (!client.createRelation(params[0], params[1], params[2], params[3],
  932. onDelete, validateOnWrite, rowsIndexed)) {
  933. printError("could not create the relation (see the service log)");
  934. return false;
  935. }
  936. std::cout << "declared relation " << params[0] << " (" << params[1] << "."
  937. << params[2] << " -> " << params[3] << ", on_delete=" << onDelete << ")\n"
  938. << "indexed " << rowsIndexed << " existing row(s) in " << params[1] << "\n";
  939. return true;
  940. }
  941. if (cmd == "relation-drop") {
  942. if (params.empty()) { printError("usage: relation-drop <name>"); return false; }
  943. if (!client.dropRelation(params[0])) {
  944. printError("could not drop the relation (see the service log)");
  945. return false;
  946. }
  947. std::cout << "dropped relation " << params[0] << "\n";
  948. return true;
  949. }
  950. // v2.11.0 T7 - "does this relation's reverse index actually match
  951. // live data?" Read-only, changes nothing. Walks the whole reverse
  952. // index (cost is proportional to distinct parents referenced, not to
  953. // the child collection's size) so this is a migration/operator tool,
  954. // not something to run in a loop.
  955. if (cmd == "relation-check") {
  956. if (params.empty()) { printError("usage: relation-check <name>"); return false; }
  957. auto result = client.checkRelation(params[0]);
  958. if (!result.success) {
  959. printError("could not check the relation: " + result.error);
  960. return false;
  961. }
  962. if (result.totalDangling == 0) {
  963. std::cout << C_GREEN << "clean" << C_RESET << " - no dangling references for "
  964. << params[0] << "\n";
  965. return true;
  966. }
  967. std::cout << C_RED << result.totalDangling << " dangling reference(s)" << C_RESET
  968. << " for " << params[0] << ":\n";
  969. for (const auto& d : result.dangling) {
  970. std::cout << " parent " << d.parentId << " does not exist, referenced by "
  971. << d.childCount << " child document(s)";
  972. if (!d.sampleChildIds.empty()) {
  973. std::cout << " (e.g. ";
  974. for (size_t i = 0; i < d.sampleChildIds.size(); ++i) {
  975. if (i) std::cout << ", ";
  976. std::cout << d.sampleChildIds[i];
  977. }
  978. std::cout << ")";
  979. }
  980. std::cout << "\n";
  981. }
  982. if (result.dangling.size() < result.totalDangling) {
  983. std::cout << " ... " << (result.totalDangling - result.dangling.size())
  984. << " more not shown\n";
  985. }
  986. return true;
  987. }
  988. // v2.11.0 T8 — the only reachable path to relations_enforced besides
  989. // grpcurl. A partial update: touches only this one knob.
  990. //
  991. // v2.11.4 - with no value it READS the setting. Until then this
  992. // command could change a flag no command could show, so the state
  993. // after `configure-relations x off` was something you had to
  994. // remember rather than something you could check.
  995. if (cmd == "configure-relations") {
  996. if (params.empty()) {
  997. printError("usage: configure-relations <collection> [on|off]");
  998. return false;
  999. }
  1000. if (params.size() == 1) {
  1001. const auto current = client.tryGetRelationsEnforced(params[0]);
  1002. if (!current) {
  1003. printError("could not read relations_enforced for " + params[0]);
  1004. return false;
  1005. }
  1006. std::cout << params[0] << " relations_enforced="
  1007. << (*current ? "on" : "off") << "\n";
  1008. return true;
  1009. }
  1010. if (params[1] != "on" && params[1] != "off") {
  1011. printError("expected 'on' or 'off', got: " + params[1]);
  1012. return false;
  1013. }
  1014. const bool enforced = params[1] == "on";
  1015. if (!client.setRelationsEnforced(params[0], enforced)) {
  1016. printError("could not update relations_enforced (see the service log)");
  1017. return false;
  1018. }
  1019. std::cout << C_GREEN << "ok" << C_RESET << " " << params[0]
  1020. << " relations_enforced=" << (enforced ? "on" : "off") << "\n";
  1021. return true;
  1022. }
  1023. // v2.11.0 T5 — DescribeDelete: "what would happen if I deleted this?"
  1024. // without deleting anything. A per-collection READ, not admin - any
  1025. // caller who can read the collection can ask this. Cheap enough to
  1026. // run before every delete: counts come from the reverse index.
  1027. if (cmd == "describe-delete") {
  1028. if (params.size() < 2) {
  1029. printError("usage: describe-delete <collection> <id>");
  1030. return false;
  1031. }
  1032. auto d = client.describeDelete(params[0], params[1]);
  1033. if (!d.success) {
  1034. printError("could not describe the delete: " + d.error);
  1035. return false;
  1036. }
  1037. if (d.impacts.empty()) {
  1038. std::cout << "no relations reference " << params[0] << "/" << params[1]
  1039. << " - safe to delete\n";
  1040. return true;
  1041. }
  1042. std::cout << (d.wouldBeBlocked
  1043. ? (C_RED + std::string("would be BLOCKED") + C_RESET)
  1044. : (C_GREEN + std::string("would proceed") + C_RESET))
  1045. << " deleting " << params[0] << "/" << params[1] << ":\n";
  1046. for (const auto& imp : d.impacts) {
  1047. std::cout << " " << (imp.blocks ? C_RED : C_DIM) << "[" << imp.onDelete << "]"
  1048. << C_RESET << " " << imp.relation << ": " << imp.childCount
  1049. << " child document(s) in " << imp.childCollection
  1050. << " via " << imp.childField;
  1051. if (!imp.sampleChildIds.empty()) {
  1052. std::cout << " (e.g. ";
  1053. for (size_t i = 0; i < imp.sampleChildIds.size(); ++i) {
  1054. if (i) std::cout << ", ";
  1055. std::cout << imp.sampleChildIds[i];
  1056. }
  1057. std::cout << ")";
  1058. }
  1059. std::cout << (imp.blocks ? " BLOCKS" : "") << "\n";
  1060. }
  1061. return true;
  1062. }
  1063. // ===== v2.7.0 access policy =====
  1064. //
  1065. // Policy lives in the `_policies` collection and is managed through the
  1066. // ordinary document API, which the server intercepts so edits refresh
  1067. // its cache and the `__security__` record goes through the lockout
  1068. // guards. These commands are ergonomics over that, not a second
  1069. // mechanism - which is why there is no policy RPC to keep in step.
  1070. if (cmd == "policies") {
  1071. const std::string project = params.empty() ? "default" : params[0];
  1072. auto rows = client.find("_policies", smartbotic::database::Client::QueryOptions{.limit = 1000});
  1073. std::cout << C_BOLD << "policies in project '" << project << "'" << C_RESET << "\n";
  1074. size_t shown = 0;
  1075. for (const auto& r : rows) {
  1076. const std::string id = r.value("_id", "");
  1077. if (id.rfind(project + ":", 0) != 0) continue;
  1078. const std::string tail = id.substr(project.size() + 1);
  1079. if (tail == "__security__") continue;
  1080. std::cout << " " << C_CYAN << tail << C_RESET
  1081. << (r.value("admin", false) ? " (admin)" : "") << "\n";
  1082. ++shown;
  1083. }
  1084. if (shown == 0) std::cout << C_DIM << " (none)" << C_RESET << "\n";
  1085. return true;
  1086. }
  1087. if (cmd == "policy") {
  1088. if (params.size() < 2) {
  1089. printError("usage: policy <project> <principal>");
  1090. return false;
  1091. }
  1092. auto doc = client.get("_policies", params[0] + ":" + params[1]);
  1093. if (!doc) { printError("no policy for " + params[0] + ":" + params[1]); return false; }
  1094. printJson(*doc);
  1095. return true;
  1096. }
  1097. if (cmd == "policy-set") {
  1098. if (params.size() < 3) {
  1099. printError("usage: policy-set <project> <principal> '<json>'\n"
  1100. " e.g. policy-set acme svc "
  1101. "'{\"collections\":{\"users\":{\"read\":true,\"mask\":[\"ssn\"]}}}'\n"
  1102. " admin: policy-set acme ops '{\"admin\":true}'");
  1103. return false;
  1104. }
  1105. try {
  1106. auto body = json::parse(params[2]);
  1107. client.upsert("_policies", body, params[0] + ":" + params[1]);
  1108. std::cout << C_GREEN << "ok" << C_RESET << " policy set for "
  1109. << params[0] << ":" << params[1] << "\n";
  1110. return true;
  1111. } catch (const std::exception& e) {
  1112. printError(e.what());
  1113. return false;
  1114. }
  1115. }
  1116. if (cmd == "policy-rm") {
  1117. if (params.size() < 2) { printError("usage: policy-rm <project> <principal>"); return false; }
  1118. try {
  1119. bool ok = client.remove("_policies", params[0] + ":" + params[1]);
  1120. std::cout << (ok ? "removed\n" : "not found\n");
  1121. return ok;
  1122. } catch (const std::exception& e) {
  1123. // The server refuses to remove the last admin of a secured
  1124. // project - that refusal is the lockout guard, not an error to
  1125. // work around.
  1126. printError(e.what());
  1127. return false;
  1128. }
  1129. }
  1130. if (cmd == "security") {
  1131. const std::string project = params.empty() ? "default" : params[0];
  1132. auto doc = client.get("_policies", project + ":__security__");
  1133. if (!doc) {
  1134. std::cout << "project '" << project << "': security "
  1135. << C_GREEN << "disabled" << C_RESET
  1136. << C_DIM << " (default - all access allowed)" << C_RESET << "\n";
  1137. return true;
  1138. }
  1139. const bool on = doc->value("enabled", false);
  1140. const std::string mode = doc->value("mode", "enforce");
  1141. std::cout << "project '" << project << "': security "
  1142. << (on ? (mode == "audit" ? C_YELLOW : C_RED) : C_GREEN)
  1143. << (on ? (mode == "audit" ? "AUDIT" : "ENFORCED") : "disabled")
  1144. << C_RESET << "\n";
  1145. if (on && mode == "audit") {
  1146. std::cout << C_DIM << " audit mode logs what it would deny and "
  1147. "allows the request - watch the service log, then "
  1148. "switch to enforce." << C_RESET << "\n";
  1149. }
  1150. return true;
  1151. }
  1152. if (cmd == "security-set") {
  1153. if (params.size() < 2) {
  1154. printError("usage: security-set <project> <on|off> [enforce|audit]\n"
  1155. " Enabling is REFUSED unless some policy in the project has "
  1156. "admin=true.\n"
  1157. " Switch a live project on with 'audit' first.");
  1158. return false;
  1159. }
  1160. const bool on = params[1] == "on" || params[1] == "true";
  1161. const std::string mode = params.size() > 2 ? params[2] : "enforce";
  1162. if (mode != "enforce" && mode != "audit") {
  1163. printError("mode must be 'enforce' or 'audit'");
  1164. return false;
  1165. }
  1166. try {
  1167. json body;
  1168. body["enabled"] = on;
  1169. body["mode"] = mode;
  1170. client.upsert("_policies", body, params[0] + ":__security__");
  1171. std::cout << C_GREEN << "ok" << C_RESET << " project '" << params[0]
  1172. << "' security " << (on ? mode : "disabled") << "\n";
  1173. return true;
  1174. } catch (const std::exception& e) {
  1175. printError(e.what());
  1176. return false;
  1177. }
  1178. }
  1179. if (cmd == "lock") {
  1180. if (client.setReadOnly(true)) {
  1181. std::cout << C_GREEN << "ok" << C_RESET << " Database locked (read-only)\n";
  1182. return true;
  1183. }
  1184. printError("failed to lock database");
  1185. return false;
  1186. }
  1187. if (cmd == "unlock") {
  1188. if (client.setReadOnly(false)) {
  1189. std::cout << C_GREEN << "ok" << C_RESET << " Database unlocked (writes accepted)\n";
  1190. return true;
  1191. }
  1192. printError("failed to unlock database");
  1193. return false;
  1194. }
  1195. if (cmd == "status") {
  1196. auto s = client.getReadOnlyStatus();
  1197. std::cout << "Read-only: " << (s.readOnly ? (std::string(C_RED) + "YES" + C_RESET) : "no") << "\n";
  1198. if (s.readOnly) {
  1199. std::cout << "Reason: " << s.reason << "\n";
  1200. }
  1201. std::cout << "Recovery outcome: " << s.recoveryOutcome << "\n";
  1202. if (!s.expectedSnapshot.empty()) {
  1203. std::cout << "Expected snapshot: " << s.expectedSnapshot << "\n";
  1204. }
  1205. if (!s.snapshotUsed.empty()) {
  1206. std::cout << "Snapshot used: " << s.snapshotUsed << "\n";
  1207. }
  1208. if (!s.failureReason.empty()) {
  1209. std::cout << "Failure reason: " << s.failureReason << "\n";
  1210. }
  1211. std::cout << "WAL replayed: " << s.walEntriesReplayed << " entries\n";
  1212. std::cout << "Snapshots tried: " << s.snapshotsAttempted << "\n";
  1213. return true;
  1214. }
  1215. if (cmd == "help" || cmd == "?") {
  1216. printUsage();
  1217. return true;
  1218. }
  1219. printError("unknown command: " + cmd + " (try 'help')");
  1220. return false;
  1221. } catch (const std::exception& e) {
  1222. printError(e.what());
  1223. return false;
  1224. }
  1225. }
  1226. // Tokenize a line, respecting single/double quotes and JSON braces
  1227. std::vector<std::string> tokenize(const std::string& line) {
  1228. std::vector<std::string> tokens;
  1229. std::string current;
  1230. int brace_depth = 0;
  1231. char in_quote = 0;
  1232. for (size_t i = 0; i < line.size(); ++i) {
  1233. char c = line[i];
  1234. if (in_quote) {
  1235. current += c;
  1236. if (c == in_quote && (i == 0 || line[i-1] != '\\')) {
  1237. in_quote = 0;
  1238. // Strip surrounding quotes for simple string tokens
  1239. if (brace_depth == 0 && current.size() >= 2
  1240. && (current.front() == '\'' || current.front() == '"')
  1241. && current.front() == current.back()) {
  1242. current = current.substr(1, current.size() - 2);
  1243. }
  1244. }
  1245. continue;
  1246. }
  1247. if (c == '\'' || c == '"') {
  1248. in_quote = c;
  1249. current += c;
  1250. continue;
  1251. }
  1252. if (c == '{') { brace_depth++; current += c; continue; }
  1253. if (c == '}') {
  1254. brace_depth--;
  1255. current += c;
  1256. if (brace_depth <= 0) {
  1257. brace_depth = 0;
  1258. tokens.push_back(current);
  1259. current.clear();
  1260. }
  1261. continue;
  1262. }
  1263. if (brace_depth > 0) { current += c; continue; }
  1264. if (c == ' ' || c == '\t') {
  1265. if (!current.empty()) {
  1266. tokens.push_back(current);
  1267. current.clear();
  1268. }
  1269. continue;
  1270. }
  1271. current += c;
  1272. }
  1273. if (!current.empty()) tokens.push_back(current);
  1274. return tokens;
  1275. }
  1276. // v2.4.4 — offline sub-db placement audit / repair.
  1277. //
  1278. // `verify-subdbs` is read-only and safe against a running server.
  1279. // `reconcile-subdbs --apply` rewrites document placement and REQUIRES the
  1280. // service to be stopped: it holds an LMDB write txn over the whole env.
  1281. int cmdSubdbs(const std::string& command, const std::vector<std::string>& params) {
  1282. std::string env_path, project;
  1283. bool apply = false;
  1284. bool stamp = false;
  1285. for (size_t i = 0; i < params.size(); ++i) {
  1286. const std::string& p = params[i];
  1287. if (p == "--env" && i + 1 < params.size()) {
  1288. env_path = params[++i];
  1289. } else if (p == "--project" && i + 1 < params.size()) {
  1290. project = params[++i];
  1291. } else if (p == "--apply") {
  1292. apply = true;
  1293. } else if (p == "--stamp-identity") {
  1294. stamp = true;
  1295. } else {
  1296. printError("unknown argument: " + p);
  1297. return 2;
  1298. }
  1299. }
  1300. if (env_path.empty()) {
  1301. printError("--env <path> is required (e.g. "
  1302. "/var/lib/smartbotic-database/projects/default/env)");
  1303. return 2;
  1304. }
  1305. if (command == "verify-subdbs" && apply) {
  1306. printError("--apply is not valid for verify-subdbs; use reconcile-subdbs");
  1307. return 2;
  1308. }
  1309. try {
  1310. auto report = smartbotic::db::storage::audit(env_path, project);
  1311. smartbotic::db::storage::print_audit(report);
  1312. if (command == "verify-subdbs") {
  1313. return report.misplaced.empty() ? 0 : 1;
  1314. }
  1315. if (!apply) {
  1316. std::cout << "\n" << C_YELLOW << "Dry run." << C_RESET
  1317. << " Re-run with --apply to perform the repair.\n"
  1318. << C_DIM
  1319. << "Stop the service first, and take a backup: the repair "
  1320. "rewrites document placement in place.\n"
  1321. << C_RESET;
  1322. return report.misplaced.empty() ? 0 : 1;
  1323. }
  1324. if (stamp) {
  1325. std::cout << "\n" << C_YELLOW << "--stamp-identity:" << C_RESET
  1326. << " writing sentinels. This REQUIRES the server binary to be"
  1327. " v2.4.4 or newer;\n earlier builds do not skip the sentinel"
  1328. " and will fail on scan.\n";
  1329. }
  1330. std::cout << "\nApplying...\n";
  1331. auto res = smartbotic::db::storage::repair(env_path, report, stamp);
  1332. std::cout << C_GREEN << "done." << C_RESET
  1333. << " moved=" << res.moved
  1334. << " quarantined=" << res.quarantined
  1335. << " stamped=" << res.stamped << "\n";
  1336. for (const auto& e : res.errors) {
  1337. std::cerr << C_RED << " warn: " << C_RESET << e << "\n";
  1338. }
  1339. return res.errors.empty() ? 0 : 1;
  1340. } catch (const std::exception& e) {
  1341. printError(e.what());
  1342. return 1;
  1343. }
  1344. }
  1345. } // anonymous namespace
  1346. int main(int argc, char* argv[]) {
  1347. Args args;
  1348. // Parse flags
  1349. std::vector<std::string> positional;
  1350. for (int i = 1; i < argc; ++i) {
  1351. std::string arg = argv[i];
  1352. if (arg == "--address" && i + 1 < argc) {
  1353. args.address = argv[++i];
  1354. } else if (arg == "--project" && i + 1 < argc) {
  1355. args.project = argv[++i];
  1356. } else if (arg == "--help" || arg == "-h") {
  1357. printUsage();
  1358. return 0;
  1359. } else if (arg == "--version" || arg == "-V") {
  1360. // Offline, and before anything else: a version check must not need a
  1361. // reachable server. Same format as the service binary so the two can
  1362. // be compared at a glance.
  1363. std::cout << "smartbotic-db-cli version " << SMARTBOTIC_DB_VERSION_STRING
  1364. << " (commit " << SMARTBOTIC_DB_GIT_COMMIT_STRING << ")\n"
  1365. // The LOADED client library, which can differ from the
  1366. // binary's own version if only one package was upgraded.
  1367. // That divergence is exactly what an operator is trying to
  1368. // diagnose when they ask a binary for its version.
  1369. << "libsmartbotic-db-client "
  1370. << smartbotic::database::clientLibraryVersion()
  1371. << " (commit " << smartbotic::database::clientLibraryCommit() << ")\n";
  1372. return 0;
  1373. } else {
  1374. positional.push_back(arg);
  1375. }
  1376. }
  1377. if (!positional.empty()) {
  1378. args.command = positional[0];
  1379. args.params.assign(positional.begin() + 1, positional.end());
  1380. }
  1381. // Offline helpers — these don't need a running server, so dispatch
  1382. // them before opening the gRPC channel.
  1383. if (args.command == "generate-auth-key") {
  1384. return cmdGenerateAuthKey();
  1385. }
  1386. if (args.command == "generate-tls-cert") {
  1387. return cmdGenerateTlsCert(args.params);
  1388. }
  1389. if (args.command == "verify-subdbs" || args.command == "reconcile-subdbs") {
  1390. return cmdSubdbs(args.command, args.params);
  1391. }
  1392. // Connect
  1393. smartbotic::database::Client::Config clientCfg{.address = args.address};
  1394. if (!args.project.empty()) clientCfg.project = args.project;
  1395. smartbotic::database::Client client(clientCfg);
  1396. client.connect();
  1397. // Scriptable mode: single command
  1398. if (!args.command.empty()) {
  1399. return execCommand(client, args.command, args.params, args.project) ? 0 : 1;
  1400. }
  1401. // Interactive mode
  1402. std::cout << C_BOLD << "smartbotic-db-cli" << C_RESET
  1403. << " connected to " << C_CYAN << args.address << C_RESET << "\n"
  1404. << C_DIM << "Type 'help' for commands, 'exit' to quit." << C_RESET << "\n";
  1405. std::string line;
  1406. while (true) {
  1407. std::cout << C_YELLOW << "> " << C_RESET;
  1408. if (!std::getline(std::cin, line)) break;
  1409. // Trim
  1410. auto start = line.find_first_not_of(" \t");
  1411. if (start == std::string::npos) continue;
  1412. line = line.substr(start);
  1413. if (line == "exit" || line == "quit" || line == "q") break;
  1414. if (line.empty()) continue;
  1415. auto tokens = tokenize(line);
  1416. if (tokens.empty()) continue;
  1417. auto cmd = tokens[0];
  1418. std::vector<std::string> params(tokens.begin() + 1, tokens.end());
  1419. execCommand(client, cmd, params, args.project);
  1420. }
  1421. return 0;
  1422. }