main.cpp 67 KB

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