|
| 1 | +#include <userver/server/middlewares/cors.hpp> |
| 2 | + |
| 3 | +#include <algorithm> |
| 4 | + |
| 5 | +#include <userver/components/component_config.hpp> |
| 6 | +#include <userver/components/component_context.hpp> |
| 7 | +#include <userver/formats/common/merge.hpp> |
| 8 | +#include <userver/formats/yaml/serialize.hpp> |
| 9 | +#include <userver/formats/yaml/value_builder.hpp> |
| 10 | +#include <userver/logging/log.hpp> |
| 11 | +#include <userver/server/handlers/exceptions.hpp> |
| 12 | +#include <userver/server/http/http_request.hpp> |
| 13 | +#include <userver/server/http/http_response.hpp> |
| 14 | +#include <userver/server/http/http_status.hpp> |
| 15 | +#include <userver/utils/algo.hpp> |
| 16 | +#include <userver/utils/text_light.hpp> |
| 17 | +#include <userver/yaml_config/merge_schemas.hpp> |
| 18 | + |
| 19 | +#ifndef ARCADIA_ROOT |
| 20 | +#include "generated/src/server/middlewares/cors.yaml.hpp" // Y_IGNORE |
| 21 | +#endif |
| 22 | + |
| 23 | +USERVER_NAMESPACE_BEGIN |
| 24 | + |
| 25 | +namespace server::middlewares { |
| 26 | + |
| 27 | +namespace { |
| 28 | + |
| 29 | +constexpr std::string_view kAccessControlRequestMethod = "Access-Control-Request-Method"; |
| 30 | +constexpr std::string_view kAccessControlAllowMethods = "Access-Control-Allow-Methods"; |
| 31 | +constexpr std::string_view kAccessControlAllowHeaders = "Access-Control-Allow-Headers"; |
| 32 | +constexpr std::string_view kAccessControlMaxAge = "Access-Control-Max-Age"; |
| 33 | +constexpr std::string_view kAccessControlAllowOrigin = "Access-Control-Allow-Origin"; |
| 34 | +constexpr std::string_view kAccessControlAllowCredentials = "Access-Control-Allow-Credentials"; |
| 35 | +constexpr std::string_view kAccessControlExposeHeaders = "Access-Control-Expose-Headers"; |
| 36 | + |
| 37 | +} // namespace |
| 38 | + |
| 39 | +Cors::Cors(const Config& config) |
| 40 | + : config_(config) |
| 41 | +{} |
| 42 | + |
| 43 | +void Cors::HandleRequest(http::HttpRequest& request, request::RequestContext& context) const { |
| 44 | + const auto& origin = GetOriginHeader(request); |
| 45 | + |
| 46 | + if (IsPreflightRequest(request)) { |
| 47 | + HandlePreflightRequest(request); |
| 48 | + return; // Don't call Next() for preflight requests |
| 49 | + } |
| 50 | + |
| 51 | + // For actual requests, add CORS headers and continue processing |
| 52 | + if (!origin.empty()) { |
| 53 | + if (IsOriginAllowed(origin)) { |
| 54 | + AddCorsHeaders(request, origin); |
| 55 | + } else { |
| 56 | + // NOLINTNEXTLINE(google-build-using-namespace) |
| 57 | + using namespace server::handlers; |
| 58 | + throw ClientError( |
| 59 | + HandlerErrorCode::kUnauthorized, |
| 60 | + ServiceErrorCode{"Access forbidden"}, |
| 61 | + InternalMessage{"Origin is forbidden"}, |
| 62 | + ExternalBody{"Bad Origin header"} |
| 63 | + ); |
| 64 | + } |
| 65 | + } |
| 66 | + |
| 67 | + Next(request, context); |
| 68 | +} |
| 69 | + |
| 70 | +bool Cors::IsPreflightRequest(const http::HttpRequest& request) const { |
| 71 | + return request.GetMethod() == http::HttpMethod::kOptions && request.HasHeader(kAccessControlRequestMethod); |
| 72 | +} |
| 73 | + |
| 74 | +void Cors::HandlePreflightRequest(http::HttpRequest& request) const { |
| 75 | + const auto& origin = GetOriginHeader(request); |
| 76 | + |
| 77 | + if (origin.empty() || !IsOriginAllowed(origin)) { |
| 78 | + request.GetHttpResponse().SetStatus(http::HttpStatus::kForbidden); |
| 79 | + return; |
| 80 | + } |
| 81 | + |
| 82 | + const auto& requested_method = request.GetHeader(kAccessControlRequestMethod); |
| 83 | + if (requested_method.empty()) { |
| 84 | + request.GetHttpResponse().SetStatus(http::HttpStatus::kBadRequest); |
| 85 | + return; |
| 86 | + } |
| 87 | + |
| 88 | + if (!utils::Contains(config_.allowed_methods, requested_method)) { |
| 89 | + request.GetHttpResponse().SetStatus(http::HttpStatus::kMethodNotAllowed); |
| 90 | + return; |
| 91 | + } |
| 92 | + |
| 93 | + // All checks passed, send successful preflight response |
| 94 | + auto& response = request.GetHttpResponse(); |
| 95 | + response.SetStatus(http::HttpStatus::kNoContent); |
| 96 | + |
| 97 | + AddCorsHeaders(request, origin); |
| 98 | + |
| 99 | + // Add preflight-specific headers |
| 100 | + response.SetHeader(kAccessControlAllowMethods, utils::text::Join(config_.allowed_methods, " ,")); |
| 101 | + |
| 102 | + if (!config_.allowed_headers.empty()) { |
| 103 | + response.SetHeader(kAccessControlAllowHeaders, utils::text::Join(config_.allowed_headers, ", ")); |
| 104 | + } |
| 105 | + |
| 106 | + response.SetHeader(kAccessControlMaxAge, std::to_string(config_.max_age.count())); |
| 107 | +} |
| 108 | + |
| 109 | +void Cors::AddCorsHeaders(http::HttpRequest& request, const std::string& origin) const { |
| 110 | + auto& response = request.GetHttpResponse(); |
| 111 | + |
| 112 | + // Always set the origin for allowed requests |
| 113 | + response.SetHeader(kAccessControlAllowOrigin, origin); |
| 114 | + |
| 115 | + // Set credentials header if allowed |
| 116 | + if (config_.allow_credentials) { |
| 117 | + response.SetHeader(kAccessControlAllowCredentials, std::string{"true"}); |
| 118 | + } |
| 119 | + |
| 120 | + // Set exposed headers if any |
| 121 | + if (!config_.exposed_headers.empty()) { |
| 122 | + response.SetHeader(kAccessControlExposeHeaders, utils::text::Join(config_.exposed_headers, ", ")); |
| 123 | + } |
| 124 | + |
| 125 | + response.SetHeader(USERVER_NAMESPACE::http::headers::kVary, std::string{"Origin"}); |
| 126 | +} |
| 127 | + |
| 128 | +bool Cors::IsOriginAllowed(const std::string& origin) const { |
| 129 | + if (origin.empty()) { |
| 130 | + return false; |
| 131 | + } |
| 132 | + |
| 133 | + // Check if wildcard is allowed |
| 134 | + if (utils::Contains(config_.allowed_origins, "*")) { |
| 135 | + return true; |
| 136 | + } |
| 137 | + |
| 138 | + LOG_INFO() << config_.allowed_origins; |
| 139 | + // Check for exact matches |
| 140 | + return utils::Contains(config_.allowed_origins, origin); |
| 141 | +} |
| 142 | + |
| 143 | +const std::string& Cors::GetOriginHeader(const http::HttpRequest& request) const { return request.GetHeader("Origin"); } |
| 144 | + |
| 145 | +Cors::Config Parse(const yaml_config::YamlConfig& value, formats::parse::To<Cors::Config>) { |
| 146 | + Cors::Config config; |
| 147 | + |
| 148 | + config.allowed_origins = value["allowed-origins"].As<std::vector<std::string>>(); |
| 149 | + config.allow_credentials = value["allow-credentials"].As<bool>(config.allow_credentials); |
| 150 | + config.max_age = std::chrono::seconds(value["max-age-seconds"].As<int>(config.max_age.count())); |
| 151 | + |
| 152 | + config.allowed_methods = value["allowed-methods"].As<std::vector<std::string>>(config.allowed_methods); |
| 153 | + std::sort(config.allowed_methods.begin(), config.allowed_methods.end()); |
| 154 | + |
| 155 | + config.allowed_headers = value["allowed-headers"].As<std::vector<std::string>>(config.allowed_headers); |
| 156 | + config.exposed_headers = value["exposed-headers"].As<std::vector<std::string>>({}); |
| 157 | + |
| 158 | + return config; |
| 159 | +} |
| 160 | + |
| 161 | +CorsFactory::CorsFactory(const components::ComponentConfig& config, const components::ComponentContext& context) |
| 162 | + : HttpMiddlewareFactoryBase{config, context}, |
| 163 | + global_config_{(const yaml_config::YamlConfig&)config} // Explicit slicing |
| 164 | +{} |
| 165 | + |
| 166 | +std::unique_ptr<HttpMiddlewareBase> CorsFactory::Create( |
| 167 | + const handlers::HttpHandlerBase&, |
| 168 | + yaml_config::YamlConfig middleware_config |
| 169 | +) const { |
| 170 | + formats::yaml::ValueBuilder builder = global_config_.GetRawYamlWithoutConfigVars(); |
| 171 | + formats::common::Merge(builder, middleware_config.GetRawYamlWithoutConfigVars()); |
| 172 | + yaml_config::YamlConfig config(builder.ExtractValue(), middleware_config.GetRawConfigVars()); |
| 173 | + |
| 174 | + const auto cfg = config.As<Cors::Config>(); |
| 175 | + return std::make_unique<Cors>(cfg); |
| 176 | +} |
| 177 | + |
| 178 | +yaml_config::Schema CorsFactory::GetStaticConfigSchema() { |
| 179 | + return yaml_config::MergeSchemasFromResource<ComponentBase>("src/server/middlewares/cors.yaml"); |
| 180 | +} |
| 181 | + |
| 182 | +yaml_config::Schema CorsFactory::GetMiddlewareConfigSchema() const { |
| 183 | + return yaml_config::MergeSchemasFromResource<ComponentBase>("src/server/middlewares/cors.yaml"); |
| 184 | +} |
| 185 | + |
| 186 | +} // namespace server::middlewares |
| 187 | + |
| 188 | +USERVER_NAMESPACE_END |
0 commit comments