wgtmac commented on code in PR #577:
URL: https://github.com/apache/iceberg-cpp/pull/577#discussion_r2896354659


##########
src/iceberg/catalog/rest/auth/auth_manager.cc:
##########
@@ -90,4 +94,135 @@ Result<std::unique_ptr<AuthManager>> MakeBasicAuthManager(
   return std::make_unique<BasicAuthManager>();
 }
 
+/// \brief OAuth2 authentication manager.
+///
+/// Two-phase init: InitSession fetches and caches a token for the config 
request;
+/// CatalogSession reuses the cached token and enables refresh.
+class OAuth2AuthManager : public AuthManager {
+ public:
+  Result<std::shared_ptr<AuthSession>> InitSession(
+      HttpClient& init_client,
+      const std::unordered_map<std::string, std::string>& properties) override 
{
+    // Credential takes priority: fetch a fresh token for the config request.
+    auto credential_it = properties.find(AuthProperties::kOAuth2Credential);
+    if (credential_it != properties.end() && !credential_it->second.empty()) {
+      ICEBERG_ASSIGN_OR_RAISE(auto ctx, ParseOAuth2Context(properties));
+      auto noop_session = AuthSession::MakeDefault({});
+      ICEBERG_ASSIGN_OR_RAISE(init_token_response_,
+                              FetchToken(init_client, ctx.token_endpoint, 
ctx.client_id,
+                                         ctx.client_secret, ctx.scope, 
*noop_session));
+      return AuthSession::MakeDefault(
+          {{"Authorization", "Bearer " + init_token_response_->access_token}});
+    }
+
+    auto token_it = properties.find(AuthProperties::kOAuth2Token);
+    if (token_it != properties.end() && !token_it->second.empty()) {
+      return AuthSession::MakeDefault({{"Authorization", "Bearer " + 
token_it->second}});
+    }
+
+    return AuthSession::MakeDefault({});
+  }
+
+  Result<std::shared_ptr<AuthSession>> CatalogSession(
+      HttpClient& client,
+      const std::unordered_map<std::string, std::string>& properties) override 
{
+    if (init_token_response_.has_value()) {
+      auto token_response = std::move(*init_token_response_);
+      init_token_response_.reset();
+      ICEBERG_ASSIGN_OR_RAISE(auto ctx, ParseOAuth2Context(properties));
+      return AuthSession::MakeOAuth2(token_response, ctx.token_endpoint, 
ctx.client_id,
+                                     ctx.client_secret, ctx.scope, client);
+    }
+
+    // If token is provided, use it directly.
+    auto token_it = properties.find(AuthProperties::kOAuth2Token);
+    if (token_it != properties.end() && !token_it->second.empty()) {
+      return AuthSession::MakeDefault({{"Authorization", "Bearer " + 
token_it->second}});
+    }
+
+    // Fetch a new token using client_credentials grant.
+    auto credential_it = properties.find(AuthProperties::kOAuth2Credential);
+    if (credential_it != properties.end() && !credential_it->second.empty()) {
+      ICEBERG_ASSIGN_OR_RAISE(auto ctx, ParseOAuth2Context(properties));
+      auto noop_session = AuthSession::MakeDefault({});
+      OAuthTokenResponse token_response;
+      ICEBERG_ASSIGN_OR_RAISE(token_response,
+                              FetchToken(client, ctx.token_endpoint, 
ctx.client_id,
+                                         ctx.client_secret, ctx.scope, 
*noop_session));
+      return AuthSession::MakeOAuth2(token_response, ctx.token_endpoint, 
ctx.client_id,
+                                     ctx.client_secret, ctx.scope, client);
+    }
+
+    return AuthSession::MakeDefault({});
+  }
+
+  // TODO(lishuxu): Override TableSession() to support token exchange (RFC 
8693).
+  // TODO(lishuxu): Override ContextualSession() to support per-context token 
exchange.
+
+ private:
+  struct OAuth2Context {
+    std::string client_id;
+    std::string client_secret;
+    std::string token_endpoint;
+    std::string scope;
+  };
+
+  /// \brief Parse credential, token endpoint, and scope from properties.
+  static Result<OAuth2Context> ParseOAuth2Context(
+      const std::unordered_map<std::string, std::string>& properties) {
+    OAuth2Context ctx;
+
+    auto credential_it = properties.find(AuthProperties::kOAuth2Credential);
+    if (credential_it == properties.end() || credential_it->second.empty()) {
+      return InvalidArgument("OAuth2 authentication requires '{}' property",
+                             AuthProperties::kOAuth2Credential);
+    }
+    const auto& credential = credential_it->second;
+    auto colon_pos = credential.find(':');
+    if (colon_pos == std::string::npos) {

Review Comment:
   ⚠️ **Parity Bug**: Iceberg Java's `OAuth2Util.parseCredential` allows 
credentials without a colon (`:`). If no colon is found, the entire string is 
treated as the `client_secret` and `client_id` becomes `null`/empty. This is 
required for some IdP setups that only provide a secret/bearer token. Please 
update the parsing logic to fall back to `client_secret = credential` and 
`client_id = ""`.



##########
src/iceberg/catalog/rest/auth/oauth2_util.cc:
##########
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#include "iceberg/catalog/rest/auth/oauth2_util.h"
+
+#include <nlohmann/json.hpp>
+
+#include "iceberg/catalog/rest/auth/auth_session.h"
+#include "iceberg/catalog/rest/error_handlers.h"
+#include "iceberg/catalog/rest/http_client.h"
+#include "iceberg/json_serde_internal.h"
+#include "iceberg/util/json_util_internal.h"
+#include "iceberg/util/macros.h"
+
+namespace iceberg::rest::auth {
+
+namespace {
+
+constexpr std::string_view kAccessToken = "access_token";
+constexpr std::string_view kTokenType = "token_type";
+constexpr std::string_view kExpiresIn = "expires_in";
+constexpr std::string_view kRefreshToken = "refresh_token";
+constexpr std::string_view kScope = "scope";
+
+constexpr std::string_view kGrantType = "grant_type";
+constexpr std::string_view kClientCredentials = "client_credentials";
+constexpr std::string_view kClientId = "client_id";
+constexpr std::string_view kClientSecret = "client_secret";
+
+}  // namespace
+
+Status OAuthTokenResponse::Validate() const {
+  if (access_token.empty()) {
+    return ValidationFailed("OAuth2 token response missing required 
'access_token'");
+  }
+  if (token_type.empty()) {
+    return ValidationFailed("OAuth2 token response missing required 
'token_type'");
+  }
+  return {};
+}
+
+Result<OAuthTokenResponse> OAuthTokenResponseFromJsonString(const std::string& 
json_str) {
+  ICEBERG_ASSIGN_OR_RAISE(auto json, FromJsonString(json_str));
+
+  OAuthTokenResponse response;
+  ICEBERG_ASSIGN_OR_RAISE(response.access_token,
+                          GetJsonValue<std::string>(json, kAccessToken));
+  ICEBERG_ASSIGN_OR_RAISE(response.token_type,
+                          GetJsonValue<std::string>(json, kTokenType));
+  ICEBERG_ASSIGN_OR_RAISE(response.expires_in,
+                          GetJsonValueOrDefault<int64_t>(json, kExpiresIn, 0));

Review Comment:
   💡 **Future-proofing / JWT Expiration**: If `expires_in` is missing and the 
token is a JWT, Iceberg Java decodes the JWT payload to extract the `exp` 
claim. While defaulting to `0` here is acceptable since auto-refresh is marked 
as a TODO, consider adding a comment here as a reminder for the future 
auto-refresh implementation.



##########
src/iceberg/catalog/rest/auth/oauth2_util.cc:
##########
@@ -0,0 +1,115 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you 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.
+ */
+
+#include "iceberg/catalog/rest/auth/oauth2_util.h"
+
+#include <nlohmann/json.hpp>
+
+#include "iceberg/catalog/rest/auth/auth_session.h"
+#include "iceberg/catalog/rest/error_handlers.h"
+#include "iceberg/catalog/rest/http_client.h"
+#include "iceberg/json_serde_internal.h"
+#include "iceberg/util/json_util_internal.h"
+#include "iceberg/util/macros.h"
+
+namespace iceberg::rest::auth {
+
+namespace {
+
+constexpr std::string_view kAccessToken = "access_token";
+constexpr std::string_view kTokenType = "token_type";
+constexpr std::string_view kExpiresIn = "expires_in";
+constexpr std::string_view kRefreshToken = "refresh_token";
+constexpr std::string_view kScope = "scope";
+
+constexpr std::string_view kGrantType = "grant_type";
+constexpr std::string_view kClientCredentials = "client_credentials";
+constexpr std::string_view kClientId = "client_id";
+constexpr std::string_view kClientSecret = "client_secret";
+
+}  // namespace
+
+Status OAuthTokenResponse::Validate() const {
+  if (access_token.empty()) {
+    return ValidationFailed("OAuth2 token response missing required 
'access_token'");
+  }
+  if (token_type.empty()) {
+    return ValidationFailed("OAuth2 token response missing required 
'token_type'");
+  }
+  return {};
+}
+
+Result<OAuthTokenResponse> OAuthTokenResponseFromJsonString(const std::string& 
json_str) {
+  ICEBERG_ASSIGN_OR_RAISE(auto json, FromJsonString(json_str));
+
+  OAuthTokenResponse response;
+  ICEBERG_ASSIGN_OR_RAISE(response.access_token,
+                          GetJsonValue<std::string>(json, kAccessToken));
+  ICEBERG_ASSIGN_OR_RAISE(response.token_type,
+                          GetJsonValue<std::string>(json, kTokenType));
+  ICEBERG_ASSIGN_OR_RAISE(response.expires_in,
+                          GetJsonValueOrDefault<int64_t>(json, kExpiresIn, 0));
+  ICEBERG_ASSIGN_OR_RAISE(response.refresh_token,
+                          GetJsonValueOrDefault<std::string>(json, 
kRefreshToken));
+  ICEBERG_ASSIGN_OR_RAISE(response.scope,
+                          GetJsonValueOrDefault<std::string>(json, kScope));
+  ICEBERG_RETURN_UNEXPECTED(response.Validate());
+  return response;
+}
+
+Result<OAuthTokenResponse> FetchToken(HttpClient& client,
+                                      const std::string& token_endpoint,
+                                      const std::string& client_id,
+                                      const std::string& client_secret,
+                                      const std::string& scope, AuthSession& 
session) {
+  std::unordered_map<std::string, std::string> form_data{
+      {std::string(kGrantType), std::string(kClientCredentials)},
+      {std::string(kClientId), client_id},

Review Comment:
   Following the Java parity fix above (where `client_id` might be empty), you 
should only append `client_id` to the `form_data` if it is not empty:
   ```cpp
   if (!client_id.empty()) {
       form_data.emplace(std::string(kClientId), client_id);
   }
   ```



-- 
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]

Reply via email to