Perform insensitive string compare of cookie SameSite attribute (#1706)

Co-authored-by: Omar Mohamed <omar@omar-laptop.lan>
This commit is contained in:
Omar Mohamed Khallaf 2023-08-14 04:41:34 +03:00 committed by GitHub
parent 43b014cc24
commit 5509091ab8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 40 additions and 4 deletions

View File

@ -18,6 +18,7 @@
#include <drogon/utils/string_view.h> #include <drogon/utils/string_view.h>
#include <trantor/utils/Date.h> #include <trantor/utils/Date.h>
#include <trantor/utils/Logger.h> #include <trantor/utils/Logger.h>
#include <cctype>
#include <string> #include <string>
#include <limits> #include <limits>
@ -295,25 +296,60 @@ class DROGON_EXPORT Cookie
return sameSite_; return sameSite_;
} }
/**
* @brief Compare two strings ignoring the their cases
*
* @param str1 string to check its value
* @param str2 string to check against, written in lower case
*
* @note the function is optimized to check for cookie's samesite value
* where we check if the value equals to a specific value we already know in
* str2. so the function doesn't apply tolower to the second argument
* str2 as it's always in lower case.
*
* @return 0 if both strings are equall ignoring case, negative value if lhs
* is smaller than rhs and vice versa
*/
static int stricmp(const string_view str1, const string_view str2)
{
auto str1Len{str1.length()};
auto str2Len{str2.length()};
if (str1Len != str2Len)
return str1Len - str2Len;
for (size_t idx{0}; idx < str1Len; ++idx)
{
auto lowerChar{tolower(str1[idx])};
if (lowerChar != str2[idx])
{
return lowerChar - str2[idx];
}
}
return 0;
}
/** /**
* @brief Converts a string value to its associated enum class SameSite * @brief Converts a string value to its associated enum class SameSite
* value * value
*/ */
static SameSite convertString2SameSite(const string_view &sameSite) static SameSite convertString2SameSite(const string_view &sameSite)
{ {
if (sameSite == "Lax") if (stricmp(sameSite, "lax") == 0)
{ {
return Cookie::SameSite::kLax; return Cookie::SameSite::kLax;
} }
else if (sameSite == "Strict") else if (stricmp(sameSite, "strict") == 0)
{ {
return Cookie::SameSite::kStrict; return Cookie::SameSite::kStrict;
} }
else if (sameSite == "None") else if (stricmp(sameSite, "none") == 0)
{ {
return Cookie::SameSite::kNone; return Cookie::SameSite::kNone;
} }
else if (sameSite != "Null") else if (stricmp(sameSite, "null") != 0)
{ {
LOG_WARN LOG_WARN
<< "'" << sameSite << "'" << sameSite