Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 28 additions & 14 deletions src/envoy/http/jwt_auth/jwt_authenticator.cc
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,12 @@ namespace {
// The HTTP header to pass verified token payload.
const LowerCaseString kJwtPayloadKey("sec-istio-auth-userinfo");

// The CORS OPTIONS HTTP method
const LowerCaseString kOptionsHttpMethod("options");

// Extract host and path from a URI
void ExtractUriHostPath(const std::string& uri, std::string* host,
std::string* path) {
void ExtractUriHostPath(const std::string &uri, std::string *host,
std::string *path) {
// Example:
// uri = "https://example.com/certs"
// pos : ^
Expand All @@ -49,16 +52,27 @@ void ExtractUriHostPath(const std::string& uri, std::string* host,

} // namespace

JwtAuthenticator::JwtAuthenticator(Upstream::ClusterManager& cm,
JwtAuthStore& store)
JwtAuthenticator::JwtAuthenticator(Upstream::ClusterManager &cm,
JwtAuthStore &store)
: cm_(cm), store_(store) {}

// Verify a JWT token.
void JwtAuthenticator::Verify(HeaderMap& headers,
JwtAuthenticator::Callbacks* callback) {
void JwtAuthenticator::Verify(HeaderMap &headers,
JwtAuthenticator::Callbacks *callback) {
headers_ = &headers;
callback_ = callback;

// Per the spec
// http://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0, CORS
// pre-flight requests shouldn't include user credentials.
if (headers_->Method() &&
LowerCaseString(kOptionsHttpMethod) ==

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I prefer to do this check in Fitler.cc right inside the decodeHeaders().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

decodeHeaders() does not have tests. Placing the check in Verify() will enable tests. Plus, placing the check in Verify() is equivalent to placing the check in decodeHeaders().

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done: changed to use the OPTIONS fixed string from Envoy.

LowerCaseString(headers_->Method()->value().c_str())) {
ENVOY_LOG(debug, "CORS preflight requests are passed through.");
DoneWithStatus(Status::OK);
return;
}

ENVOY_LOG(debug, "Jwt authentication starts");
std::vector<std::unique_ptr<JwtTokenExtractor::Token>> tokens;
store_.token_extractor().Extract(headers, &tokens);
Expand Down Expand Up @@ -119,7 +133,7 @@ void JwtAuthenticator::Verify(HeaderMap& headers,
FetchPubkey(issuer);
}

void JwtAuthenticator::FetchPubkey(PubkeyCacheItem* issuer) {
void JwtAuthenticator::FetchPubkey(PubkeyCacheItem *issuer) {
uri_ = issuer->jwt_config().remote_jwks().http_uri().uri();
std::string host, path;
ExtractUriHostPath(uri_, &host, &path);
Expand All @@ -130,7 +144,7 @@ void JwtAuthenticator::FetchPubkey(PubkeyCacheItem* issuer) {
message->headers().insertPath().value(path);
message->headers().insertHost().value(host);

const auto& cluster = issuer->jwt_config().remote_jwks().http_uri().cluster();
const auto &cluster = issuer->jwt_config().remote_jwks().http_uri().cluster();
if (cm_.get(cluster) == nullptr) {
DoneWithStatus(Status::FAILED_FETCH_PUBKEY);
return;
Expand All @@ -141,15 +155,15 @@ void JwtAuthenticator::FetchPubkey(PubkeyCacheItem* issuer) {
std::move(message), *this, Http::AsyncClient::RequestOptions());
}

void JwtAuthenticator::onSuccess(MessagePtr&& response) {
void JwtAuthenticator::onSuccess(MessagePtr &&response) {
request_ = nullptr;
uint64_t status_code = Http::Utility::getResponseStatus(response->headers());
if (status_code == 200) {
ENVOY_LOG(debug, "fetch pubkey [uri = {}]: success", uri_);
std::string body;
if (response->body()) {
auto len = response->body()->length();
body = std::string(static_cast<char*>(response->body()->linearize(len)),
body = std::string(static_cast<char *>(response->body()->linearize(len)),
len);
} else {
ENVOY_LOG(debug, "fetch pubkey [uri = {}]: body is empty", uri_);
Expand Down Expand Up @@ -177,7 +191,7 @@ void JwtAuthenticator::onDestroy() {
}

// Handle the public key fetch done event.
void JwtAuthenticator::OnFetchPubkeyDone(const std::string& pubkey) {
void JwtAuthenticator::OnFetchPubkeyDone(const std::string &pubkey) {
auto issuer = store_.pubkey_cache().LookupByIssuer(jwt_->Iss());
Status status = issuer->SetRemoteJwks(pubkey);
if (status != Status::OK) {
Expand All @@ -188,7 +202,7 @@ void JwtAuthenticator::OnFetchPubkeyDone(const std::string& pubkey) {
}

// Verify with a specific public key.
void JwtAuthenticator::VerifyKey(const PubkeyCacheItem& issuer_item) {
void JwtAuthenticator::VerifyKey(const PubkeyCacheItem &issuer_item) {
JwtAuth::Verifier v;
if (!v.Verify(*jwt_, *issuer_item.pubkey())) {
DoneWithStatus(v.GetStatus());
Expand Down Expand Up @@ -218,7 +232,7 @@ bool JwtAuthenticator::OkToBypass() {
return false;
}

void JwtAuthenticator::DoneWithStatus(const Status& status) {
void JwtAuthenticator::DoneWithStatus(const Status &status) {
ENVOY_LOG(debug, "Jwt authentication completed with: {}",
JwtAuth::StatusToString(status));
ENVOY_LOG(debug,
Expand All @@ -232,7 +246,7 @@ void JwtAuthenticator::DoneWithStatus(const Status& status) {
callback_ = nullptr;
}

const LowerCaseString& JwtAuthenticator::JwtPayloadKey() {
const LowerCaseString &JwtAuthenticator::JwtPayloadKey() {
return kJwtPayloadKey;
}

Expand Down
28 changes: 28 additions & 0 deletions src/envoy/http/jwt_auth/jwt_authenticator_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,34 @@ TEST_F(JwtAuthenticatorTest, TestMissingJwtWhenAllowMissingOrFailedIsTrue) {
auth_->Verify(headers, &mock_cb_);
}

TEST_F(JwtAuthenticatorTest, TestMissingJwtWhenHttpMethodIsCORS) {
// In this test, when JWT is missing, the status should still be OK
// because CORS preflight requests shouldn't include user credentials.
EXPECT_CALL(mock_cm_, httpAsyncClientForCluster(_)).Times(0);
EXPECT_CALL(mock_cb_, onDone(_)).WillOnce(Invoke([](const Status &status) {
ASSERT_EQ(status, Status::OK);
}));

auto cors_headers =
TestHeaderMapImpl{{":method", "OPTIONS"}, {":path", "/any/cors-path"}};
auth_->Verify(cors_headers, &mock_cb_);
}

TEST_F(JwtAuthenticatorTest, TestInvalidJWTWhenHttpMethodIsCORS) {
// In this test, when JWT is invalid, the status should still be OK
// because CORS preflight requests are passed through.
EXPECT_CALL(mock_cm_, httpAsyncClientForCluster(_)).Times(0);
EXPECT_CALL(mock_cb_, onDone(_)).WillOnce(Invoke([](const Status &status) {
ASSERT_EQ(status, Status::OK);
}));

std::string token = "invalidToken";
auto cors_headers = TestHeaderMapImpl{{":method", "OPTIONS"},
{":path", "/any/cors-path"},
{"Authorization", "Bearer " + token}};
auth_->Verify(cors_headers, &mock_cb_);
}

TEST_F(JwtAuthenticatorTest, TestInValidJwtWhenAllowMissingOrFailedIsTrue) {
// In this test, when JWT is invalid, the status should still be OK
// because allow_missing_or_failed is true.
Expand Down