lishuxu commented on code in PR #1132:
URL: https://github.com/apache/iceberg-cpp/pull/1132#discussion_r4720347463
##########
src/iceberg/test/rest_catalog_unit_test.cc:
##########
@@ -669,6 +670,202 @@ class RestCatalogOAuth2UriTest : public
RestCatalogLoadTableTest {
int factory_calls_ = 0;
};
+struct OAuth2RefreshModeCase {
+ std::string name;
+ std::string client;
+ std::string server_default;
+ std::string server_override;
+ bool exchange_enabled;
+};
+
+class RestCatalogOAuth2RefreshTest
+ : public RestCatalogOAuth2UriTest,
+ public ::testing::WithParamInterface<OAuth2RefreshModeCase> {};
+
+TEST_P(RestCatalogOAuth2RefreshTest,
RefreshUsesMergedConfigAndUpdatesBusinessRequests) {
+ const auto& mode = GetParam();
+ properties_["token-refresh-enabled"] = "true";
+ if (!mode.client.empty()) {
+ properties_["token-exchange-enabled"] = mode.client;
+ }
+ CatalogConfig server_config;
+ if (!mode.server_default.empty()) {
+ server_config.defaults["token-exchange-enabled"] = mode.server_default;
+ }
+ if (!mode.server_override.empty()) {
+ server_config.overrides["token-exchange-enabled"] = mode.server_override;
+ }
+ ExpectInit(server_config,
+
R"({"access_token":"initial","token_type":"bearer","expires_in":1})");
+
+ std::unordered_map<std::string, std::string> expected_form;
+ if (mode.exchange_enabled) {
+ expected_form = {
+ {"grant_type", "urn:ietf:params:oauth:grant-type:token-exchange"},
+ {"subject_token", "initial"},
+ {"subject_token_type", auth::AuthProperties::kAccessTokenType},
+ {"scope", "catalog"},
+ };
+ } else {
+ expected_form = {{"grant_type", "client_credentials"},
+ {"client_id", "client"},
+ {"client_secret", "secret"},
+ {"scope", "catalog"}};
+ }
+ EXPECT_CALL(*mock_client_, PostForm("https://auth.example/token/", _, _, _,
_))
+ .WillOnce([&](const std::string&, const auto& form, const auto& headers,
+ const ErrorHandler&, auth::AuthSession&) ->
Result<HttpResponse> {
+ EXPECT_THAT(form, ::testing::ContainerEq(expected_form));
+ if (mode.exchange_enabled) {
+ // Config selection is unchanged if the queued refresh starts after
expiry.
+ EXPECT_THAT(
+ headers,
+ ::testing::ElementsAre(::testing::Pair(
+ "Authorization",
+ ::testing::AnyOf("Bearer initial", "Basic
Y2xpZW50OnNlY3JldA=="))));
+ } else {
+ EXPECT_TRUE(headers.empty());
+ }
+ return HttpResponse(200,
R"({"access_token":"refreshed","token_type":"bearer"})");
+ });
+
+ test::MockExecutor executor;
+ std::promise<ExecutorTask> queued;
+ auto ready = queued.get_future();
+ EXPECT_CALL(executor, Submit).WillOnce([&](ExecutorTask task) -> Status {
+ queued.set_value(std::move(task));
+ return {};
+ });
+ ICEBERG_UNWRAP_OR_FAIL(auto root, MakeOAuth2Catalog(&executor));
+ ASSERT_EQ(ready.wait_for(std::chrono::seconds(5)),
std::future_status::ready);
+ std::move(ready.get())();
+
+ EXPECT_CALL(*mock_client_, Get("https://catalog.example/api/v1/namespaces",
_, _, _, _))
+ .WillOnce([](const std::string&, const auto&, const auto&, const
ErrorHandler&,
+ auth::AuthSession& session) -> Result<HttpResponse> {
+ ICEBERG_ASSIGN_OR_RAISE(auto request, session.Authenticate({}));
+ EXPECT_EQ(request.headers.at("Authorization"), "Bearer refreshed");
+ return HttpResponse(200, R"({"namespaces":[]})");
+ });
+ ICEBERG_UNWRAP_OR_FAIL(auto catalog, root->AsCatalog());
+ EXPECT_THAT(catalog->ListNamespaces({}), IsOk());
+ EXPECT_EQ(factory_calls_, 2);
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ ExchangeModes, RestCatalogOAuth2RefreshTest,
+ ::testing::Values(OAuth2RefreshModeCase{"Default", "", "", "", true},
+ OAuth2RefreshModeCase{"Enabled", "true", "", "", true},
+ OAuth2RefreshModeCase{"Disabled", "false", "", "",
false},
+ OAuth2RefreshModeCase{"ServerDisables", "true", "",
"false", false},
+ OAuth2RefreshModeCase{"ServerEnables", "false", "",
"true", true},
+ OAuth2RefreshModeCase{"ServerDefaultDisables", "",
"false", "",
+ false},
+ OAuth2RefreshModeCase{"ClientOverridesServerDefault",
"false",
+ "true", "", false}),
+ [](const ::testing::TestParamInfo<OAuth2RefreshModeCase>& info) {
+ return info.param.name;
+ });
+
+struct OAuth2RecoveryCase {
+ std::string name;
+ bool expired;
+ bool exchange_enabled;
+};
+
+class RestCatalogOAuth2RecoveryTest
+ : public RestCatalogOAuth2UriTest,
+ public ::testing::WithParamInterface<OAuth2RecoveryCase> {};
+
+TEST_P(RestCatalogOAuth2RecoveryTest, RecoversAndUpdatesBusinessRequests) {
+ const auto& mode = GetParam();
+ properties_["token-refresh-enabled"] = "true";
+ properties_["token-exchange-enabled"] = mode.exchange_enabled ? "true" :
"false";
+ properties_["credential"] = ":SeCrEt:Tail";
+ ExpectInit({}, nlohmann::json({{"access_token", "Initial"},
+ {"token_type", "bearer"},
+ {"expires_in", mode.expired ? 0 : 1}})
+ .dump());
+
+ const int expected_requests = mode.expired ? 1 : 7;
+ int requests = 0;
+ EXPECT_CALL(*mock_client_, PostForm("https://auth.example/token/", _, _, _,
_))
+ .Times(expected_requests)
+ .WillRepeatedly([&](const std::string&, const auto& form, const auto&
headers,
+ const ErrorHandler&,
+ auth::AuthSession& session) -> Result<HttpResponse> {
+ ++requests;
+ HttpRequest request{.headers = {{"authorization", "Bearer
StaleDefault"},
+ {"X-Trace", "KeepThisValue"}}};
+ for (const auto& [key, value] : headers) {
+ request.headers.insert_or_assign(key, value);
+ }
+ ICEBERG_ASSIGN_OR_RAISE(auto authenticated,
+ session.Authenticate(std::move(request)));
+ std::unordered_map<std::string, std::string> expected_form{{"scope",
"catalog"}};
+ if (mode.exchange_enabled) {
+ expected_form.insert({
+ {"grant_type",
"urn:ietf:params:oauth:grant-type:token-exchange"},
+ {"subject_token", "Initial"},
+ {"subject_token_type", auth::AuthProperties::kAccessTokenType},
+ });
+ if (mode.expired || requests == 7) {
+ EXPECT_EQ(authenticated.headers.at("Authorization"),
+ "Basic OlNlQ3JFdDpUYWls");
+ } else {
+ // Earlier attempts can also use Basic if the queued token has
expired.
+ EXPECT_THAT(authenticated.headers.at("Authorization"),
+ ::testing::AnyOf("Bearer Initial", "Basic
OlNlQ3JFdDpUYWls"));
+ }
+ } else {
+ expected_form.insert(
+ {{"grant_type", "client_credentials"}, {"client_secret",
"SeCrEt:Tail"}});
+ EXPECT_EQ(authenticated.headers.at("Authorization"), "Bearer
StaleDefault");
+ }
+ EXPECT_THAT(form, ::testing::ContainerEq(expected_form));
+ EXPECT_EQ(authenticated.headers.at("X-Trace"), "KeepThisValue");
+ if (requests < expected_requests) {
+ return IOError("ordinary refresh failed");
+ }
+ return HttpResponse(200,
R"({"access_token":"Recovered","token_type":"bearer"})");
+ });
+
+ test::MockExecutor executor;
+ std::promise<ExecutorTask> queued;
+ auto ready = queued.get_future();
+ EXPECT_CALL(executor, Submit).WillOnce([&](ExecutorTask task) -> Status {
+ queued.set_value(std::move(task));
+ return {};
+ });
+ ICEBERG_UNWRAP_OR_FAIL(auto root, MakeOAuth2Catalog(&executor));
+ ASSERT_EQ(ready.wait_for(std::chrono::seconds(5)),
std::future_status::ready);
+ test::FakeRetryEnvironment retry_environment;
+ ScopedRetryTestHooks retry_hooks(retry_environment.hooks());
+ std::move(ready.get())();
+ EXPECT_EQ(requests, expected_requests);
+
+ EXPECT_CALL(*mock_client_, Get("https://catalog.example/api/v1/namespaces",
_, _, _, _))
+ .WillOnce([](const std::string&, const auto&, const auto&, const
ErrorHandler&,
+ auth::AuthSession& session) -> Result<HttpResponse> {
+ ICEBERG_ASSIGN_OR_RAISE(auto request, session.Authenticate({}));
+ EXPECT_EQ(request.headers.at("Authorization"), "Bearer Recovered");
+ return HttpResponse(200, R"({"namespaces":[]})");
+ });
+ ICEBERG_UNWRAP_OR_FAIL(auto catalog, root->AsCatalog());
+ EXPECT_THAT(catalog->ListNamespaces({}), IsOk());
+ EXPECT_EQ(factory_calls_, 2);
+}
+
+INSTANTIATE_TEST_SUITE_P(
+ RecoveryModes, RestCatalogOAuth2RecoveryTest,
+ ::testing::Values(OAuth2RecoveryCase{"ExpiredExchange", true, true},
Review Comment:
Kept only FinalExchange at the catalog layer and moved the seventh-attempt
client_credentials success case next to StopsAfterHttpRetryBudget. The loopback
tests cover both expired-token cases.
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]
---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]