main.cpp 57 KB

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