diff --git a/CODEOWNERS b/CODEOWNERS index 257c2577dbdd..9ca4bae5c252 100644 --- a/CODEOWNERS +++ b/CODEOWNERS @@ -192,6 +192,8 @@ extensions/filters/http/oauth2 @derekargueta @mattklein123 /*/extensions/filters/http/rate_limit_quota @tyxia @yanavlasov # HTTP Bandwidth Limit /*/extensions/filters/http/bandwidth_limit @nitgoy @mattklein123 @yanavlasov @tonya11en +# HTTP Basic Auth +/*/extensions/filters/http/basic_auth @zhaohuabing @wbpcode # Original IP detection /*/extensions/http/original_ip_detection/custom_header @alyssawilk @mattklein123 /*/extensions/http/original_ip_detection/xff @alyssawilk @mattklein123 diff --git a/api/BUILD b/api/BUILD index d40a6c4d7470..04b9837a5134 100644 --- a/api/BUILD +++ b/api/BUILD @@ -163,6 +163,7 @@ proto_library( "//envoy/extensions/filters/http/aws_lambda/v3:pkg", "//envoy/extensions/filters/http/aws_request_signing/v3:pkg", "//envoy/extensions/filters/http/bandwidth_limit/v3:pkg", + "//envoy/extensions/filters/http/basic_auth/v3:pkg", "//envoy/extensions/filters/http/buffer/v3:pkg", "//envoy/extensions/filters/http/cache/v3:pkg", "//envoy/extensions/filters/http/cdn_loop/v3:pkg", diff --git a/api/envoy/extensions/filters/http/basic_auth/v3/BUILD b/api/envoy/extensions/filters/http/basic_auth/v3/BUILD new file mode 100644 index 000000000000..1c1a6f6b4423 --- /dev/null +++ b/api/envoy/extensions/filters/http/basic_auth/v3/BUILD @@ -0,0 +1,12 @@ +# DO NOT EDIT. This file is generated by tools/proto_format/proto_sync.py. + +load("@envoy_api//bazel:api_build_system.bzl", "api_proto_package") + +licenses(["notice"]) # Apache 2 + +api_proto_package( + deps = [ + "//envoy/config/core/v3:pkg", + "@com_github_cncf_udpa//udpa/annotations:pkg", + ], +) diff --git a/api/envoy/extensions/filters/http/basic_auth/v3/basic_auth.proto b/api/envoy/extensions/filters/http/basic_auth/v3/basic_auth.proto new file mode 100644 index 000000000000..df23868a4260 --- /dev/null +++ b/api/envoy/extensions/filters/http/basic_auth/v3/basic_auth.proto @@ -0,0 +1,36 @@ +syntax = "proto3"; + +package envoy.extensions.filters.http.basic_auth.v3; + +import "envoy/config/core/v3/base.proto"; + +import "udpa/annotations/sensitive.proto"; +import "udpa/annotations/status.proto"; + +option java_package = "io.envoyproxy.envoy.extensions.filters.http.basic_auth.v3"; +option java_outer_classname = "BasicAuthProto"; +option java_multiple_files = true; +option go_package = "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/basic_auth/v3;basic_authv3"; +option (udpa.annotations.file_status).package_version_status = ACTIVE; + +// [#protodoc-title: Basic Auth] +// Basic Auth :ref:`configuration overview `. +// [#extension: envoy.filters.http.basic_auth] + +// Basic HTTP authentication. +// +// Example: +// +// .. code-block:: yaml +// +// users: +// inline_string: |- +// user1:{SHA}hashed_user1_password +// user2:{SHA}hashed_user2_password +// +message BasicAuth { + // Username-password pairs used to verify user credentials in the "Authorization" header. + // The value needs to be the htpasswd format. + // Reference to https://httpd.apache.org/docs/2.4/programs/htpasswd.html + config.core.v3.DataSource users = 1 [(udpa.annotations.sensitive) = true]; +} diff --git a/api/versioning/BUILD b/api/versioning/BUILD index 9ad67e06e99c..5f050eedfb59 100644 --- a/api/versioning/BUILD +++ b/api/versioning/BUILD @@ -101,6 +101,7 @@ proto_library( "//envoy/extensions/filters/http/aws_lambda/v3:pkg", "//envoy/extensions/filters/http/aws_request_signing/v3:pkg", "//envoy/extensions/filters/http/bandwidth_limit/v3:pkg", + "//envoy/extensions/filters/http/basic_auth/v3:pkg", "//envoy/extensions/filters/http/buffer/v3:pkg", "//envoy/extensions/filters/http/cache/v3:pkg", "//envoy/extensions/filters/http/cdn_loop/v3:pkg", diff --git a/changelogs/current.yaml b/changelogs/current.yaml index cff26a84b048..5f3ca45398ff 100644 --- a/changelogs/current.yaml +++ b/changelogs/current.yaml @@ -62,6 +62,10 @@ removed_config_or_runtime: runtime flag and legacy code path. new_features: +- area: filters + change: | + Added :ref:`the Basic Auth filter `, which can be used to + authenticate user credentials in the HTTP Authentication heaer defined in `RFC7617 `_. - area: upstream change: | Added :ref:`enable_full_scan ` diff --git a/docs/root/configuration/http/http_filters/basic_auth_filter.rst b/docs/root/configuration/http/http_filters/basic_auth_filter.rst new file mode 100644 index 000000000000..da8b160fd054 --- /dev/null +++ b/docs/root/configuration/http/http_filters/basic_auth_filter.rst @@ -0,0 +1,46 @@ +.. _config_http_filters_basic_auth: + +Basic Auth +========== + +This HTTP filter can be used to authenticate user credentials in the HTTP Authentication header defined +in `RFC7617 `. + +The filter will extract the username and password from the HTTP Authentication header and verify them +against the configured username and password list. + +If the username and password are valid, the request will be forwared to the next filter in the filter chains. +If they're invalid or not provided in the HTTP request, the request will be denied with a 401 Unauthorized response. + +Configuration +------------- + +* This filter should be configured with the type URL ``type.googleapis.com/envoy.extensions.filters.http.basic_auth.v3.BasicAuth``. +* :ref:`v3 API reference ` + +``users`` is a list of username-password pairs used to verify user credentials in the "Authorization" header. + The value needs to be the `htpasswd ` format. + + +An example configuration of the filter may look like the following: + +.. code-block:: yaml + + users: + inline_string: |- + user1:{SHA}hashed_user1_password + user2:{SHA}hashed_user2_password + +Note that only SHA format is currently supported. Other formats may be added in the future. + +Statistics +---------- + +The HTTP basic auth filter outputs statistics in the ``http..basic_auth.`` namespace. + +.. csv-table:: + :header: Name, Type, Description + :widths: 1, 1, 2 + + allowed, Counter, Total number of allowed requests + denied, Counter, Total number of denied requests diff --git a/docs/root/configuration/http/http_filters/http_filters.rst b/docs/root/configuration/http/http_filters/http_filters.rst index bbf38623d02f..eb1333ad0e03 100644 --- a/docs/root/configuration/http/http_filters/http_filters.rst +++ b/docs/root/configuration/http/http_filters/http_filters.rst @@ -11,6 +11,7 @@ HTTP filters aws_lambda_filter aws_request_signing_filter bandwidth_limit_filter + basic_auth_filter buffer_filter cache_filter cdn_loop_filter diff --git a/source/common/common/logger.h b/source/common/common/logger.h index f3ad2bc01bc7..a90e43628e1e 100644 --- a/source/common/common/logger.h +++ b/source/common/common/logger.h @@ -39,6 +39,7 @@ const static bool should_log = true; FUNCTION(aws) \ FUNCTION(assert) \ FUNCTION(backtrace) \ + FUNCTION(basic_auth) \ FUNCTION(cache_filter) \ FUNCTION(client) \ FUNCTION(config) \ diff --git a/source/extensions/extensions_build_config.bzl b/source/extensions/extensions_build_config.bzl index a75696fbf8c8..6efa0a95f852 100644 --- a/source/extensions/extensions_build_config.bzl +++ b/source/extensions/extensions_build_config.bzl @@ -124,6 +124,7 @@ EXTENSIONS = { "envoy.filters.http.aws_lambda": "//source/extensions/filters/http/aws_lambda:config", "envoy.filters.http.aws_request_signing": "//source/extensions/filters/http/aws_request_signing:config", "envoy.filters.http.bandwidth_limit": "//source/extensions/filters/http/bandwidth_limit:config", + "envoy.filters.http.basic_auth": "//source/extensions/filters/http/basic_auth:config", "envoy.filters.http.buffer": "//source/extensions/filters/http/buffer:config", "envoy.filters.http.cache": "//source/extensions/filters/http/cache:config", "envoy.filters.http.cdn_loop": "//source/extensions/filters/http/cdn_loop:config", diff --git a/source/extensions/extensions_metadata.yaml b/source/extensions/extensions_metadata.yaml index 2471dc695903..c8396f16f726 100644 --- a/source/extensions/extensions_metadata.yaml +++ b/source/extensions/extensions_metadata.yaml @@ -217,6 +217,13 @@ envoy.filters.http.bandwidth_limit: status: stable type_urls: - envoy.extensions.filters.http.bandwidth_limit.v3.BandwidthLimit +envoy.filters.http.basic_auth: + categories: + - envoy.filters.http + security_posture: robust_to_untrusted_downstream + status: alpha + type_urls: + - envoy.extensions.filters.http.basic_auth.v3.BasicAuth envoy.filters.http.buffer: categories: - envoy.filters.http diff --git a/source/extensions/filters/http/basic_auth/BUILD b/source/extensions/filters/http/basic_auth/BUILD new file mode 100644 index 000000000000..f610d4fee905 --- /dev/null +++ b/source/extensions/filters/http/basic_auth/BUILD @@ -0,0 +1,39 @@ +load( + "//bazel:envoy_build_system.bzl", + "envoy_cc_extension", + "envoy_cc_library", + "envoy_extension_package", +) + +licenses(["notice"]) # Apache 2 + +envoy_extension_package() + +envoy_cc_library( + name = "basic_auth_lib", + srcs = ["basic_auth_filter.cc"], + hdrs = ["basic_auth_filter.h"], + external_deps = ["ssl"], + deps = [ + "//envoy/server:filter_config_interface", + "//source/common/common:base64_lib", + "//source/common/config:utility_lib", + "//source/common/http:header_map_lib", + "//source/common/protobuf:utility_lib", + "//source/extensions/filters/http/common:pass_through_filter_lib", + ], +) + +envoy_cc_extension( + name = "config", + srcs = ["config.cc"], + hdrs = ["config.h"], + deps = [ + ":basic_auth_lib", + "//envoy/registry", + "//source/common/config:datasource_lib", + "//source/common/protobuf:utility_lib", + "//source/extensions/filters/http/common:factory_base_lib", + "@envoy_api//envoy/extensions/filters/http/basic_auth/v3:pkg_cc_proto", + ], +) diff --git a/source/extensions/filters/http/basic_auth/basic_auth_filter.cc b/source/extensions/filters/http/basic_auth/basic_auth_filter.cc new file mode 100644 index 000000000000..ae7b10e6c573 --- /dev/null +++ b/source/extensions/filters/http/basic_auth/basic_auth_filter.cc @@ -0,0 +1,91 @@ +#include "source/extensions/filters/http/basic_auth/basic_auth_filter.h" + +#include + +#include "source/common/common/base64.h" +#include "source/common/http/header_utility.h" +#include "source/common/http/headers.h" + +namespace Envoy { +namespace Extensions { +namespace HttpFilters { +namespace BasicAuth { + +namespace { + +// Function to compute SHA1 hash +std::string computeSHA1(absl::string_view password) { + unsigned char hash[SHA_DIGEST_LENGTH]; + + // Calculate the SHA-1 hash + SHA1(reinterpret_cast(password.data()), password.length(), hash); + + // Encode the binary hash in Base64 + return Base64::encode(reinterpret_cast(hash), SHA_DIGEST_LENGTH); +} + +} // namespace + +FilterConfig::FilterConfig(UserMapConstPtr users, const std::string& stats_prefix, + Stats::Scope& scope) + : users_(std::move(users)), stats_(generateStats(stats_prefix + "basic_auth.", scope)) {} + +bool FilterConfig::validateUser(absl::string_view username, absl::string_view password) const { + auto user = users_->find(username); + if (user == users_->end()) { + return false; + } + + return computeSHA1(password) == user->second.hash; +} + +BasicAuthFilter::BasicAuthFilter(FilterConfigConstSharedPtr config) : config_(std::move(config)) {} + +Http::FilterHeadersStatus BasicAuthFilter::decodeHeaders(Http::RequestHeaderMap& headers, bool) { + auto auth_header = headers.get(Http::CustomHeaders::get().Authorization); + if (!auth_header.empty()) { + absl::string_view auth_value = auth_header[0]->value().getStringView(); + + if (absl::StartsWith(auth_value, "Basic ")) { + // Extract and decode the Base64 part of the header. + absl::string_view base64Token = auth_value.substr(6); + const std::string decoded = Base64::decodeWithoutPadding(base64Token); + + // The decoded string is in the format "username:password". + const size_t colon_pos = decoded.find(':'); + + if (colon_pos != std::string::npos) { + absl::string_view decoded_view = decoded; + absl::string_view username = decoded_view.substr(0, colon_pos); + absl::string_view password = decoded_view.substr(colon_pos + 1); + + if (config_->validateUser(username, password)) { + config_->stats().allowed_.inc(); + return Http::FilterHeadersStatus::Continue; + } else { + config_->stats().denied_.inc(); + decoder_callbacks_->sendLocalReply( + Http::Code::Unauthorized, + "User authentication failed. Invalid username/password combination", nullptr, + absl::nullopt, "invalid_credential_for_basic_auth"); + return Http::FilterHeadersStatus::StopIteration; + } + } + } + } + + config_->stats().denied_.inc(); + decoder_callbacks_->sendLocalReply(Http::Code::Unauthorized, + "User authentication failed. Missing username and password", + nullptr, absl::nullopt, "no_credential_for_basic_auth"); + return Http::FilterHeadersStatus::StopIteration; +} + +void BasicAuthFilter::setDecoderFilterCallbacks(Http::StreamDecoderFilterCallbacks& callbacks) { + decoder_callbacks_ = &callbacks; +} + +} // namespace BasicAuth +} // namespace HttpFilters +} // namespace Extensions +} // namespace Envoy diff --git a/source/extensions/filters/http/basic_auth/basic_auth_filter.h b/source/extensions/filters/http/basic_auth/basic_auth_filter.h new file mode 100644 index 000000000000..d900b304eb67 --- /dev/null +++ b/source/extensions/filters/http/basic_auth/basic_auth_filter.h @@ -0,0 +1,80 @@ +#pragma once + +#include "envoy/stats/stats_macros.h" + +#include "source/common/common/logger.h" +#include "source/extensions/filters/http/common/pass_through_filter.h" + +#include "absl/container/flat_hash_map.h" + +namespace Envoy { +namespace Extensions { +namespace HttpFilters { +namespace BasicAuth { + +/** + * All Basic Auth filter stats. @see stats_macros.h + */ +#define ALL_BASIC_AUTH_STATS(COUNTER) \ + COUNTER(allowed) \ + COUNTER(denied) + +/** + * Struct definition for Basic Auth stats. @see stats_macros.h + */ +struct BasicAuthStats { + ALL_BASIC_AUTH_STATS(GENERATE_COUNTER_STRUCT) +}; + +/** + * Struct definition for username password pairs. + */ +struct User { + // the user name + std::string name; + // the hashed password, see https://httpd.apache.org/docs/2.4/misc/password_encryptions.html + std::string hash; +}; + +using UserMapConstPtr = + std::unique_ptr>; // username, User + +/** + * Configuration for the Basic Auth filter. + */ +class FilterConfig { +public: + FilterConfig(UserMapConstPtr users, const std::string& stats_prefix, Stats::Scope& scope); + const BasicAuthStats& stats() const { return stats_; } + bool validateUser(absl::string_view username, absl::string_view password) const; + +private: + static BasicAuthStats generateStats(const std::string& prefix, Stats::Scope& scope) { + return BasicAuthStats{ALL_BASIC_AUTH_STATS(POOL_COUNTER_PREFIX(scope, prefix))}; + } + + UserMapConstPtr users_; + BasicAuthStats stats_; +}; +using FilterConfigConstSharedPtr = std::shared_ptr; + +// The Envoy filter to process HTTP basic auth. +class BasicAuthFilter : public Http::PassThroughDecoderFilter, + public Logger::Loggable { +public: + BasicAuthFilter(FilterConfigConstSharedPtr config); + + // Http::StreamDecoderFilter + Http::FilterHeadersStatus decodeHeaders(Http::RequestHeaderMap& headers, bool) override; + void setDecoderFilterCallbacks(Http::StreamDecoderFilterCallbacks& callbacks) override; + +private: + // The callback function. + Http::StreamDecoderFilterCallbacks* decoder_callbacks_; + FilterConfigConstSharedPtr config_; +}; + +} // namespace BasicAuth +} // namespace HttpFilters +} // namespace Extensions +} // namespace Envoy diff --git a/source/extensions/filters/http/basic_auth/config.cc b/source/extensions/filters/http/basic_auth/config.cc new file mode 100644 index 000000000000..02a3582cad69 --- /dev/null +++ b/source/extensions/filters/http/basic_auth/config.cc @@ -0,0 +1,69 @@ +#include "source/extensions/filters/http/basic_auth/config.h" + +#include "source/common/config/datasource.h" +#include "source/extensions/filters/http/basic_auth/basic_auth_filter.h" + +namespace Envoy { +namespace Extensions { +namespace HttpFilters { +namespace BasicAuth { + +using envoy::extensions::filters::http::basic_auth::v3::BasicAuth; + +namespace { + +UserMapConstPtr readHtpasswd(const std::string& htpasswd) { + std::unique_ptr> users = + std::make_unique>(); + std::istringstream htpsswd_ss(htpasswd); + std::string line; + + while (std::getline(htpsswd_ss, line)) { + const size_t colon_pos = line.find(':'); + + if (colon_pos != std::string::npos) { + std::string name = line.substr(0, colon_pos); + std::string hash = line.substr(colon_pos + 1); + + if (name.empty()) { + throw EnvoyException("basic auth: invalid user name"); + } + + if (absl::StartsWith(hash, "{SHA}")) { + hash = hash.substr(5); + // The base64 encoded SHA1 hash is 28 bytes long + if (hash.length() != 28) { + throw EnvoyException("basic auth: invalid SHA hash length"); + } + + users->insert({name, {name, hash}}); + continue; + } + } + + throw EnvoyException("basic auth: unsupported htpasswd format: please use {SHA}"); + } + + return users; +} + +} // namespace + +Http::FilterFactoryCb BasicAuthFilterFactory::createFilterFactoryFromProtoTyped( + const BasicAuth& proto_config, const std::string& stats_prefix, + Server::Configuration::FactoryContext& context) { + const std::string htpasswd = Config::DataSource::read(proto_config.users(), false, context.api()); + UserMapConstPtr users = readHtpasswd(htpasswd); + FilterConfigConstSharedPtr config = + std::make_unique(std::move(users), stats_prefix, context.scope()); + return [config](Http::FilterChainFactoryCallbacks& callbacks) -> void { + callbacks.addStreamDecoderFilter(std::make_shared(config)); + }; +} + +REGISTER_FACTORY(BasicAuthFilterFactory, Server::Configuration::NamedHttpFilterConfigFactory); + +} // namespace BasicAuth +} // namespace HttpFilters +} // namespace Extensions +} // namespace Envoy diff --git a/source/extensions/filters/http/basic_auth/config.h b/source/extensions/filters/http/basic_auth/config.h new file mode 100644 index 000000000000..7abebaaa789c --- /dev/null +++ b/source/extensions/filters/http/basic_auth/config.h @@ -0,0 +1,27 @@ +#pragma once + +#include "envoy/extensions/filters/http/basic_auth/v3/basic_auth.pb.h" +#include "envoy/extensions/filters/http/basic_auth/v3/basic_auth.pb.validate.h" + +#include "source/extensions/filters/http/common/factory_base.h" + +namespace Envoy { +namespace Extensions { +namespace HttpFilters { +namespace BasicAuth { + +class BasicAuthFilterFactory + : public Common::FactoryBase { +public: + BasicAuthFilterFactory() : FactoryBase("envoy.filters.http.basic_auth") {} + +private: + Http::FilterFactoryCb createFilterFactoryFromProtoTyped( + const envoy::extensions::filters::http::basic_auth::v3::BasicAuth& config, + const std::string& stats_prefix, Server::Configuration::FactoryContext& context) override; +}; + +} // namespace BasicAuth +} // namespace HttpFilters +} // namespace Extensions +} // namespace Envoy diff --git a/source/extensions/filters/http/well_known_names.h b/source/extensions/filters/http/well_known_names.h index cfd1783b55b4..8e33a0699c0a 100644 --- a/source/extensions/filters/http/well_known_names.h +++ b/source/extensions/filters/http/well_known_names.h @@ -16,6 +16,8 @@ class HttpFilterNameValues { const std::string Buffer = "envoy.filters.http.buffer"; // Bandwidth limit filter const std::string BandwidthLimit = "envoy.filters.http.bandwidth_limit"; + // Basic Auth filter + const std::string BasicAuth = "envoy.filters.http.basic_auth"; // Cache filter const std::string Cache = "envoy.filters.http.cache"; // CDN Loop filter diff --git a/test/extensions/filters/http/basic_auth/BUILD b/test/extensions/filters/http/basic_auth/BUILD new file mode 100644 index 000000000000..39e573d580cd --- /dev/null +++ b/test/extensions/filters/http/basic_auth/BUILD @@ -0,0 +1,45 @@ +load( + "//bazel:envoy_build_system.bzl", + "envoy_package", +) +load( + "//test/extensions:extensions_build_system.bzl", + "envoy_extension_cc_test", +) + +licenses(["notice"]) # Apache 2 + +envoy_package() + +envoy_extension_cc_test( + name = "filter_test", + srcs = ["filter_test.cc"], + extension_names = ["envoy.filters.http.basic_auth"], + deps = [ + "//source/extensions/filters/http/basic_auth:basic_auth_lib", + "//test/mocks/server:server_mocks", + "@envoy_api//envoy/extensions/filters/http/basic_auth/v3:pkg_cc_proto", + ], +) + +envoy_extension_cc_test( + name = "config_test", + srcs = ["config_test.cc"], + extension_names = ["envoy.filters.http.basic_auth"], + deps = [ + "//source/extensions/filters/http/basic_auth:config", + "//test/mocks/server:server_mocks", + ], +) + +envoy_extension_cc_test( + name = "basic_auth_integration_test", + size = "large", + srcs = ["basic_auth_integration_test.cc"], + extension_names = ["envoy.filters.http.basic_auth"], + deps = [ + "//source/extensions/filters/http/basic_auth:config", + "//test/integration:http_protocol_integration_lib", + "//test/test_common:utility_lib", + ], +) diff --git a/test/extensions/filters/http/basic_auth/basic_auth_integration_test.cc b/test/extensions/filters/http/basic_auth/basic_auth_integration_test.cc new file mode 100644 index 000000000000..2e70bf9efb5b --- /dev/null +++ b/test/extensions/filters/http/basic_auth/basic_auth_integration_test.cc @@ -0,0 +1,119 @@ +#include "test/integration/http_protocol_integration.h" +#include "test/test_common/utility.h" + +#include "gtest/gtest.h" + +namespace Envoy { +namespace Extensions { +namespace HttpFilters { +namespace BasicAuth { +namespace { + +class BasicAuthIntegrationTest : public HttpProtocolIntegrationTest { +public: + void initializeFilter() { + // user1, test1 + // user2, test2 + const std::string filter_config = + R"EOF( +name: envoy.filters.http.basic_auth +typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.basic_auth.v3.BasicAuth + users: + inline_string: |- + user1:{SHA}tESsBmE/yNY3lb6a0L6vVQEZNqw= + user2:{SHA}EJ9LPFDXsN9ynSmbxvjp75Bmlx8= +)EOF"; + config_helper_.prependFilter(filter_config); + initialize(); + } +}; + +// BasicAuth integration tests that should run with all protocols +class BasicAuthIntegrationTestAllProtocols : public BasicAuthIntegrationTest {}; + +INSTANTIATE_TEST_SUITE_P( + Protocols, BasicAuthIntegrationTestAllProtocols, + testing::ValuesIn(HttpProtocolIntegrationTest::getProtocolTestParamsWithoutHTTP3()), + HttpProtocolIntegrationTest::protocolTestParamsToString); + +// Request with valid credential +TEST_P(BasicAuthIntegrationTestAllProtocols, ValidCredential) { + initializeFilter(); + codec_client_ = makeHttpConnection(lookupPort("http")); + + auto response = codec_client_->makeHeaderOnlyRequest(Http::TestRequestHeaderMapImpl{ + {":method", "GET"}, + {":path", "/"}, + {":scheme", "http"}, + {":authority", "host"}, + {"Authorization", "Basic dXNlcjE6dGVzdDE="}, // user1, test1 + }); + + waitForNextUpstreamRequest(); + upstream_request_->encodeHeaders(Http::TestResponseHeaderMapImpl{{":status", "200"}}, true); + ASSERT_TRUE(response->waitForEndStream()); + ASSERT_TRUE(response->complete()); + EXPECT_EQ("200", response->headers().getStatusValue()); +} + +// Request without credential +TEST_P(BasicAuthIntegrationTestAllProtocols, NoCredential) { + initializeFilter(); + codec_client_ = makeHttpConnection(lookupPort("http")); + + auto response = codec_client_->makeHeaderOnlyRequest(Http::TestRequestHeaderMapImpl{ + {":method", "GET"}, + {":path", "/"}, + {":scheme", "http"}, + {":authority", "host"}, + }); + + ASSERT_TRUE(response->waitForEndStream()); + ASSERT_TRUE(response->complete()); + EXPECT_EQ("401", response->headers().getStatusValue()); + EXPECT_EQ("User authentication failed. Missing username and password", response->body()); +} + +// Request without wrong password +TEST_P(BasicAuthIntegrationTestAllProtocols, WrongPasswrod) { + initializeFilter(); + codec_client_ = makeHttpConnection(lookupPort("http")); + + auto response = codec_client_->makeHeaderOnlyRequest(Http::TestRequestHeaderMapImpl{ + {":method", "GET"}, + {":path", "/"}, + {":scheme", "http"}, + {":authority", "host"}, + {"Authorization", "Basic dXNlcjE6dGVzdDI="}, // user1, test2 + }); + + ASSERT_TRUE(response->waitForEndStream()); + ASSERT_TRUE(response->complete()); + EXPECT_EQ("401", response->headers().getStatusValue()); + EXPECT_EQ("User authentication failed. Invalid username/password combination", response->body()); +} + +// Request with none-existed user +TEST_P(BasicAuthIntegrationTestAllProtocols, NoneExistedUser) { + initializeFilter(); + codec_client_ = makeHttpConnection(lookupPort("http")); + + auto response = codec_client_->makeHeaderOnlyRequest(Http::TestRequestHeaderMapImpl{ + {":method", "GET"}, + {":path", "/"}, + {":scheme", "http"}, + {":authority", "host"}, + {"Authorization", "Basic dXNlcjM6dGVzdDI="}, // user3, test2 + }); + + ASSERT_TRUE(response->waitForEndStream()); + ASSERT_TRUE(response->complete()); + EXPECT_EQ("401", response->headers().getStatusValue()); + EXPECT_EQ("User authentication failed. Invalid username/password combination", response->body()); +} +} // namespace +} // namespace BasicAuth +} // namespace HttpFilters +} // namespace Extensions +} // namespace Envoy diff --git a/test/extensions/filters/http/basic_auth/config_test.cc b/test/extensions/filters/http/basic_auth/config_test.cc new file mode 100644 index 000000000000..2be2d5812596 --- /dev/null +++ b/test/extensions/filters/http/basic_auth/config_test.cc @@ -0,0 +1,127 @@ +#include "source/extensions/filters/http/basic_auth/basic_auth_filter.h" +#include "source/extensions/filters/http/basic_auth/config.h" + +#include "test/mocks/server/mocks.h" + +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +namespace Envoy { +namespace Extensions { +namespace HttpFilters { +namespace BasicAuth { + +TEST(Factory, ValidConfig) { + const std::string yaml = R"( + users: + inline_string: |- + user1:{SHA}tESsBmE/yNY3lb6a0L6vVQEZNqw= + user2:{SHA}EJ9LPFDXsN9ynSmbxvjp75Bmlx8= + )"; + + BasicAuthFilterFactory factory; + ProtobufTypes::MessagePtr proto_config = factory.createEmptyRouteConfigProto(); + TestUtility::loadFromYaml(yaml, *proto_config); + + NiceMock context; + + auto callback = factory.createFilterFactoryFromProto(*proto_config, "stats", context); + Http::MockFilterChainFactoryCallbacks filter_callback; + EXPECT_CALL(filter_callback, addStreamDecoderFilter(_)); + callback(filter_callback); +} + +TEST(Factory, InvalidConfigNoColon) { + const std::string yaml = R"( + users: + inline_string: |- + user1{SHA}tESsBmE/yNY3lb6a0L6vVQEZNqw= + user2:{SHA}EJ9LPFDXsN9ynSmbxvjp75Bmlx8= + )"; + + BasicAuthFilterFactory factory; + ProtobufTypes::MessagePtr proto_config = factory.createEmptyRouteConfigProto(); + TestUtility::loadFromYaml(yaml, *proto_config); + + NiceMock context; + + EXPECT_THROW(factory.createFilterFactoryFromProto(*proto_config, "stats", context), + EnvoyException); +} + +TEST(Factory, InvalidConfigNoUser) { + const std::string yaml = R"( + users: + inline_string: |- + :{SHA}tESsBmE/yNY3lb6a0L6vVQEZNqw= + user2:{SHA}EJ9LPFDXsN9ynSmbxvjp75Bmlx8= + )"; + + BasicAuthFilterFactory factory; + ProtobufTypes::MessagePtr proto_config = factory.createEmptyRouteConfigProto(); + TestUtility::loadFromYaml(yaml, *proto_config); + + NiceMock context; + + EXPECT_THROW(factory.createFilterFactoryFromProto(*proto_config, "stats", context), + EnvoyException); +} + +TEST(Factory, InvalidConfigNoPassword) { + const std::string yaml = R"( + users: + inline_string: |- + user1: + user2:{SHA}EJ9LPFDXsN9ynSmbxvjp75Bmlx8= + )"; + + BasicAuthFilterFactory factory; + ProtobufTypes::MessagePtr proto_config = factory.createEmptyRouteConfigProto(); + TestUtility::loadFromYaml(yaml, *proto_config); + + NiceMock context; + + EXPECT_THROW(factory.createFilterFactoryFromProto(*proto_config, "stats", context), + EnvoyException); +} + +TEST(Factory, InvalidConfigNoHash) { + const std::string yaml = R"( + users: + inline_string: |- + user1:{SHA} + user2:{SHA}EJ9LPFDXsN9ynSmbxvjp75Bmlx8= + )"; + + BasicAuthFilterFactory factory; + ProtobufTypes::MessagePtr proto_config = factory.createEmptyRouteConfigProto(); + TestUtility::loadFromYaml(yaml, *proto_config); + + NiceMock context; + + EXPECT_THROW(factory.createFilterFactoryFromProto(*proto_config, "stats", context), + EnvoyException); +} + +TEST(Factory, InvalidConfigNotSHA) { + const std::string yaml = R"( + users: + inline_string: |- + user1:{SHA}tESsBmE/yNY3lb6a0L6vVQEZNqw= + user2:$apr1$0vAnUTEB$4EJJr0GR3y48WF2AiieWs. + )"; + + BasicAuthFilterFactory factory; + ProtobufTypes::MessagePtr proto_config = factory.createEmptyRouteConfigProto(); + TestUtility::loadFromYaml(yaml, *proto_config); + + NiceMock context; + + EXPECT_THROW(factory.createFilterFactoryFromProto(*proto_config, "stats", context), + EnvoyException); +} + +} // namespace BasicAuth +} // namespace HttpFilters +} // namespace Extensions +} // namespace Envoy diff --git a/test/extensions/filters/http/basic_auth/filter_test.cc b/test/extensions/filters/http/basic_auth/filter_test.cc new file mode 100644 index 000000000000..d8d3f3000be4 --- /dev/null +++ b/test/extensions/filters/http/basic_auth/filter_test.cc @@ -0,0 +1,103 @@ +#include "envoy/extensions/filters/http/basic_auth/v3/basic_auth.pb.h" + +#include "source/extensions/filters/http/basic_auth/basic_auth_filter.h" + +#include "test/mocks/http/mocks.h" + +#include "gmock/gmock.h" +#include "gtest/gtest.h" + +namespace Envoy { +namespace Extensions { +namespace HttpFilters { +namespace BasicAuth { + +class FilterTest : public testing::Test { +public: + FilterTest() { + std::unique_ptr> users = + std::make_unique>(); + users->insert({"user1", {"user1", "tESsBmE/yNY3lb6a0L6vVQEZNqw="}}); // user1:test1 + users->insert({"user2", {"user2", "EJ9LPFDXsN9ynSmbxvjp75Bmlx8="}}); // user2:test2 + config_ = std::make_unique(std::move(users), "stats", *stats_.rootScope()); + filter_ = std::make_shared(config_); + filter_->setDecoderFilterCallbacks(decoder_filter_callbacks_); + } + + NiceMock stats_; + NiceMock decoder_filter_callbacks_; + FilterConfigConstSharedPtr config_; + std::shared_ptr filter_; +}; + +TEST_F(FilterTest, BasicAuth) { + // user1:test1 + Http::TestRequestHeaderMapImpl request_headers_user1{{"Authorization", "Basic dXNlcjE6dGVzdDE="}}; + + EXPECT_EQ(Http::FilterHeadersStatus::Continue, + filter_->decodeHeaders(request_headers_user1, true)); + + // user2:test2 + Http::TestRequestHeaderMapImpl request_headers_user2{{"Authorization", "Basic dXNlcjI6dGVzdDI="}}; + + EXPECT_EQ(Http::FilterHeadersStatus::Continue, + filter_->decodeHeaders(request_headers_user2, true)); +} + +TEST_F(FilterTest, UserNotExist) { + // user3:test2 + Http::TestRequestHeaderMapImpl request_headers_user1{{"Authorization", "Basic dXNlcjM6dGVzdDI="}}; + + EXPECT_CALL(decoder_filter_callbacks_, sendLocalReply(_, _, _, _, _)) + .WillOnce(Invoke([&](Http::Code code, absl::string_view body, + std::function, + const absl::optional grpc_status, + absl::string_view details) { + EXPECT_EQ(Http::Code::Unauthorized, code); + EXPECT_EQ("User authentication failed. Invalid username/password combination", body); + EXPECT_EQ(grpc_status, absl::nullopt); + EXPECT_EQ(details, "invalid_credential_for_basic_auth"); + })); + EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, + filter_->decodeHeaders(request_headers_user1, true)); +} + +TEST_F(FilterTest, InvalidPassword) { + // user1:test2 + Http::TestRequestHeaderMapImpl request_headers_user1{{"Authorization", "Basic dXNlcjE6dGVzdDI="}}; + + EXPECT_CALL(decoder_filter_callbacks_, sendLocalReply(_, _, _, _, _)) + .WillOnce(Invoke([&](Http::Code code, absl::string_view body, + std::function, + const absl::optional grpc_status, + absl::string_view details) { + EXPECT_EQ(Http::Code::Unauthorized, code); + EXPECT_EQ("User authentication failed. Invalid username/password combination", body); + EXPECT_EQ(grpc_status, absl::nullopt); + EXPECT_EQ(details, "invalid_credential_for_basic_auth"); + })); + EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, + filter_->decodeHeaders(request_headers_user1, true)); +} + +TEST_F(FilterTest, NoAuthHeader) { + Http::TestRequestHeaderMapImpl request_headers_user1; + + EXPECT_CALL(decoder_filter_callbacks_, sendLocalReply(_, _, _, _, _)) + .WillOnce(Invoke([&](Http::Code code, absl::string_view body, + std::function, + const absl::optional grpc_status, + absl::string_view details) { + EXPECT_EQ(Http::Code::Unauthorized, code); + EXPECT_EQ("User authentication failed. Missing username and password", body); + EXPECT_EQ(grpc_status, absl::nullopt); + EXPECT_EQ(details, "no_credential_for_basic_auth"); + })); + EXPECT_EQ(Http::FilterHeadersStatus::StopIteration, + filter_->decodeHeaders(request_headers_user1, true)); +} + +} // namespace BasicAuth +} // namespace HttpFilters +} // namespace Extensions +} // namespace Envoy diff --git a/tools/spelling/spelling_dictionary.txt b/tools/spelling/spelling_dictionary.txt index ba9fe8bc3477..29e9a2538994 100644 --- a/tools/spelling/spelling_dictionary.txt +++ b/tools/spelling/spelling_dictionary.txt @@ -823,6 +823,7 @@ hostnames hostset hotrestart hrefs +htpasswd huffman hystrix idempotency