-
Notifications
You must be signed in to change notification settings - Fork 31
feat: create a C++ sample plugin for HMAC cookie authorization. #117
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
mpwarres
merged 11 commits into
GoogleCloudPlatform:main
from
walves-cit:cpp-plugins-hmac-authcookie
Mar 5, 2025
Merged
Changes from 6 commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
708a76c
feat: adding new HMAC cookie token validation sample c++ plugin
walves-cit 77cfbd8
doc: adding README entry for new HMAC cookie token validation sample …
walves-cit 24fb088
Merge branch 'GoogleCloudPlatform:main' into cpp-plugins-hmac-authcookie
walves-cit cb6633b
fix: fix filter end stream return status
walves-cit d5019ae
Merge branch 'main' into cpp-plugins-hmac-authcookie
walves-cit 5216cf1
fix: some code improvements
walves-cit 2f18e98
Merge branch 'main' into cpp-plugins-hmac-authcookie
walves-cit 0da5257
fix: changing the logic to more realistic scenario
walves-cit 3977c6f
Merge branch 'main' into cpp-plugins-hmac-authcookie
walves-cit e986923
doc: code comments improvements
walves-cit 87b460d
Merge branch 'main' into cpp-plugins-hmac-authcookie
mpwarres File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,27 @@ | ||
| load("//:plugins.bzl", "proxy_wasm_plugin_cpp", "proxy_wasm_plugin_rust", "proxy_wasm_tests") | ||
|
|
||
| licenses(["notice"]) # Apache 2 | ||
|
|
||
| proxy_wasm_plugin_cpp( | ||
| name = "plugin_cpp.wasm", | ||
| srcs = ["plugin.cc"], | ||
| deps = [ | ||
| "@proxy_wasm_cpp_sdk//contrib:contrib_lib", | ||
| "@com_google_absl//absl/strings", | ||
| "@boringssl//:ssl", | ||
| ], | ||
| linkopts = [ | ||
| # To avoid the error: | ||
| # library_pthread.js:26: #error "STANDALONE_WASM does not support shared memories yet". | ||
| # Disabling the pthreads avoids the inclusion of the library_pthread.js. | ||
| "-sUSE_PTHREADS=0", | ||
| ], | ||
| ) | ||
|
|
||
| proxy_wasm_tests( | ||
| name = "tests", | ||
| plugins = [ | ||
| ":plugin_cpp.wasm", | ||
| ], | ||
| tests = ":tests.textpb", | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,92 @@ | ||
| // Copyright 2024 Google LLC | ||
| // | ||
| // Licensed under the Apache License, Version 2.0 (the "License"); | ||
| // you may not use this file except in compliance with the License. | ||
| // You may obtain a copy of the License at | ||
| // | ||
| // http://www.apache.org/licenses/LICENSE-2.0 | ||
| // | ||
| // Unless required by applicable law or agreed to in writing, software | ||
| // distributed under the License is distributed on an "AS IS" BASIS, | ||
| // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| // See the License for the specific language governing permissions and | ||
| // limitations under the License. | ||
|
|
||
| // [START serviceextensions_plugin_hmac_authcookie] | ||
| #include <openssl/hmac.h> | ||
|
|
||
| #include <iomanip> | ||
| #include <sstream> | ||
| #include <string> | ||
|
|
||
| #include "absl/strings/str_split.h" | ||
| #include "proxy_wasm_intrinsics.h" | ||
|
|
||
| // Replace with your desired secret key. | ||
| const std::string kSecretKey = "your_secret_key"; | ||
|
|
||
| class MyHttpContext : public Context { | ||
| public: | ||
| explicit MyHttpContext(uint32_t id, RootContext* root) : Context(id, root) {} | ||
|
|
||
| FilterHeadersStatus onRequestHeaders(uint32_t headers, | ||
| bool end_of_stream) override { | ||
| const auto token = getTokenFromCookie(); | ||
mpwarres marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if (!token.has_value()) { | ||
| LOG_INFO("Access forbidden - missing HMAC cookie."); | ||
| sendLocalResponse(403, "", "Access forbidden - missing HMAC cookie.\n", | ||
| {}); | ||
| return FilterHeadersStatus::ContinueAndEndStream; | ||
| } | ||
|
|
||
| const auto path = getRequestHeader(":path")->toString(); | ||
mpwarres marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| if (computeHmacSignature(path) != token.value()) { | ||
| LOG_INFO("Access forbidden - invalid HMAC cookie."); | ||
| sendLocalResponse(403, "", "Access forbidden - invalid HMAC cookie.\n", | ||
| {}); | ||
| return FilterHeadersStatus::ContinueAndEndStream; | ||
| } | ||
|
|
||
| return FilterHeadersStatus::Continue; | ||
| } | ||
|
|
||
| private: | ||
| // Try to get the HMAC auth token from the Cookie header. | ||
| std::optional<std::string> getTokenFromCookie() { | ||
| const auto cookies = getRequestHeader("Cookie")->toString(); | ||
| std::map<std::string, std::string> m; | ||
| for (absl::string_view sp : absl::StrSplit(cookies, "; ")) { | ||
| const std::pair<std::string, std::string> cookie = | ||
| absl::StrSplit(sp, absl::MaxSplits('=', 1)); | ||
| if (cookie.first == "Authorization") { | ||
| return cookie.second; | ||
| } | ||
| } | ||
|
|
||
| return std::nullopt; | ||
| } | ||
|
|
||
| // Helper function to convert binary data to a hexadecimal string. | ||
| std::string toHexString(const unsigned char* data, size_t length) { | ||
mpwarres marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| std::stringstream ss; | ||
| for (size_t i = 0; i < length; ++i) { | ||
| ss << std::hex << std::setw(2) << std::setfill('0') << (int)data[i]; | ||
| } | ||
| return ss.str(); | ||
| } | ||
|
|
||
| // Function to compute the HMAC signature. | ||
| std::string computeHmacSignature(const std::string& data) { | ||
| unsigned char* result; | ||
| unsigned int len = EVP_MAX_MD_SIZE; | ||
|
|
||
| result = HMAC(EVP_sha256(), kSecretKey.c_str(), kSecretKey.length(), | ||
| reinterpret_cast<const unsigned char*>(data.c_str()), | ||
| data.length(), nullptr, &len); | ||
| return toHexString(result, len); | ||
| } | ||
| }; | ||
|
|
||
| static RegisterContextFactory register_StaticContext( | ||
| CONTEXT_FACTORY(MyHttpContext), ROOT_FACTORY(RootContext)); | ||
| // [END serviceextensions_plugin_hmac_authcookie] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,43 @@ | ||
| # With a valid token, request allowed and token removed from :path. | ||
| test { | ||
| name: "WithValidHMACToken" | ||
| benchmark: false | ||
| request_headers { | ||
| input { | ||
| header { key: ":path" value: "/somepage/otherpage?param1=value1¶m2=value2" } | ||
| header { key: "Cookie" value: "SomeCookie=SomeValue; Authorization=48277f04685e364e0e3f3c4bfa78cb91293d304bbf196829334cb1c4a741d6b0" } | ||
| } | ||
| result { | ||
| has_header { key: ":path" value: "/somepage/otherpage?param1=value1¶m2=value2" } | ||
| } | ||
| } | ||
| } | ||
| # No token set, forbidden request. | ||
| test { | ||
| name: "NoToken" | ||
| request_headers { | ||
| input { | ||
| header { key: ":path" value: "/admin" } | ||
| } | ||
| result { | ||
| immediate { http_status: 403 details: "" } | ||
| body { exact: "Access forbidden - missing HMAC cookie.\n" } | ||
| log { regex: ".+Access forbidden - missing HMAC cookie.$" } | ||
| } | ||
| } | ||
| } | ||
| # invalid token, forbidden request. | ||
| test { | ||
| name: "InvalidToken" | ||
| request_headers { | ||
| input { | ||
| header { key: ":path" value: "/somepage/otherpage?param1=value1" } | ||
| header { key: "Cookie" value: "SomeCookie=SomeValue; Authorization=48277f04685e364e0e3f3c4bfa78cb91293d304bbf196829334cb1c4a741d6b0" } | ||
| } | ||
| result { | ||
| immediate { http_status: 403 details: "" } | ||
| body { exact: "Access forbidden - invalid HMAC cookie.\n" } | ||
| log { regex: ".+Access forbidden - invalid HMAC cookie.$" } | ||
| } | ||
| } | ||
| } |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.