settings.cpp 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. #include "errors.hpp"
  2. #include "functions/net_guard.hpp"
  3. #include "json_http.hpp"
  4. #include "server.hpp"
  5. namespace svapi {
  6. void registerSettingsRoutes(ApiServer& s) {
  7. auto& svr = s.raw(); ServerDeps* d = &s.deps();
  8. svr.Get("/api/v1/settings", [d](const httplib::Request& req, httplib::Response& res) {
  9. requireAdmin(requireKey(*d, req));
  10. auto snap = d->settings.snapshot();
  11. nlohmann::json j = snap->toJson();
  12. bool keySet = !snap->openaiApiKey.empty();
  13. j.erase("openai_api_key");
  14. j["openai_api_key_set"] = keySet;
  15. bool captchaSecretSet = !snap->captchaSecret.empty();
  16. j.erase("captcha_secret");
  17. j["captcha_secret_set"] = captchaSecretSet;
  18. sendJson(res, 200, j);
  19. });
  20. svr.Put("/api/v1/settings", [d](const httplib::Request& req, httplib::Response& res) {
  21. requireAdmin(requireKey(*d, req));
  22. auto body = bodyJson(req);
  23. // Start from the current snapshot (preserve unspecified fields).
  24. Settings updated = *d->settings.snapshot();
  25. if (body.contains("openai_api_base"))
  26. updated.openaiApiBase = body["openai_api_base"].get<std::string>();
  27. // Only overwrite the key if a non-empty string is supplied.
  28. if (body.contains("openai_api_key")) {
  29. std::string k = body["openai_api_key"].get<std::string>();
  30. if (!k.empty()) updated.openaiApiKey = k;
  31. }
  32. if (body.contains("default_embedding_model"))
  33. updated.defaultEmbeddingModel = body["default_embedding_model"].get<std::string>();
  34. if (body.contains("cors_origins") && body["cors_origins"].is_array())
  35. updated.corsOrigins = body["cors_origins"].get<std::vector<std::string>>();
  36. if (body.contains("session_ttl_minutes"))
  37. updated.sessionTtlMinutes = body["session_ttl_minutes"].get<uint32_t>();
  38. if (body.contains("webui_enabled"))
  39. updated.webuiEnabled = body["webui_enabled"].get<bool>();
  40. if (body.contains("default_project"))
  41. updated.defaultProject = body["default_project"].get<std::string>();
  42. if (body.contains("embedding_connect_timeout_sec"))
  43. updated.embeddingConnectTimeoutSec = body["embedding_connect_timeout_sec"].get<uint32_t>();
  44. if (body.contains("embedding_read_timeout_sec"))
  45. updated.embeddingReadTimeoutSec = body["embedding_read_timeout_sec"].get<uint32_t>();
  46. // 0.18.1. These four were added to Settings and to the GET in the same
  47. // commit and NOT here, so the route answered 200 and discarded them -
  48. // a setting that reads back its default however many times you write it
  49. // is the accepted-and-ignored defect this codebase keeps meeting, and
  50. // it was caught by a round-trip check against the built deb rather than
  51. // by any test. The handler is an explicit allow-list, so adding a field
  52. // to Settings is never enough on its own.
  53. if (body.contains("embedding_connect_cap_sec"))
  54. updated.embeddingConnectCapSec = body["embedding_connect_cap_sec"].get<uint32_t>();
  55. if (body.contains("vector_filter_scan_cap"))
  56. updated.vectorFilterScanCap = body["vector_filter_scan_cap"].get<uint32_t>();
  57. if (body.contains("captcha_connect_timeout_sec"))
  58. updated.captchaConnectTimeoutSec = body["captcha_connect_timeout_sec"].get<uint32_t>();
  59. if (body.contains("captcha_read_timeout_sec"))
  60. updated.captchaReadTimeoutSec = body["captcha_read_timeout_sec"].get<uint32_t>();
  61. if (body.contains("embedding_cache_size"))
  62. updated.embeddingCacheSize = body["embedding_cache_size"].get<uint32_t>();
  63. if (body.contains("embedding_cache_ttl_sec"))
  64. updated.embeddingCacheTtlSec = body["embedding_cache_ttl_sec"].get<uint32_t>();
  65. if (body.contains("embedding_cache_max_bytes"))
  66. updated.embeddingCacheMaxBytes = body["embedding_cache_max_bytes"].get<uint64_t>();
  67. if (body.contains("embedding_cache_normalize"))
  68. updated.embeddingCacheNormalize = body["embedding_cache_normalize"].get<bool>();
  69. if (body.contains("embedding_client_pool_size"))
  70. updated.embeddingClientPoolSize = body["embedding_client_pool_size"].get<uint32_t>();
  71. if (body.contains("function_egress_blocked_cidrs")) {
  72. const nlohmann::json& raw = body["function_egress_blocked_cidrs"];
  73. if (!raw.is_array())
  74. throw ApiError(ErrCode::Unprocessable, "validation",
  75. "function_egress_blocked_cidrs must be an array of CIDR strings");
  76. std::vector<std::string> cidrs;
  77. for (const auto& e : raw) {
  78. if (!e.is_string())
  79. throw ApiError(ErrCode::Unprocessable, "validation",
  80. "function_egress_blocked_cidrs must contain only strings");
  81. const std::string c = e.get<std::string>();
  82. if (c.empty()) continue;
  83. // Validated HERE, not when a function first calls out. A typo in
  84. // an egress blocklist is a hole in the guard, and the operator
  85. // who typed it is the only person able to fix it - telling them
  86. // now beats a warning in some later run's log.
  87. if (!functions::parseCidr(c).has_value())
  88. throw ApiError(ErrCode::Unprocessable, "invalid_cidr",
  89. "not a valid CIDR or address: '" + c + "'",
  90. {{"entry", c}});
  91. cidrs.push_back(c);
  92. }
  93. updated.functionEgressBlockedCidrs = std::move(cidrs);
  94. }
  95. if (body.contains("function_egress_allow_private")) {
  96. if (!body["function_egress_allow_private"].is_boolean())
  97. throw ApiError(ErrCode::Unprocessable, "validation",
  98. "function_egress_allow_private must be a boolean");
  99. updated.functionEgressAllowPrivate = body["function_egress_allow_private"].get<bool>();
  100. }
  101. if (body.contains("captcha_provider"))
  102. updated.captchaProvider = body["captcha_provider"].get<std::string>();
  103. // Only overwrite the secret if a non-empty string is supplied (mirror openai_api_key handling).
  104. if (body.contains("captcha_secret")) {
  105. std::string cs = body["captcha_secret"].get<std::string>();
  106. if (!cs.empty()) updated.captchaSecret = cs;
  107. }
  108. if (body.contains("captcha_verify_url"))
  109. updated.captchaVerifyUrl = body["captcha_verify_url"].get<std::string>();
  110. d->settings.save(updated);
  111. sendJson(res, 200, {{"ok", true}});
  112. });
  113. // Server-global read-only lock (not per project). GET reflects the DB's own
  114. // authoritative state - the DB can also enter read-only by itself after a
  115. // failed/degraded recovery, not only via an operator's PUT here, so `reason`
  116. // (when non-empty) tells the caller which it was.
  117. svr.Get(R"(/api/v1/admin/readonly)", [d](const httplib::Request& req, httplib::Response& res) {
  118. requireAdmin(requireKey(*d, req));
  119. auto st = d->db.client().getReadOnlyStatus();
  120. nlohmann::json j{{"readonly", st.readOnly}, {"scope", "server"}};
  121. if (!st.reason.empty()) j["reason"] = st.reason;
  122. sendJson(res, 200, j);
  123. });
  124. svr.Put(R"(/api/v1/admin/readonly)", [d](const httplib::Request& req, httplib::Response& res) {
  125. requireAdmin(requireKey(*d, req));
  126. auto body = bodyJson(req);
  127. if (!body.is_object() || !body.contains("readonly") || !body["readonly"].is_boolean())
  128. throw ApiError(ErrCode::Unprocessable, "validation", "readonly (boolean) is required");
  129. const bool ro = body["readonly"].get<bool>();
  130. if (!d->db.client().setReadOnly(ro))
  131. throw ApiError(ErrCode::Unavailable, "db_error", "failed to set read-only mode");
  132. auto st = d->db.client().getReadOnlyStatus();
  133. nlohmann::json j{{"readonly", st.readOnly}, {"scope", "server"}};
  134. if (!st.reason.empty()) j["reason"] = st.reason;
  135. sendJson(res, 200, j);
  136. });
  137. }
  138. } // namespace svapi