CTTY commented on code in PR #2838:
URL: https://github.com/apache/iceberg-rust/pull/2838#discussion_r3754234661


##########
crates/catalog/rest/src/catalog.rs:
##########
@@ -179,6 +196,53 @@ pub(crate) struct RestCatalogConfig {
 
     #[builder(default)]
     client: Option<Client>,
+
+    /// Lazily-created default HTTP client, shared through clones of this
+    /// config so OAuth and catalog traffic reuse one connection pool
+    /// (matching the single-client behavior before the AuthManager refactor).
+    #[builder(default)]
+    default_client: Arc<OnceLock<Client>>,
+
+    #[builder(default)]
+    auth_manager: Option<Arc<dyn AuthManager>>,

Review Comment:
   This should be moved to RestCatalog directly



##########
crates/catalog/rest/src/catalog.rs:
##########
@@ -341,6 +359,57 @@ impl RestCatalogConfig {
             .unwrap_or(false)
     }
 
+    /// The configured auth scheme: explicit `rest.auth.type` (matched
+    /// case-insensitively) when set;
+    /// otherwise `oauth2` when a `token`, `credential` or `oauth2-server-uri`
+    /// is configured (preserving pre-`rest.auth.type` setups), `none` when
+    /// none is.
+    fn auth_type(&self) -> String {
+        self.props
+            .get(REST_CATALOG_PROP_AUTH_TYPE)
+            // Matched case-insensitively, as the other flag properties are.
+            .map(|auth_type| auth_type.to_ascii_lowercase())
+            .unwrap_or_else(|| {
+                if self.token().is_some()
+                    || self.credential().is_some()
+                    || self.explicit_oauth2_server_uri().is_some()
+                {
+                    AUTH_TYPE_OAUTH2.to_string()
+                } else {
+                    AUTH_TYPE_NONE.to_string()
+                }
+            })
+    }
+
+    /// Resolves the auth manager: a `with_auth_manager` override wins,
+    /// otherwise one is built from the `rest.auth.type` configuration.
+    pub(crate) fn resolve_auth_manager(&self) -> Result<Arc<dyn AuthManager>> {

Review Comment:
   AuthManager should live within `RestCatalog` directly as `Option<Arc<dyn 
AuthManager>>`, and it should be resolved along with context initialization(You 
are already doing this now :) but I think the main point is that auth manager 
and related functions should not live in `RestCatalogConfig`.)



##########
crates/catalog/rest/src/catalog.rs:
##########
@@ -349,16 +418,124 @@ impl RestCatalogConfig {
 
         let mut props = config.defaults;
         props.extend(self.props);
+        // The builder moved the client warehouse off the props; restore it
+        // between defaults and overrides (default < client < override).
+        if let Some(warehouse) = &self.warehouse {
+            props.insert(REST_CATALOG_PROP_WAREHOUSE.to_string(), 
warehouse.clone());
+        }
         props.extend(config.overrides);
 
         self.props = props;
         self
     }
 }
 
