From d8fb7d0846e82957ce3aa50d4c3eb4c494a787b5 Mon Sep 17 00:00:00 2001 From: whaffman Date: Thu, 30 Oct 2025 23:04:27 +0100 Subject: [PATCH] feat: enhance request validation with method checks and error handling --- webserv/client/Client.cpp | 4 +++- webserv/http/RequestValidator.cpp | 14 ++++++++++++-- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/webserv/client/Client.cpp b/webserv/client/Client.cpp index fe8144e..940c3ab 100644 --- a/webserv/client/Client.cpp +++ b/webserv/client/Client.cpp @@ -1,6 +1,7 @@ #include #include // for CgiHandler #include // for ErrorHandler +#include #include // for HttpHeaders #include // for HttpRequest #include // for HttpResponse @@ -110,7 +111,8 @@ void Client::request() catch (const RequestValidator::ValidationException &e) { Log::error("Validation Exception during request handling: " + std::string(e.what())); - ErrorHandler::createErrorResponse(e.code(), *httpResponse_); + const auto &config = httpRequest_->getUri().getConfig(); + ErrorHandler::createErrorResponse(e.code(), *httpResponse_, config); return; } catch (const std::exception &e) diff --git a/webserv/http/RequestValidator.cpp b/webserv/http/RequestValidator.cpp index f033295..d223769 100644 --- a/webserv/http/RequestValidator.cpp +++ b/webserv/http/RequestValidator.cpp @@ -1,7 +1,9 @@ #include "webserv/log/Log.hpp" + #include #include +#include #include #include #include @@ -85,8 +87,15 @@ std::optional RequestValidator::validateMetho if (request->getMethod().empty()) { - return ValidationError{400, "Bad Request: Empty HTTP Method"}; + return ValidationError{400, "Bad Request: Empty or Invalid HTTP Method"}; } + + std::vector possibleMethods = {"GET", "POST", "PUT", "DELETE", "HEAD", "OPTIONS", "PATCH"}; + if (std::ranges::find(possibleMethods, request->getMethod()) == possibleMethods.end()) + { + return ValidationError{501, "Method Not Implemented"}; + } + if (allowedMethodsOpt.has_value()) { allowedMethods = std::move(*allowedMethodsOpt); @@ -102,10 +111,11 @@ std::optional RequestValidator::validateMetho return std::nullopt; // Method is allowed } } + return ValidationError{405, "Method Not Allowed"}; } -RequestValidator::ValidationException::ValidationException(int code) : code_(code){}; +RequestValidator::ValidationException::ValidationException(int code) : code_(code) {}; int RequestValidator::ValidationException::code() const noexcept {