From d824f9474a225903c158200e69fba41382a9e17b Mon Sep 17 00:00:00 2001 From: AndrewNikkk Date: Sat, 17 Oct 2026 00:01:31 +0300 Subject: [PATCH] =?UTF-8?q?=D0=9B=D0=A02:=20=D0=BF=D1=80=D0=B0=D0=B2=D0=BA?= =?UTF-8?q?=D0=B8=20=D0=BF=D0=BE=20=D1=80=D0=B5=D0=B2=D1=8C=D1=8E=20=D0=BA?= =?UTF-8?q?=D0=BE=D0=BD=D1=82=D1=80=D0=B0=D0=BA=D1=82=D0=B0=20=D0=B8=20?= =?UTF-8?q?=D1=82=D0=B0=D0=B9=D0=BC=D0=B0=D1=83=D1=82=D0=B0=20Postgres?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 400 на некорректный JSON, NUL, unicode-пробелы, >100 участников, чужой курсор и тело логина. Клиентский лимит ожидания PostgreSQL: 503 вместо зависания при паузе БД. --- src/chat_repo.cpp | 11 ++++++ src/db.cpp | 37 ++++++++++++++++++- src/main.cpp | 93 +++++++++++++++++++++++++++++++++++++++++++---- 3 files changed, 132 insertions(+), 9 deletions(-) diff --git a/src/chat_repo.cpp b/src/chat_repo.cpp index 822af2f5..580fc71b 100644 --- a/src/chat_repo.cpp +++ b/src/chat_repo.cpp @@ -138,6 +138,17 @@ std::optional ChatRepo::list_for_user( auto lease = pool_.acquire(); pqxx::work tx(*lease); + if (cur) { + auto owner_check = tx.exec( + "SELECT 1 FROM chats WHERE id = $1 AND id IN " + "(SELECT chat_id FROM chat_members WHERE user_id = $2)", + pqxx::params{cur->id, user_id}); + if (owner_check.empty()) { + tx.commit(); + return std::nullopt; + } + } + std::string sql = "SELECT " + std::string(kChatSelect) + ", " + kCreatedUsSql + " " "FROM chats " diff --git a/src/db.cpp b/src/db.cpp index 15e12d07..e1827f5d 100644 --- a/src/db.cpp +++ b/src/db.cpp @@ -3,6 +3,10 @@ #include #include +#include +#include +#include +#include #include #include #include @@ -19,6 +23,7 @@ namespace { constexpr int kConnectTimeoutSeconds = 2; constexpr int kTcpUserTimeoutMs = 5000; constexpr int kStatementTimeoutMs = 5000; +constexpr int kClientIoTimeoutSeconds = 5; constexpr auto kAcquireTimeout = std::chrono::seconds(3); std::string add_conn_param(std::string conninfo, const std::string& key, @@ -37,9 +42,29 @@ std::string add_conn_param(std::string conninfo, const std::string& key, } bool is_alive(pqxx::connection* conn) { + std::promise done; + auto fut = done.get_future(); + std::thread th([conn, &done]() { + try { + pqxx::nontransaction tx(*conn); + tx.exec("SELECT 1"); + done.set_value(); + } catch (...) { + done.set_exception(std::current_exception()); + } + }); + if (fut.wait_for(std::chrono::seconds(kClientIoTimeoutSeconds)) != + std::future_status::ready) { + const int fd = conn->sock(); + if (fd >= 0) { + ::shutdown(fd, SHUT_RDWR); + } + th.join(); + return false; + } + th.join(); try { - pqxx::nontransaction tx(*conn); - tx.exec("SELECT 1"); + fut.get(); return true; } catch (...) { return false; @@ -196,6 +221,14 @@ std::unique_ptr open_pg_connection(const std::string& conninfo std::to_string(kConnectTimeoutSeconds)); full = add_conn_param(full, "tcp_user_timeout", std::to_string(kTcpUserTimeoutMs)); auto conn = std::make_unique(full); + const int fd = conn->sock(); + if (fd >= 0) { + timeval tv{}; + tv.tv_sec = kClientIoTimeoutSeconds; + tv.tv_usec = 0; + ::setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv)); + ::setsockopt(fd, SOL_SOCKET, SO_SNDTIMEO, &tv, sizeof(tv)); + } if (statement_timeout) { pqxx::nontransaction tx(*conn); tx.exec("SET statement_timeout = " + std::to_string(kStatementTimeoutMs)); diff --git a/src/main.cpp b/src/main.cpp index c55dfdd4..cea57cb3 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -35,6 +35,7 @@ #include #include #include +#include #include #include @@ -130,7 +131,7 @@ static std::optional parse_json_object(const std::string& body) nlohmann::json j; try { j = nlohmann::json::parse(body); - } catch (const nlohmann::json::parse_error&) { + } catch (const nlohmann::json::exception&) { return std::nullopt; } @@ -400,11 +401,62 @@ static bool json_content_type_ok( } +static bool contains_nul(const std::string& s) { + return s.find('\0') != std::string::npos; +} + +static bool is_unicode_space(uint32_t cp) { + if (cp <= 0x7F) { + return std::isspace(static_cast(cp)) != 0; + } + if (cp >= 0x2000 && cp <= 0x200A) { + return true; + } + switch (cp) { + case 0x00A0: + case 0x1680: + case 0x2028: + case 0x2029: + case 0x202F: + case 0x205F: + case 0x3000: + case 0xFEFF: + return true; + default: + return false; + } +} + static bool is_blank(const std::string& s) { - for (unsigned char c : s) { - if (!std::isspace(c)) { + size_t i = 0; + while (i < s.size()) { + const unsigned char c = static_cast(s[i]); + uint32_t cp = c; + size_t w = 1; + if (c >= 0x80) { + if ((c & 0xE0) == 0xC0 && i + 1 < s.size()) { + w = 2; + cp = (static_cast(c & 0x1F) << 6) + | (static_cast(s[i + 1]) & 0x3F); + } else if ((c & 0xF0) == 0xE0 && i + 2 < s.size()) { + w = 3; + cp = (static_cast(c & 0x0F) << 12) + | ((static_cast(s[i + 1]) & 0x3F) << 6) + | (static_cast(s[i + 2]) & 0x3F); + } else if ((c & 0xF8) == 0xF0 && i + 3 < s.size()) { + w = 4; + cp = (static_cast(c & 0x07) << 18) + | ((static_cast(s[i + 1]) & 0x3F) << 12) + | ((static_cast(s[i + 2]) & 0x3F) << 6) + | (static_cast(s[i + 3]) & 0x3F); + } else { + return false; + } + } + if (!is_unicode_space(cp)) { return false; } + i += w; } return true; } @@ -705,6 +757,13 @@ static void handle_client(int client, } } else if (method == "POST" && path == "/api/v1/auth/sessions") { + const auto body_at = request.find("\r\n\r\n"); + const std::string session_body = + body_at == std::string::npos ? "" : request.substr(body_at + 4); + if (!session_body.empty()) { + send_all(client, error_response(400, "invalid_request", + "body not allowed", request_id)); + } else { auto it = headers.find("authorization"); std::optional> creds; if (it != headers.end()) { @@ -746,6 +805,7 @@ static void handle_client(int client, send_all(client, failure_response(e, "create_session", request_id)); } } + } } else if (method == "GET" && path == "/api/v1/users/me") { if (send_auth_error()) { @@ -790,11 +850,13 @@ static void handle_client(int client, send_all(client, error_response(400, "invalid_request", "invalid fields", request_id)); } else if (!valid_username(*username) || + contains_nul(*display_name) || is_blank(*display_name) || !cps_in_range(*display_name, 1, 100)) { send_all(client, error_response(400, "invalid_request", "invalid fields", request_id)); - } else if (!cps_in_range(*password, 12, 128)) { + } else if (contains_nul(*password) || + !cps_in_range(*password, 12, 128)) { send_all(client, error_response(400, "invalid_request", "invalid password", request_id)); } else { @@ -849,9 +911,13 @@ static void handle_client(int client, if (!title || !member_ids) { send_all(client, error_response(400, "invalid_request", "invalid fields", request_id)); - } else if (is_blank(*title) || !cps_in_range(*title, 1, 100)) { + } else if (contains_nul(*title) || is_blank(*title) || + !cps_in_range(*title, 1, 100)) { send_all(client, error_response(400, "invalid_request", "invalid fields", request_id)); + } else if (member_ids->empty() || member_ids->size() > 100) { + send_all(client, error_response(400, "invalid_request", + "invalid members", request_id)); } else if (std::find(member_ids->begin(), member_ids->end(), user_id) == member_ids->end()) { send_all(client, error_response(400, "invalid_request", @@ -918,7 +984,8 @@ static void handle_client(int client, if (!text) { send_all(client, error_response(400, "invalid_request", "invalid fields", request_id)); - } else if (is_blank(*text) || !cps_in_range(*text, 1, 4000)) { + } else if (contains_nul(*text) || is_blank(*text) || + !cps_in_range(*text, 1, 4000)) { send_all(client, error_response(400, "invalid_request", "invalid fields", request_id)); } else { @@ -1189,7 +1256,19 @@ int main() { client = q.front(); q.pop(); } - handle_client(client, request_n, users, chats, messages, *sessions, pool, redis_pool.get()); + try { + handle_client(client, request_n, users, chats, messages, *sessions, pool, redis_pool.get()); + } catch (const std::exception& e) { + std::clog << "unhandled request error: " << e.what() << "\n"; + send_all(client, error_response(500, "internal_error", + "internal error", + std::to_string(request_n.load()))); + live_del(client); + ::close(client); + } catch (...) { + live_del(client); + ::close(client); + } } }); }