main.cpp 61 KB

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