Skip to content

Commit

Permalink
JwtAuthn: support completing padding on forward jwt payload header (e…
Browse files Browse the repository at this point in the history
…nvoyproxy#16752)

Signed-off-by: Xuyang Tao <[email protected]>
  • Loading branch information
TAOXUY authored and Le Yao committed Sep 30, 2021
1 parent 16bdba2 commit 7ebd4b8
Show file tree
Hide file tree
Showing 12 changed files with 130 additions and 6 deletions.
11 changes: 10 additions & 1 deletion api/envoy/extensions/filters/http/jwt_authn/v3/config.proto
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ option (udpa.annotations.file_status).package_version_status = ACTIVE;
// cache_duration:
// seconds: 300
//
// [#next-free-field: 11]
// [#next-free-field: 12]
message JwtProvider {
option (udpa.annotations.versioning).previous_message_type =
"envoy.config.filter.http.jwt_authn.v2alpha.JwtProvider";
Expand Down Expand Up @@ -190,6 +190,15 @@ message JwtProvider {
string forward_payload_header = 8
[(validate.rules).string = {well_known_regex: HTTP_HEADER_NAME strict: false}];

// When :ref:`forward_payload_header <envoy_v3_api_field_extensions.filters.http.jwt_authn.v3.JwtProvider.forward_payload_header>`
// is specified, the base64 encoded payload will be added to the headers.
// Normally JWT based64 encode doesn't add padding. If this field is true,
// the header will be padded.
//
// This field is only relevant if :ref:`forward_payload_header <envoy_v3_api_field_extensions.filters.http.jwt_authn.v3.JwtProvider.forward_payload_header>`
// is specified.
bool pad_forward_payload_header = 11;

// If non empty, successfully verified JWT payloads will be written to StreamInfo DynamicMetadata
// in the format as: *namespace* is the jwt_authn filter name as **envoy.filters.http.jwt_authn**
// The value is the *protobuf::Struct*. The value of this field will be the key for its *fields*
Expand Down
11 changes: 10 additions & 1 deletion api/envoy/extensions/filters/http/jwt_authn/v4alpha/config.proto

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions docs/root/version_history/current.rst
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ New Features
* http: added upstream and downstream alpha HTTP/3 support! See :ref:`quic_options <envoy_v3_api_field_config.listener.v3.UdpListenerConfig.quic_options>` for downstream and the new http3_protocol_options in :ref:`http_protocol_options <envoy_v3_api_msg_extensions.upstreams.http.v3.HttpProtocolOptions>` for upstream HTTP/3.
* input matcher: a new input matcher that :ref:`matches an IP address against a list of CIDR ranges <envoy_v3_api_file_envoy/extensions/matching/input_matchers/ip/v3/ip.proto>`.
* jwt_authn: added support to fetch remote jwks asynchronously specified by :ref:`async_fetch <envoy_v3_api_field_extensions.filters.http.jwt_authn.v3.RemoteJwks.async_fetch>`.
* jwt_authn: added support to add padding in the forwarded JWT payload specified by :ref:`pad_forward_payload_header <envoy_v3_api_field_extensions.filters.http.jwt_authn.v3.JwtProvider.pad_forward_payload_header>`.
* listener: added ability to change an existing listener's address.
* listener: added filter chain match support for :ref:`direct source address <envoy_v3_api_field_config.listener.v3.FilterChainMatch.direct_source_prefix_ranges>`.
* local_rate_limit_filter: added suppoort for locally rate limiting http requests on a per connection basis. This can be enabled by setting the :ref:`local_rate_limit_per_downstream_connection <envoy_v3_api_field_extensions.filters.http.local_ratelimit.v3.LocalRateLimit.local_rate_limit_per_downstream_connection>` field to true.
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions source/common/common/base64.cc
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
#include "source/common/common/empty_string.h"

#include "absl/container/fixed_array.h"
#include "absl/strings/str_cat.h"

namespace Envoy {
namespace {
Expand Down Expand Up @@ -234,6 +235,13 @@ std::string Base64::encode(const char* input, uint64_t length, bool add_padding)
return ret;
}

void Base64::completePadding(std::string& encoded) {
if (encoded.length() % 4 != 0) {
std::string trailing_padding(4 - encoded.length() % 4, '=');
absl::StrAppend(&encoded, trailing_padding);
}
}

std::string Base64Url::decode(const std::string& input) {
if (input.empty()) {
return EMPTY_STRING;
Expand Down
6 changes: 6 additions & 0 deletions source/common/common/base64.h
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,12 @@ class Base64 {
* bytes.
*/
static std::string decodeWithoutPadding(absl::string_view input);

/**
* Add the padding in the base64 encoded binary if the padding is missing.
* @param encoded is the target to complete the padding.
*/
static void completePadding(std::string& encoded);
};

/**
Expand Down
13 changes: 11 additions & 2 deletions source/extensions/filters/http/jwt_authn/authenticator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
#include "envoy/http/async_client.h"

#include "source/common/common/assert.h"
#include "source/common/common/base64.h"
#include "source/common/common/enum_to_int.h"
#include "source/common/common/logger.h"
#include "source/common/http/message_impl.h"
Expand Down Expand Up @@ -252,9 +253,17 @@ void AuthenticatorImpl::verifyKey() {

// Forward the payload
const auto& provider = jwks_data_->getJwtProvider();

if (!provider.forward_payload_header().empty()) {
headers_->addCopy(Http::LowerCaseString(provider.forward_payload_header()),
jwt_->payload_str_base64url_);
if (provider.pad_forward_payload_header()) {
std::string payload_with_padding = jwt_->payload_str_base64url_;
Base64::completePadding(payload_with_padding);
headers_->addCopy(Http::LowerCaseString(provider.forward_payload_header()),
payload_with_padding);
} else {
headers_->addCopy(Http::LowerCaseString(provider.forward_payload_header()),
jwt_->payload_str_base64url_);
}
}

if (!provider.forward()) {
Expand Down
41 changes: 41 additions & 0 deletions test/common/common/base64_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,47 @@ TEST(Base64Test, BinaryBufferEncode) {
EXPECT_EQ("AAECAwgKCQCqvN4=", Base64::encode(buffer, 30));
}

TEST(Base64Test, CompletePadding) {
struct CompletePaddingBase64UrlTestCases {
std::string base64, base64_with_padding;
};

// For base64 encoding, there are only three length needed to test
// - 3n bytes => 4n bytes, no padding needed
// - 3n + 1 bytes => 4n + 2 bytes, 2 padding needed
// - 3n + 2 bytes => 4n + 3 bytes, 1 padding needed
CompletePaddingBase64UrlTestCases testCases[3] = {
// Payload text(3n bytes):
{"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG8iLCJpYXQiOjE1MTYyMzkwMjJ"
"9",
// No padding added.
"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG8iLCJpYXQiOjE1MTYyMzkwMjJ"
"9"},
// Payload text(3n + 1 bytes):
{"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2"
"MjM5MDIyfQ",
// 2 padding added.
"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2"
"MjM5MDIyfQ=="},
// Payload text(3n + 2 bytes):
{"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lZSIsImlhdCI6MTUx"
"NjIzOTAyMn0",
// 1 padding added.
"eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lZSIsImlhdCI6MTUx"
"NjIzOTAyMn0="}};
for (auto& tc : testCases) {
// Ensure these two base64 binaries are equivalent after decoding.
EXPECT_EQ(Base64::decodeWithoutPadding(tc.base64),
Base64::decodeWithoutPadding(tc.base64_with_padding));
// Ensure the `base64_with_padding` is correctly padded.
EXPECT_NE(Base64::decode(tc.base64_with_padding), "");

std::string base64_padded = tc.base64;
Base64::completePadding(base64_padded);
EXPECT_EQ(base64_padded, tc.base64_with_padding);
}
}

TEST(Base64UrlTest, EncodeString) {
EXPECT_EQ("", Base64Url::encode("", 0));
EXPECT_EQ("AAA", Base64Url::encode("\0\0", 2));
Expand Down
1 change: 1 addition & 0 deletions test/extensions/filters/http/jwt_authn/BUILD
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ envoy_extension_cc_test(
extension_name = "envoy.filters.http.jwt_authn",
deps = [
":mock_lib",
"//source/common/common:base64_lib",
"//source/extensions/filters/http/common:jwks_fetcher_lib",
"//source/extensions/filters/http/jwt_authn:authenticator_lib",
"//source/extensions/filters/http/jwt_authn:filter_config_lib",
Expand Down
17 changes: 17 additions & 0 deletions test/extensions/filters/http/jwt_authn/authenticator_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,23 @@ TEST_F(AuthenticatorTest, TestOkJWTandCache) {
EXPECT_EQ(0U, filter_config_->stats().jwks_fetch_failed_.value());
}

TEST_F(AuthenticatorTest, TestCompletePaddingInJwtPayload) {
(*proto_config_.mutable_providers())[std::string(ProviderName)].set_pad_forward_payload_header(
true);
createAuthenticator();
EXPECT_CALL(*raw_fetcher_, fetch(_, _, _))
.WillOnce(Invoke([this](const envoy::config::core::v3::HttpUri&, Tracing::Span&,
JwksFetcher::JwksReceiver& receiver) {
receiver.onJwksSuccess(std::move(jwks_));
}));

Http::TestRequestHeaderMapImpl headers{{"Authorization", "Bearer " + std::string(GoodToken)}};

expectVerifyStatus(Status::Ok, headers);

EXPECT_EQ(headers.get_("sec-istio-auth-userinfo"), ExpectedPayloadValueWithPadding);
}

// This test verifies the Jwt is forwarded if "forward" flag is set.
TEST_F(AuthenticatorTest, TestForwardJwt) {
// Config forward_jwt flag
Expand Down
5 changes: 5 additions & 0 deletions test/extensions/filters/http/jwt_authn/test_common.h
Original file line number Diff line number Diff line change
Expand Up @@ -178,6 +178,11 @@ const char ExpectedPayloadValue[] = "eyJpc3MiOiJodHRwczovL2V4YW1wbGUuY29tIiwic3V
"xlLmNvbSIsImV4cCI6MjAwMTAwMTAwMSwiYXVkIjoiZXhhbXBsZV9zZXJ2"
"aWNlIn0";

const char ExpectedPayloadValueWithPadding[] =
"eyJpc3MiOiJodHRwczovL2V4YW1wbGUuY29tIiwic3ViIjoidGVzdEBleGFtcG"
"xlLmNvbSIsImV4cCI6MjAwMTAwMTAwMSwiYXVkIjoiZXhhbXBsZV9zZXJ2"
"aWNlIn0=";

// Base64 decoded Payload JSON
const char ExpectedPayloadJSON[] = R"(
{
Expand Down

0 comments on commit 7ebd4b8

Please sign in to comment.