-#[derive(Debug)]
+/// Parses the `credential` property.
+///
+/// ## Output
+///
+/// - `None`: No credential is set.
+/// - `Some(None, client_secret)`: No client_id is set, use client_secret 
directly.
+/// - `Some(Some(client_id), client_secret)`: Both client_id and client_secret 
are set.
+pub(crate) fn credential_from_props(
+    props: &HashMap<String, String>,
+) -> Option<(Option<String>, String)> {
+    let cred = props.get("credential")?;
+
+    match cred.split_once(':') {
+        Some((client_id, client_secret)) => {
+            Some((Some(client_id.to_string()), client_secret.to_string()))
+        }
+        None => Some((None, cred.to_string())),
+    }
+}
+
+/// The extra headers added to each request, which include:
+///
+/// - `content-type`
+/// - `x-client-version`
+/// - `user-agent`
+/// - All headers specified by `header.xxx` in props.
+pub(crate) fn extra_headers_from_props(props: &HashMap<String, String>) -> 
Result<HeaderMap> {
+    let mut headers = HeaderMap::from_iter([
+        (
+            header::CONTENT_TYPE,
+            HeaderValue::from_static("application/json"),
+        ),
+        (
+            HeaderName::from_static("x-client-version"),
+            HeaderValue::from_static(ICEBERG_REST_SPEC_VERSION),
+        ),
+        (
+            header::USER_AGENT,
+            
HeaderValue::from_str(&format!("iceberg-rs/{CARGO_PKG_VERSION}")).unwrap(),
+        ),
+    ]);
+
+    headers.extend(explicit_headers_from_props(props)?);
+
+    Ok(headers)
+}
+
+/// The default OAuth2 token endpoint for a catalog `uri`.
+pub(crate) fn default_token_endpoint(uri: &str) -> String {
+    [uri, PATH_V1, "oauth", "tokens"].join("/")
+}
+
+/// Only the headers explicitly configured via `header.xxx` props (no 
defaults).
+pub(crate) fn explicit_headers_from_props(props: &HashMap<String, String>) -> 
Result<HeaderMap> {
+    let mut headers = HeaderMap::new();
+    for (key, value) in props
+        .iter()
+        .filter_map(|(k, v)| k.strip_prefix("header.").map(|k| (k, v)))
+    {
+        headers.insert(
+            HeaderName::from_str(key).map_err(|e| {
+                Error::new(
+                    ErrorKind::DataInvalid,
+                    format!("Invalid header name: {key}"),
+                )
+                .with_source(e)
+            })?,
+            HeaderValue::from_str(value).map_err(|e| {
+                Error::new(
+                    ErrorKind::DataInvalid,
+                    // The value itself is omitted: it may be a secret.
+                    format!("Invalid value for header: {key}"),
+                )
+                .with_source(e)
+            })?,
+        );
+    }
+
+    Ok(headers)
+}
+
+/// The optional OAuth parameters added to each authentication request.
+pub(crate) fn oauth_params_from_props(props: &HashMap<String, String>) -> 
HashMap<String, String> {
+    let mut params = HashMap::new();
+
+    if let Some(scope) = props.get("scope") {
+        params.insert("scope".to_string(), scope.to_string());
+    } else {
+        params.insert("scope".to_string(), "catalog".to_string());
+    }
+
+    let optional_params = ["audience", "resource"];
+    for param_name in optional_params {
+        if let Some(value) = props.get(param_name) {
+            params.insert(param_name.to_string(), value.to_string());
+        }
+    }
+
+    params
+}
+
 struct RestContext {
     client: HttpClient,
+    /// The session the catalog's auth manager derived from the merged
+    /// configuration; it authenticates every request below.
+    session: Arc<dyn AuthSession>,

Review Comment:
   I think the Session needs to be binded with the session directly. My 
understanding is that each client will have a session. and if a child session 
wants to use the parent client, it will need to clone the parent client and 
remove the parent session from the client



##########
crates/catalog/rest/src/auth/mod.rs:
##########
@@ -0,0 +1,251 @@
+// 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.
+
+//! Pluggable authentication for the REST catalog, mirroring Iceberg Java's
+//! `AuthManager`/`AuthSession` API.
+
+mod oauth2;
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::{HeaderMap, Method};
+use iceberg::Result;
+pub use oauth2::OAuth2Manager;
+use reqwest::{Client, Request};
+
+/// `rest.auth.type` value disabling authentication.
+pub const AUTH_TYPE_NONE: &str = "none";
+/// `rest.auth.type` value selecting OAuth2 token authentication.
+pub const AUTH_TYPE_OAUTH2: &str = "oauth2";
+
+/// Creates the [`AuthSession`]s used to authenticate REST catalog requests.
+///
+/// A manager is created once per catalog, either from the `rest.auth.type`
+/// property or injected through `RestCatalogBuilder::with_auth_manager`. It
+/// builds the sessions the catalog then keeps.
+///
+/// Both methods are handed the catalog's HTTP client, which an implementation
+/// may reuse for its own requests (e.g. a token exchange) so that they share
+/// the catalog's connection pool.
+#[async_trait]
+pub trait AuthManager: Debug + Send + Sync {
+    /// Session used for the initial `/v1/config` handshake, given the
+    /// user-supplied properties.
+    ///
+    /// Returns a [`Box`]: an init session is used once and released, unlike
+    /// the shared [`AuthManager::catalog_session`].
+    async fn init_session(
+        &self,
+        client: &Client,
+        props: &HashMap<String, String>,
+    ) -> Result<Box<dyn AuthSession>>;
+
+    /// Session used for all subsequent catalog requests, given the properties
+    /// merged from the user configuration and the server's config response.
+    ///
+    /// Returns an [`Arc`]: this session is shared by concurrent requests for
+    /// the rest of the catalog's lifetime. Implementations may carry state
+    /// (e.g. a cached token) over from the init session.
+    async fn catalog_session(
+        &self,
+        client: &Client,

Review Comment:
   Same here, I think this should be HttpClient



##########
crates/catalog/rest/src/client.rs:
##########
@@ -250,17 +107,20 @@ impl HttpClient {
             .headers(self.extra_headers.clone())
     }
 
-    /// Executes the given `Request` and returns a `Response`.
-    pub async fn execute(&self, mut request: Request) -> Result<Response> {
-        request.headers_mut().extend(self.extra_headers.clone());
-        Ok(self.client.execute(request).await?)
-    }
-
     // Queries the Iceberg REST catalog after authentication with the given 
`Request` and
     // returns a `Response`.
-    pub async fn query_catalog(&self, mut request: Request) -> 
Result<Response> {
-        self.authenticate(&mut request).await?;
-        self.execute(request).await
+    pub async fn query_catalog(
+        &self,
+        mut request: Request,

Review Comment:
   This should be HttpRequest



##########
crates/catalog/rest/src/auth/mod.rs:
##########
@@ -0,0 +1,251 @@
+// 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.
+
+//! Pluggable authentication for the REST catalog, mirroring Iceberg Java's
+//! `AuthManager`/`AuthSession` API.
+
+mod oauth2;
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::{HeaderMap, Method};
+use iceberg::Result;
+pub use oauth2::OAuth2Manager;
+use reqwest::{Client, Request};
+
+/// `rest.auth.type` value disabling authentication.
+pub const AUTH_TYPE_NONE: &str = "none";
+/// `rest.auth.type` value selecting OAuth2 token authentication.
+pub const AUTH_TYPE_OAUTH2: &str = "oauth2";
+
+/// Creates the [`AuthSession`]s used to authenticate REST catalog requests.
+///
+/// A manager is created once per catalog, either from the `rest.auth.type`
+/// property or injected through `RestCatalogBuilder::with_auth_manager`. It
+/// builds the sessions the catalog then keeps.
+///
+/// Both methods are handed the catalog's HTTP client, which an implementation
+/// may reuse for its own requests (e.g. a token exchange) so that they share
+/// the catalog's connection pool.
+#[async_trait]
+pub trait AuthManager: Debug + Send + Sync {
+    /// Session used for the initial `/v1/config` handshake, given the
+    /// user-supplied properties.
+    ///
+    /// Returns a [`Box`]: an init session is used once and released, unlike
+    /// the shared [`AuthManager::catalog_session`].
+    async fn init_session(
+        &self,
+        client: &Client,
+        props: &HashMap<String, String>,
+    ) -> Result<Box<dyn AuthSession>>;
+
+    /// Session used for all subsequent catalog requests, given the properties
+    /// merged from the user configuration and the server's config response.
+    ///
+    /// Returns an [`Arc`]: this session is shared by concurrent requests for
+    /// the rest of the catalog's lifetime. Implementations may carry state
+    /// (e.g. a cached token) over from the init session.
+    async fn catalog_session(
+        &self,
+        client: &Client,
+        props: &HashMap<String, String>,
+    ) -> Result<Arc<dyn AuthSession>>;
+}
+
+/// An outgoing REST request being authenticated by an [`AuthSession`].
+///
+/// Wraps the request so an [`AuthSession`] mutates it through the stable
+/// `http` crate types rather than the concrete request type the REST catalog
+/// uses internally.
+pub struct HttpRequest<'a> {

Review Comment:
   Im leaning toward moving this to a different module `rest/src/request.rs`. 
And we move to use this most of the places. This way we will have a cleaner 
abstraction layer



##########
crates/catalog/rest/src/auth/mod.rs:
##########
@@ -0,0 +1,251 @@
+// 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.
+
+//! Pluggable authentication for the REST catalog, mirroring Iceberg Java's
+//! `AuthManager`/`AuthSession` API.
+
+mod oauth2;
+
+use std::collections::HashMap;
+use std::fmt::Debug;
+use std::sync::Arc;
+
+use async_trait::async_trait;
+use http::{HeaderMap, Method};
+use iceberg::Result;
+pub use oauth2::OAuth2Manager;
+use reqwest::{Client, Request};
+
+/// `rest.auth.type` value disabling authentication.
+pub const AUTH_TYPE_NONE: &str = "none";
+/// `rest.auth.type` value selecting OAuth2 token authentication.
+pub const AUTH_TYPE_OAUTH2: &str = "oauth2";
+
+/// Creates the [`AuthSession`]s used to authenticate REST catalog requests.
+///
+/// A manager is created once per catalog, either from the `rest.auth.type`
+/// property or injected through `RestCatalogBuilder::with_auth_manager`. It
+/// builds the sessions the catalog then keeps.
+///
+/// Both methods are handed the catalog's HTTP client, which an implementation
+/// may reuse for its own requests (e.g. a token exchange) so that they share
+/// the catalog's connection pool.
+#[async_trait]
+pub trait AuthManager: Debug + Send + Sync {
+    /// Session used for the initial `/v1/config` handshake, given the
+    /// user-supplied properties.
+    ///
+    /// Returns a [`Box`]: an init session is used once and released, unlike
+    /// the shared [`AuthManager::catalog_session`].
+    async fn init_session(
+        &self,
+        client: &Client,

Review Comment:
   AuthManager should be dealing with `HttpClient` and ideally only 
`HttpClient` will work with `Client` directly



##########
crates/catalog/rest/src/client.rs:
##########
@@ -18,55 +18,43 @@
 use std::collections::HashMap;
 use std::fmt::{Debug, Formatter};
 
-use http::StatusCode;
 use iceberg::{Error, ErrorKind, Result};
 use reqwest::header::HeaderMap;
 use reqwest::{Client, IntoUrl, Method, Request, RequestBuilder, Response};
 use serde::de::DeserializeOwned;
-use tokio::sync::Mutex;
 
 use crate::RestCatalogConfig;
-use crate::types::{ErrorResponse, TokenResponse};
+use crate::auth::{AuthSession, HttpRequest};
 
 pub(crate) struct HttpClient {
     client: Client,
 
-    /// The token to be used for authentication.
-    ///
-    /// It's possible to fetch the token from the server while needed.
-    token: Mutex<Option<String>>,
-    /// The token endpoint to be used for authentication.
-    token_endpoint: String,
-    /// The credential to be used for authentication.
-    credential: Option<(Option<String>, String)>,
     /// Extra headers to be added to each request.
     extra_headers: HeaderMap,
-    /// Extra oauth parameters to be added to each authentication request.
-    extra_oauth_params: HashMap<String, String>,
     /// Whether to disable header redaction in error logs (defaults to false 
for security).
     disable_header_redaction: bool,

Review Comment:
   I thought the HttpClient would be binded with a `AuthSession`?



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