main.cpp 60 KB

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