main.cpp 60 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397
  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. // A flag is never a field name. `index-create "users email" --unique`
  667. // (collection and field quoted as one argument) used to declare a
  668. // unique index on a field named `--unique` of a collection named
  669. // `users email` - found on zeus, rebuilt with a WARN at every boot.
  670. if (params[0].rfind("--", 0) == 0 || params[1].rfind("--", 0) == 0) {
  671. printError("usage: index-create <collection> <field> [--unique] - '" +
  672. (params[1].rfind("--", 0) == 0 ? params[1] : params[0]) +
  673. "' is a flag, not a name (were the collection and field quoted together?)");
  674. return false;
  675. }
  676. const bool unique = std::find(params.begin(), params.end(), "--unique") != params.end();
  677. if (unique) {
  678. // v2.11.0 T11 — a duplicate-refusal is not a generic failure:
  679. // surface the examples so the operator can go fix the data
  680. // rather than guess what "could not create the index" meant.
  681. auto result = client.createUniqueIndex(params[0], params[1]);
  682. if (!result.success) {
  683. printError(result.error);
  684. if (!result.duplicateExamples.empty()) {
  685. std::cout << " colliding document ids: ";
  686. for (size_t i = 0; i < result.duplicateExamples.size(); ++i) {
  687. if (i) std::cout << ", ";
  688. std::cout << result.duplicateExamples[i];
  689. }
  690. std::cout << "\n";
  691. }
  692. return false;
  693. }
  694. std::cout << "indexed " << result.rowsIndexed << " existing row(s) on "
  695. << params[0] << "#" << params[1] << " (unique)\n";
  696. return true;
  697. }
  698. uint64_t rows = 0;
  699. if (!client.createIndex(params[0], params[1], rows)) {
  700. printError("could not create the index (see the service log)");
  701. return false;
  702. }
  703. std::cout << "indexed " << rows << " existing row(s) on "
  704. << params[0] << "#" << params[1] << "\n";
  705. return true;
  706. }
  707. // v2.12.0 - composite unique constraints.
  708. if (cmd == "unique-create" || cmd == "unique-drop") {
  709. if (params.size() < 3) {
  710. printError("usage: " + cmd + " <collection> <field> <field> [field...]");
  711. return false;
  712. }
  713. const std::vector<std::string> fields(params.begin() + 1, params.end());
  714. if (cmd == "unique-drop") {
  715. if (!client.dropCompositeUniqueIndex(params[0], fields)) {
  716. printError("could not drop the constraint (see the service log)");
  717. return false;
  718. }
  719. std::cout << C_GREEN << "ok" << C_RESET << " dropped\n";
  720. return true;
  721. }
  722. auto r = client.createCompositeUniqueIndex(params[0], fields);
  723. if (!r.success) {
  724. printError(r.error);
  725. return false;
  726. }
  727. std::cout << C_GREEN << "ok" << C_RESET << " " << (r.alreadyExisted ? "already declared" : "declared")
  728. << ", " << r.rowsIndexed << " row(s) constrained\n";
  729. return true;
  730. }
  731. if (cmd == "index-drop") {
  732. if (params.size() < 2) {
  733. printError("usage: index-drop <collection> <field>");
  734. return false;
  735. }
  736. if (!client.dropIndex(params[0], params[1])) {
  737. printError("could not drop the index (see the service log)");
  738. return false;
  739. }
  740. std::cout << "dropped " << params[0] << "#" << params[1] << "\n";
  741. return true;
  742. }
  743. // ===== v2.11.0 T6b — relations (referential integrity) =====
  744. //
  745. // Declaration is admin-only: `_relations` is a system collection and a
  746. // relation names another collection's schema, which is not ordinary
  747. // per-collection write access. Follows the `indexes` output shape.
  748. if (cmd == "relations") {
  749. // v2.11.1 — an operator asking "what is enforced on this database"
  750. // means the whole database. Scoping this to the client's own project
  751. // made it print "no relations declared" on an instance with active
  752. // enforcement in another project, while `relation <name>` (never
  753. // project-scoped) happily showed that same relation. --project
  754. // narrows it back down.
  755. auto list = client.listRelations(explicitProject);
  756. if (list.empty()) {
  757. std::cout << (explicitProject.empty()
  758. ? "no relations declared in any project\n"
  759. : "no relations declared in project '" +
  760. explicitProject + "'\n");
  761. return true;
  762. }
  763. std::cout << C_BOLD << "name child.field -> parent on_delete enforced-at-write"
  764. << C_RESET << "\n";
  765. for (const auto& r : list) {
  766. std::cout << " " << C_CYAN << r.name << C_RESET
  767. << std::string(r.name.size() < 19 ? 19 - r.name.size() : 1, ' ')
  768. << r.child << "." << r.childField << " -> " << r.parent
  769. << " " << r.onDelete
  770. << (r.validateOnWrite ? " (validate_on_write)" : "") << "\n";
  771. }
  772. return true;
  773. }
  774. if (cmd == "relation") {
  775. if (params.empty()) { printError("usage: relation <name>"); return false; }
  776. auto r = client.getRelationInfo(params[0]);
  777. if (!r) { printError("relation not found: " + params[0]); return false; }
  778. std::cout << C_BOLD << r->name << C_RESET << ":\n"
  779. << " child: " << r->child << "\n"
  780. << " child_field: " << r->childField << "\n"
  781. << " parent: " << r->parent << "\n"
  782. << " on_delete: " << r->onDelete << "\n"
  783. << " validate_on_write: " << (r->validateOnWrite ? "yes" : "no") << "\n";
  784. return true;
  785. }
  786. if (cmd == "relation-create") {
  787. if (params.size() < 4) {
  788. printError("usage: relation-create <name> <child> <child_field> <parent> "
  789. "[on_delete] [validate_on_write]\n"
  790. " on_delete: restrict (default) | cascade | set_null | no_action\n"
  791. " note (v2.11.0+): cascade deletes the referencing document "
  792. "(scalar reference) or pulls the id from the array and keeps the "
  793. "document (array reference - cascade and set_null are the same "
  794. "for arrays); set_null nulls the scalar field. no_action permits "
  795. "the delete and leaves the reference dangling.");
  796. return false;
  797. }
  798. const std::string onDelete = params.size() > 4 ? params[4] : "restrict";
  799. const bool validateOnWrite = params.size() > 5
  800. && (params[5] == "true" || params[5] == "1" || params[5] == "yes");
  801. // v2.11.0 T7 - the server backfills the reverse index over rows
  802. // already in the child collection as part of this call, so
  803. // rowsIndexed reports coverage the same way index-create does.
  804. uint64_t rowsIndexed = 0;
  805. if (!client.createRelation(params[0], params[1], params[2], params[3],
  806. onDelete, validateOnWrite, rowsIndexed)) {
  807. printError("could not create the relation (see the service log)");
  808. return false;
  809. }
  810. std::cout << "declared relation " << params[0] << " (" << params[1] << "."
  811. << params[2] << " -> " << params[3] << ", on_delete=" << onDelete << ")\n"
  812. << "indexed " << rowsIndexed << " existing row(s) in " << params[1] << "\n";
  813. return true;
  814. }
  815. if (cmd == "relation-drop") {
  816. if (params.empty()) { printError("usage: relation-drop <name>"); return false; }
  817. if (!client.dropRelation(params[0])) {
  818. printError("could not drop the relation (see the service log)");
  819. return false;
  820. }
  821. std::cout << "dropped relation " << params[0] << "\n";
  822. return true;
  823. }
  824. // v2.11.0 T7 - "does this relation's reverse index actually match
  825. // live data?" Read-only, changes nothing. Walks the whole reverse
  826. // index (cost is proportional to distinct parents referenced, not to
  827. // the child collection's size) so this is a migration/operator tool,
  828. // not something to run in a loop.
  829. if (cmd == "relation-check") {
  830. if (params.empty()) { printError("usage: relation-check <name>"); return false; }
  831. auto result = client.checkRelation(params[0]);
  832. if (!result.success) {
  833. printError("could not check the relation: " + result.error);
  834. return false;
  835. }
  836. if (result.totalDangling == 0) {
  837. std::cout << C_GREEN << "clean" << C_RESET << " - no dangling references for "
  838. << params[0] << "\n";
  839. return true;
  840. }
  841. std::cout << C_RED << result.totalDangling << " dangling reference(s)" << C_RESET
  842. << " for " << params[0] << ":\n";
  843. for (const auto& d : result.dangling) {
  844. std::cout << " parent " << d.parentId << " does not exist, referenced by "
  845. << d.childCount << " child document(s)";
  846. if (!d.sampleChildIds.empty()) {
  847. std::cout << " (e.g. ";
  848. for (size_t i = 0; i < d.sampleChildIds.size(); ++i) {
  849. if (i) std::cout << ", ";
  850. std::cout << d.sampleChildIds[i];
  851. }
  852. std::cout << ")";
  853. }
  854. std::cout << "\n";
  855. }
  856. if (result.dangling.size() < result.totalDangling) {
  857. std::cout << " ... " << (result.totalDangling - result.dangling.size())
  858. << " more not shown\n";
  859. }
  860. return true;
  861. }
  862. // v2.11.0 T8 — the only reachable path to relations_enforced besides
  863. // grpcurl. A partial update: touches only this one knob.
  864. //
  865. // v2.11.4 - with no value it READS the setting. Until then this
  866. // command could change a flag no command could show, so the state
  867. // after `configure-relations x off` was something you had to
  868. // remember rather than something you could check.
  869. if (cmd == "configure-relations") {
  870. if (params.empty()) {
  871. printError("usage: configure-relations <collection> [on|off]");
  872. return false;
  873. }
  874. if (params.size() == 1) {
  875. const auto current = client.tryGetRelationsEnforced(params[0]);
  876. if (!current) {
  877. printError("could not read relations_enforced for " + params[0]);
  878. return false;
  879. }
  880. std::cout << params[0] << " relations_enforced="
  881. << (*current ? "on" : "off") << "\n";
  882. return true;
  883. }
  884. if (params[1] != "on" && params[1] != "off") {
  885. printError("expected 'on' or 'off', got: " + params[1]);
  886. return false;
  887. }
  888. const bool enforced = params[1] == "on";
  889. if (!client.setRelationsEnforced(params[0], enforced)) {
  890. printError("could not update relations_enforced (see the service log)");
  891. return false;
  892. }
  893. std::cout << C_GREEN << "ok" << C_RESET << " " << params[0]
  894. << " relations_enforced=" << (enforced ? "on" : "off") << "\n";
  895. return true;
  896. }
  897. // v2.11.0 T5 — DescribeDelete: "what would happen if I deleted this?"
  898. // without deleting anything. A per-collection READ, not admin - any
  899. // caller who can read the collection can ask this. Cheap enough to
  900. // run before every delete: counts come from the reverse index.
  901. if (cmd == "describe-delete") {
  902. if (params.size() < 2) {
  903. printError("usage: describe-delete <collection> <id>");
  904. return false;
  905. }
  906. auto d = client.describeDelete(params[0], params[1]);
  907. if (!d.success) {
  908. printError("could not describe the delete: " + d.error);
  909. return false;
  910. }
  911. if (d.impacts.empty()) {
  912. std::cout << "no relations reference " << params[0] << "/" << params[1]
  913. << " - safe to delete\n";
  914. return true;
  915. }
  916. std::cout << (d.wouldBeBlocked
  917. ? (C_RED + std::string("would be BLOCKED") + C_RESET)
  918. : (C_GREEN + std::string("would proceed") + C_RESET))
  919. << " deleting " << params[0] << "/" << params[1] << ":\n";
  920. for (const auto& imp : d.impacts) {
  921. std::cout << " " << (imp.blocks ? C_RED : C_DIM) << "[" << imp.onDelete << "]"
  922. << C_RESET << " " << imp.relation << ": " << imp.childCount
  923. << " child document(s) in " << imp.childCollection
  924. << " via " << imp.childField;
  925. if (!imp.sampleChildIds.empty()) {
  926. std::cout << " (e.g. ";
  927. for (size_t i = 0; i < imp.sampleChildIds.size(); ++i) {
  928. if (i) std::cout << ", ";
  929. std::cout << imp.sampleChildIds[i];
  930. }
  931. std::cout << ")";
  932. }
  933. std::cout << (imp.blocks ? " BLOCKS" : "") << "\n";
  934. }
  935. return true;
  936. }
  937. // ===== v2.7.0 access policy =====
  938. //
  939. // Policy lives in the `_policies` collection and is managed through the
  940. // ordinary document API, which the server intercepts so edits refresh
  941. // its cache and the `__security__` record goes through the lockout
  942. // guards. These commands are ergonomics over that, not a second
  943. // mechanism - which is why there is no policy RPC to keep in step.
  944. if (cmd == "policies") {
  945. const std::string project = params.empty() ? "default" : params[0];
  946. auto rows = client.find("_policies", smartbotic::database::Client::QueryOptions{.limit = 1000});
  947. std::cout << C_BOLD << "policies in project '" << project << "'" << C_RESET << "\n";
  948. size_t shown = 0;
  949. for (const auto& r : rows) {
  950. const std::string id = r.value("_id", "");
  951. if (id.rfind(project + ":", 0) != 0) continue;
  952. const std::string tail = id.substr(project.size() + 1);
  953. if (tail == "__security__") continue;
  954. std::cout << " " << C_CYAN << tail << C_RESET
  955. << (r.value("admin", false) ? " (admin)" : "") << "\n";
  956. ++shown;
  957. }
  958. if (shown == 0) std::cout << C_DIM << " (none)" << C_RESET << "\n";
  959. return true;
  960. }
  961. if (cmd == "policy") {
  962. if (params.size() < 2) {
  963. printError("usage: policy <project> <principal>");
  964. return false;
  965. }
  966. auto doc = client.get("_policies", params[0] + ":" + params[1]);
  967. if (!doc) { printError("no policy for " + params[0] + ":" + params[1]); return false; }
  968. printJson(*doc);
  969. return true;
  970. }
  971. if (cmd == "policy-set") {
  972. if (params.size() < 3) {
  973. printError("usage: policy-set <project> <principal> '<json>'\n"
  974. " e.g. policy-set acme svc "
  975. "'{\"collections\":{\"users\":{\"read\":true,\"mask\":[\"ssn\"]}}}'\n"
  976. " admin: policy-set acme ops '{\"admin\":true}'");
  977. return false;
  978. }
  979. try {
  980. auto body = json::parse(params[2]);
  981. client.upsert("_policies", body, params[0] + ":" + params[1]);
  982. std::cout << C_GREEN << "ok" << C_RESET << " policy set for "
  983. << params[0] << ":" << params[1] << "\n";
  984. return true;
  985. } catch (const std::exception& e) {
  986. printError(e.what());
  987. return false;
  988. }
  989. }
  990. if (cmd == "policy-rm") {
  991. if (params.size() < 2) { printError("usage: policy-rm <project> <principal>"); return false; }
  992. try {
  993. bool ok = client.remove("_policies", params[0] + ":" + params[1]);
  994. std::cout << (ok ? "removed\n" : "not found\n");
  995. return ok;
  996. } catch (const std::exception& e) {
  997. // The server refuses to remove the last admin of a secured
  998. // project - that refusal is the lockout guard, not an error to
  999. // work around.
  1000. printError(e.what());
  1001. return false;
  1002. }
  1003. }
  1004. if (cmd == "security") {
  1005. const std::string project = params.empty() ? "default" : params[0];
  1006. auto doc = client.get("_policies", project + ":__security__");
  1007. if (!doc) {
  1008. std::cout << "project '" << project << "': security "
  1009. << C_GREEN << "disabled" << C_RESET
  1010. << C_DIM << " (default - all access allowed)" << C_RESET << "\n";
  1011. return true;
  1012. }
  1013. const bool on = doc->value("enabled", false);
  1014. const std::string mode = doc->value("mode", "enforce");
  1015. std::cout << "project '" << project << "': security "
  1016. << (on ? (mode == "audit" ? C_YELLOW : C_RED) : C_GREEN)
  1017. << (on ? (mode == "audit" ? "AUDIT" : "ENFORCED") : "disabled")
  1018. << C_RESET << "\n";
  1019. if (on && mode == "audit") {
  1020. std::cout << C_DIM << " audit mode logs what it would deny and "
  1021. "allows the request - watch the service log, then "
  1022. "switch to enforce." << C_RESET << "\n";
  1023. }
  1024. return true;
  1025. }
  1026. if (cmd == "security-set") {
  1027. if (params.size() < 2) {
  1028. printError("usage: security-set <project> <on|off> [enforce|audit]\n"
  1029. " Enabling is REFUSED unless some policy in the project has "
  1030. "admin=true.\n"
  1031. " Switch a live project on with 'audit' first.");
  1032. return false;
  1033. }
  1034. const bool on = params[1] == "on" || params[1] == "true";
  1035. const std::string mode = params.size() > 2 ? params[2] : "enforce";
  1036. if (mode != "enforce" && mode != "audit") {
  1037. printError("mode must be 'enforce' or 'audit'");
  1038. return false;
  1039. }
  1040. try {
  1041. json body;
  1042. body["enabled"] = on;
  1043. body["mode"] = mode;
  1044. client.upsert("_policies", body, params[0] + ":__security__");
  1045. std::cout << C_GREEN << "ok" << C_RESET << " project '" << params[0]
  1046. << "' security " << (on ? mode : "disabled") << "\n";
  1047. return true;
  1048. } catch (const std::exception& e) {
  1049. printError(e.what());
  1050. return false;
  1051. }
  1052. }
  1053. if (cmd == "lock") {
  1054. if (client.setReadOnly(true)) {
  1055. std::cout << C_GREEN << "ok" << C_RESET << " Database locked (read-only)\n";
  1056. return true;
  1057. }
  1058. printError("failed to lock database");
  1059. return false;
  1060. }
  1061. if (cmd == "unlock") {
  1062. if (client.setReadOnly(false)) {
  1063. std::cout << C_GREEN << "ok" << C_RESET << " Database unlocked (writes accepted)\n";
  1064. return true;
  1065. }
  1066. printError("failed to unlock database");
  1067. return false;
  1068. }
  1069. if (cmd == "status") {
  1070. auto s = client.getReadOnlyStatus();
  1071. std::cout << "Read-only: " << (s.readOnly ? (std::string(C_RED) + "YES" + C_RESET) : "no") << "\n";
  1072. if (s.readOnly) {
  1073. std::cout << "Reason: " << s.reason << "\n";
  1074. }
  1075. std::cout << "Recovery outcome: " << s.recoveryOutcome << "\n";
  1076. if (!s.expectedSnapshot.empty()) {
  1077. std::cout << "Expected snapshot: " << s.expectedSnapshot << "\n";
  1078. }
  1079. if (!s.snapshotUsed.empty()) {
  1080. std::cout << "Snapshot used: " << s.snapshotUsed << "\n";
  1081. }
  1082. if (!s.failureReason.empty()) {
  1083. std::cout << "Failure reason: " << s.failureReason << "\n";
  1084. }
  1085. std::cout << "WAL replayed: " << s.walEntriesReplayed << " entries\n";
  1086. std::cout << "Snapshots tried: " << s.snapshotsAttempted << "\n";
  1087. return true;
  1088. }
  1089. if (cmd == "help" || cmd == "?") {
  1090. printUsage();
  1091. return true;
  1092. }
  1093. printError("unknown command: " + cmd + " (try 'help')");
  1094. return false;
  1095. } catch (const std::exception& e) {
  1096. printError(e.what());
  1097. return false;
  1098. }
  1099. }
  1100. // Tokenize a line, respecting single/double quotes and JSON braces
  1101. std::vector<std::string> tokenize(const std::string& line) {
  1102. std::vector<std::string> tokens;
  1103. std::string current;
  1104. int brace_depth = 0;
  1105. char in_quote = 0;
  1106. for (size_t i = 0; i < line.size(); ++i) {
  1107. char c = line[i];
  1108. if (in_quote) {
  1109. current += c;
  1110. if (c == in_quote && (i == 0 || line[i-1] != '\\')) {
  1111. in_quote = 0;
  1112. // Strip surrounding quotes for simple string tokens
  1113. if (brace_depth == 0 && current.size() >= 2
  1114. && (current.front() == '\'' || current.front() == '"')
  1115. && current.front() == current.back()) {
  1116. current = current.substr(1, current.size() - 2);
  1117. }
  1118. }
  1119. continue;
  1120. }
  1121. if (c == '\'' || c == '"') {
  1122. in_quote = c;
  1123. current += c;
  1124. continue;
  1125. }
  1126. if (c == '{') { brace_depth++; current += c; continue; }
  1127. if (c == '}') {
  1128. brace_depth--;
  1129. current += c;
  1130. if (brace_depth <= 0) {
  1131. brace_depth = 0;
  1132. tokens.push_back(current);
  1133. current.clear();
  1134. }
  1135. continue;
  1136. }
  1137. if (brace_depth > 0) { current += c; continue; }
  1138. if (c == ' ' || c == '\t') {
  1139. if (!current.empty()) {
  1140. tokens.push_back(current);
  1141. current.clear();
  1142. }
  1143. continue;
  1144. }
  1145. current += c;
  1146. }
  1147. if (!current.empty()) tokens.push_back(current);
  1148. return tokens;
  1149. }
  1150. // v2.4.4 — offline sub-db placement audit / repair.
  1151. //
  1152. // `verify-subdbs` is read-only and safe against a running server.
  1153. // `reconcile-subdbs --apply` rewrites document placement and REQUIRES the
  1154. // service to be stopped: it holds an LMDB write txn over the whole env.
  1155. int cmdSubdbs(const std::string& command, const std::vector<std::string>& params) {
  1156. std::string env_path, project;
  1157. bool apply = false;
  1158. bool stamp = false;
  1159. for (size_t i = 0; i < params.size(); ++i) {
  1160. const std::string& p = params[i];
  1161. if (p == "--env" && i + 1 < params.size()) {
  1162. env_path = params[++i];
  1163. } else if (p == "--project" && i + 1 < params.size()) {
  1164. project = params[++i];
  1165. } else if (p == "--apply") {
  1166. apply = true;
  1167. } else if (p == "--stamp-identity") {
  1168. stamp = true;
  1169. } else {
  1170. printError("unknown argument: " + p);
  1171. return 2;
  1172. }
  1173. }
  1174. if (env_path.empty()) {
  1175. printError("--env <path> is required (e.g. "
  1176. "/var/lib/smartbotic-database/projects/default/env)");
  1177. return 2;
  1178. }
  1179. if (command == "verify-subdbs" && apply) {
  1180. printError("--apply is not valid for verify-subdbs; use reconcile-subdbs");
  1181. return 2;
  1182. }
  1183. try {
  1184. auto report = smartbotic::db::storage::audit(env_path, project);
  1185. smartbotic::db::storage::print_audit(report);
  1186. if (command == "verify-subdbs") {
  1187. return report.misplaced.empty() ? 0 : 1;
  1188. }
  1189. if (!apply) {
  1190. std::cout << "\n" << C_YELLOW << "Dry run." << C_RESET
  1191. << " Re-run with --apply to perform the repair.\n"
  1192. << C_DIM
  1193. << "Stop the service first, and take a backup: the repair "
  1194. "rewrites document placement in place.\n"
  1195. << C_RESET;
  1196. return report.misplaced.empty() ? 0 : 1;
  1197. }
  1198. if (stamp) {
  1199. std::cout << "\n" << C_YELLOW << "--stamp-identity:" << C_RESET
  1200. << " writing sentinels. This REQUIRES the server binary to be"
  1201. " v2.4.4 or newer;\n earlier builds do not skip the sentinel"
  1202. " and will fail on scan.\n";
  1203. }
  1204. std::cout << "\nApplying...\n";
  1205. auto res = smartbotic::db::storage::repair(env_path, report, stamp);
  1206. std::cout << C_GREEN << "done." << C_RESET
  1207. << " moved=" << res.moved
  1208. << " quarantined=" << res.quarantined
  1209. << " stamped=" << res.stamped << "\n";
  1210. for (const auto& e : res.errors) {
  1211. std::cerr << C_RED << " warn: " << C_RESET << e << "\n";
  1212. }
  1213. return res.errors.empty() ? 0 : 1;
  1214. } catch (const std::exception& e) {
  1215. printError(e.what());
  1216. return 1;
  1217. }
  1218. }
  1219. } // anonymous namespace
  1220. int main(int argc, char* argv[]) {
  1221. Args args;
  1222. // Parse flags
  1223. std::vector<std::string> positional;
  1224. for (int i = 1; i < argc; ++i) {
  1225. std::string arg = argv[i];
  1226. if (arg == "--address" && i + 1 < argc) {
  1227. args.address = argv[++i];
  1228. } else if (arg == "--project" && i + 1 < argc) {
  1229. args.project = argv[++i];
  1230. } else if (arg == "--help" || arg == "-h") {
  1231. printUsage();
  1232. return 0;
  1233. } else if (arg == "--version" || arg == "-V") {
  1234. // Offline, and before anything else: a version check must not need a
  1235. // reachable server. Same format as the service binary so the two can
  1236. // be compared at a glance.
  1237. std::cout << "smartbotic-db-cli version " << SMARTBOTIC_DB_VERSION_STRING
  1238. << " (commit " << SMARTBOTIC_DB_GIT_COMMIT_STRING << ")\n"
  1239. // The LOADED client library, which can differ from the
  1240. // binary's own version if only one package was upgraded.
  1241. // That divergence is exactly what an operator is trying to
  1242. // diagnose when they ask a binary for its version.
  1243. << "libsmartbotic-db-client "
  1244. << smartbotic::database::clientLibraryVersion()
  1245. << " (commit " << smartbotic::database::clientLibraryCommit() << ")\n";
  1246. return 0;
  1247. } else {
  1248. positional.push_back(arg);
  1249. }
  1250. }
  1251. if (!positional.empty()) {
  1252. args.command = positional[0];
  1253. args.params.assign(positional.begin() + 1, positional.end());
  1254. }
  1255. // Offline helpers — these don't need a running server, so dispatch
  1256. // them before opening the gRPC channel.
  1257. if (args.command == "generate-auth-key") {
  1258. return cmdGenerateAuthKey();
  1259. }
  1260. if (args.command == "generate-tls-cert") {
  1261. return cmdGenerateTlsCert(args.params);
  1262. }
  1263. if (args.command == "verify-subdbs" || args.command == "reconcile-subdbs") {
  1264. return cmdSubdbs(args.command, args.params);
  1265. }
  1266. // Connect
  1267. smartbotic::database::Client::Config clientCfg{.address = args.address};
  1268. if (!args.project.empty()) clientCfg.project = args.project;
  1269. smartbotic::database::Client client(clientCfg);
  1270. client.connect();
  1271. // Scriptable mode: single command
  1272. if (!args.command.empty()) {
  1273. return execCommand(client, args.command, args.params, args.project) ? 0 : 1;
  1274. }
  1275. // Interactive mode
  1276. std::cout << C_BOLD << "smartbotic-db-cli" << C_RESET
  1277. << " connected to " << C_CYAN << args.address << C_RESET << "\n"
  1278. << C_DIM << "Type 'help' for commands, 'exit' to quit." << C_RESET << "\n";
  1279. std::string line;
  1280. while (true) {
  1281. std::cout << C_YELLOW << "> " << C_RESET;
  1282. if (!std::getline(std::cin, line)) break;
  1283. // Trim
  1284. auto start = line.find_first_not_of(" \t");
  1285. if (start == std::string::npos) continue;
  1286. line = line.substr(start);
  1287. if (line == "exit" || line == "quit" || line == "q") break;
  1288. if (line.empty()) continue;
  1289. auto tokens = tokenize(line);
  1290. if (tokens.empty()) continue;
  1291. auto cmd = tokens[0];
  1292. std::vector<std::string> params(tokens.begin() + 1, tokens.end());
  1293. execCommand(client, cmd, params, args.project);
  1294. }
  1295. return 0;
  1296. }