danielcweeks commented on code in PR #10753:
URL: https://github.com/apache/iceberg/pull/10753#discussion_r1807055242


##########
core/src/main/java/org/apache/iceberg/rest/RESTSessionCatalog.java:
##########
@@ -273,35 +227,11 @@ public void initialize(String name, Map<String, String> 
unresolved) {
       this.endpoints = ImmutableSet.copyOf(config.endpoints());
     }
 
-    this.sessions = newSessionCache(mergedProps);
-    this.tableSessions = newSessionCache(mergedProps);
-    this.keepTokenRefreshed =
-        PropertyUtil.propertyAsBoolean(
-            mergedProps,
-            OAuth2Properties.TOKEN_REFRESH_ENABLED,
-            OAuth2Properties.TOKEN_REFRESH_ENABLED_DEFAULT);
     this.client = clientBuilder.apply(mergedProps);
     this.paths = ResourcePaths.forCatalogProperties(mergedProps);
 
-    String token = mergedProps.get(OAuth2Properties.TOKEN);
-    this.catalogAuth =
-        new AuthSession(
-            baseHeaders,
-            AuthConfig.builder()
-                .credential(credential)
-                .scope(scope)
-                .oauth2ServerUri(oauth2ServerUri)
-                .optionalOAuthParams(optionalOAuthParams)
-                .build());
-    if (authResponse != null) {
-      this.catalogAuth =
-          AuthSession.fromTokenResponse(
-              client, tokenRefreshExecutor(name), authResponse, 
startTimeMillis, catalogAuth);
-    } else if (token != null) {
-      this.catalogAuth =
-          AuthSession.fromAccessToken(
-              client, tokenRefreshExecutor(name), token, 
expiresAtMillis(mergedProps), catalogAuth);
-    }
+    authManager.initialize(name, client, mergedProps);

Review Comment:
   I feel like we should have separate AuthManager instances, not 
double-initialize.



##########
core/src/main/java/org/apache/iceberg/rest/auth/AuthManager.java:
##########
@@ -0,0 +1,93 @@
+/*
+ * 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.
+ */
+package org.apache.iceberg.rest.auth;
+
+import java.util.Map;
+import org.apache.iceberg.catalog.SessionCatalog;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.rest.RESTClient;
+
+/**
+ * Manager for authentication sessions. This interface is used to create 
sessions for the catalog,
+ * the tables/views, and any other context that requires authentication.
+ *
+ * <p>Managers are usually stateful and may require initialization and 
cleanup. The manager is
+ * created by the catalog and is closed when the catalog is closed.
+ */
+public interface AuthManager extends AutoCloseable {
+
+  /**
+   * Initializes the manager with the owner of the catalog, the REST client, 
and the properties
+   * provided in the catalog configuration.
+   *
+   * <p>This method is intended to be called many times, typically once before 
contacting the config
+   * endpoint, and once after contacting the config endpoint. The properties 
provided in the catalog
+   * configuration are passed in the first call, and the properties returned 
by the config endpoint
+   * are passed in the second call, merged with the catalog ones.
+   *
+   * <p>This method cannot return null.
+   */
+  void initialize(String owner, RESTClient client, Map<String, String> 
properties);

Review Comment:
   I feel like `owner` isn't the right term.  Maybe just `name`?



##########
core/src/main/java/org/apache/iceberg/rest/auth/OAuth2Manager.java:
##########
@@ -0,0 +1,220 @@
+/*
+ * 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.
+ */
+package org.apache.iceberg.rest.auth;
+
+import java.time.Duration;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.function.Function;
+import org.apache.iceberg.CatalogProperties;
+import org.apache.iceberg.catalog.SessionCatalog;
+import org.apache.iceberg.catalog.TableIdentifier;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableList;
+import org.apache.iceberg.relocated.com.google.common.collect.ImmutableSet;
+import org.apache.iceberg.relocated.com.google.common.collect.Maps;
+import org.apache.iceberg.rest.RESTClient;
+import org.apache.iceberg.rest.RESTUtil;
+import org.apache.iceberg.rest.ResourcePaths;
+import org.apache.iceberg.rest.responses.OAuthTokenResponse;
+import org.apache.iceberg.util.PropertyUtil;
+
+public class OAuth2Manager extends RefreshingAuthManager {
+
+  private static final List<String> TOKEN_PREFERENCE_ORDER =
+      ImmutableList.of(
+          OAuth2Properties.ID_TOKEN_TYPE,
+          OAuth2Properties.ACCESS_TOKEN_TYPE,
+          OAuth2Properties.JWT_TOKEN_TYPE,
+          OAuth2Properties.SAML2_TOKEN_TYPE,
+          OAuth2Properties.SAML1_TOKEN_TYPE);
+
+  // Auth-related properties that are allowed to be passed to the table session
+  private static final Set<String> TABLE_SESSION_ALLOW_LIST =
+      ImmutableSet.<String>builder()
+          .add(OAuth2Properties.TOKEN)
+          .addAll(TOKEN_PREFERENCE_ORDER)
+          .build();
+
+  private RESTClient client;
+  private Map<String, String> properties;
+  private AuthConfig config;
+  private long startTimeMillis;
+  private OAuthTokenResponse authResponse;
+  private AuthSessionCache sessionCache;
+
+  @Override
+  public void initialize(String owner, RESTClient restClient, Map<String, 
String> props) {
+    this.client = restClient;
+    this.properties = props;
+    this.config = createConfig(props);
+    this.sessionCache = new AuthSessionCache(sessionTimeout(props));
+    setExecutorNamePrefix(owner + "-token-refresh");
+    setKeepRefreshed(config.keepRefreshed());
+    // keep track of the start time for token refresh
+    this.startTimeMillis = System.currentTimeMillis();
+  }
+
+  @Override
+  public AuthSession catalogSession() {
+    OAuth2Util.AuthSession session =
+        new OAuth2Util.AuthSession(
+            RESTUtil.merge(configHeaders(properties), 
OAuth2Util.authHeaders(config.token())),
+            config);
+    if (config.credential() != null && authResponse == null) {
+      this.authResponse =
+          OAuth2Util.fetchToken(
+              client,
+              session,
+              config.credential(),
+              config.scope(),
+              config.oauth2ServerUri(),
+              config.optionalOAuthParams());
+    }
+    if (authResponse != null) {
+      return OAuth2Util.AuthSession.fromTokenResponse(
+          client, refreshExecutor(), authResponse, startTimeMillis, session);
+    } else if (config.token() != null) {
+      return OAuth2Util.AuthSession.fromAccessToken(
+          client, refreshExecutor(), config.token(), config.expiresAtMillis(), 
session);
+    }
+    return session;
+  }
+
+  @Override
+  public AuthSession contextualSession(SessionCatalog.SessionContext context, 
AuthSession parent) {
+    return maybeCreateChildSession(
+        context.credentials(),
+        context.properties(),
+        ignored -> context.sessionId(),
+        (OAuth2Util.AuthSession) parent);
+  }
+
+  @Override
+  public AuthSession tableSession(
+      TableIdentifier table, Map<String, String> props, AuthSession parent) {
+    return maybeCreateChildSession(
+        Maps.filterKeys(props, TABLE_SESSION_ALLOW_LIST::contains),
+        props,
+        props::get,
+        (OAuth2Util.AuthSession) parent);
+  }
+
+  @Override
+  public void close() {
+    try {
+      super.close();
+    } finally {
+      sessionCache.close();
+    }
+  }
+
+  private AuthSession maybeCreateChildSession(
+      Map<String, String> credentials,
+      Map<String, String> props,
+      Function<String, String> keyFunc,
+      OAuth2Util.AuthSession parent) {
+    if (credentials != null) {
+      // use the bearer token without exchanging
+      if (credentials.containsKey(OAuth2Properties.TOKEN)) {
+        String token = credentials.get(OAuth2Properties.TOKEN);
+        return sessionCache.cachedSession(
+            keyFunc.apply(OAuth2Properties.TOKEN),
+            () ->
+                OAuth2Util.AuthSession.fromAccessToken(
+                    client, refreshExecutor(), token, expiresAtMillis(props), 
parent));
+      }
+
+      if (credentials.containsKey(OAuth2Properties.CREDENTIAL)) {
+        // fetch a token using the client credentials flow
+        String credential = credentials.get(OAuth2Properties.CREDENTIAL);
+        return sessionCache.cachedSession(
+            keyFunc.apply(OAuth2Properties.CREDENTIAL),
+            () ->
+                OAuth2Util.AuthSession.fromCredential(
+                    client, refreshExecutor(), credential, parent));
+      }
+
+      for (String tokenType : TOKEN_PREFERENCE_ORDER) {
+        if (credentials.containsKey(tokenType)) {
+          // exchange the token for an access token using the token exchange 
flow
+          String token = credentials.get(tokenType);
+          return sessionCache.cachedSession(
+              keyFunc.apply(tokenType),
+              () ->
+                  OAuth2Util.AuthSession.fromTokenExchange(
+                      client, refreshExecutor(), token, tokenType, parent));
+        }
+      }
+    }
+    return parent;
+  }
+
+  private static AuthConfig createConfig(Map<String, String> props) {
+    String scope = props.getOrDefault(OAuth2Properties.SCOPE, 
OAuth2Properties.CATALOG_SCOPE);
+    Map<String, String> optionalOAuthParams = 
OAuth2Util.buildOptionalParam(props);
+    String oauth2ServerUri =
+        props.getOrDefault(OAuth2Properties.OAUTH2_SERVER_URI, 
ResourcePaths.tokens());
+    boolean keepRefreshed =
+        PropertyUtil.propertyAsBoolean(
+            props,
+            OAuth2Properties.TOKEN_REFRESH_ENABLED,
+            OAuth2Properties.TOKEN_REFRESH_ENABLED_DEFAULT);
+    return AuthConfig.builder()
+        .credential(props.get(OAuth2Properties.CREDENTIAL))
+        .token(props.get(OAuth2Properties.TOKEN))
+        .scope(scope)
+        .oauth2ServerUri(oauth2ServerUri)
+        .optionalOAuthParams(optionalOAuthParams)
+        .keepRefreshed(keepRefreshed)
+        .expiresAtMillis(expiresAtMillis(props))
+        .build();
+  }
+
+  private static Duration sessionTimeout(Map<String, String> props) {
+    long expirationIntervalMs =
+        PropertyUtil.propertyAsLong(
+            props,
+            CatalogProperties.AUTH_SESSION_TIMEOUT_MS,
+            CatalogProperties.AUTH_SESSION_TIMEOUT_MS_DEFAULT);
+    return Duration.ofMillis(expirationIntervalMs);
+  }
+
+  private static Long expiresAtMillis(Map<String, String> props) {
+    Long expiresInMillis = null;
+    if (props.containsKey(OAuth2Properties.TOKEN)) {
+      expiresInMillis = 
OAuth2Util.expiresAtMillis(props.get(OAuth2Properties.TOKEN));
+    }
+    if (expiresInMillis == null) {
+      if (props.containsKey(OAuth2Properties.TOKEN_EXPIRES_IN_MS)) {
+        long millis =
+            PropertyUtil.propertyAsLong(
+                props,
+                OAuth2Properties.TOKEN_EXPIRES_IN_MS,
+                OAuth2Properties.TOKEN_EXPIRES_IN_MS_DEFAULT);
+        expiresInMillis = System.currentTimeMillis() + millis;
+      }
+    }
+    return expiresInMillis;
+  }
+
+  private static Map<String, String> configHeaders(Map<String, String> props) {

Review Comment:
   These aren't auth headers, so it's awkward that they're being handled by the 
AuthManager.  This also makes it inconsistent with other auth managers.



##########
core/src/main/java/org/apache/iceberg/rest/RESTSessionCatalog.java:
##########
@@ -378,7 +289,8 @@ public List<TableIdentifier> listTables(SessionContext 
context, Namespace ns) {
               paths.tables(ns),
               queryParams,
               ListTablesResponse.class,
-              headers(context),
+              ImmutableMap.of(),

Review Comment:
   It looks like we're not applying configured headers anymore? I don't think 
this was purely scoped to Auth headers.  Unless I'm missing it, we're not 
extracting environmental or property based headers.



##########
core/src/main/java/org/apache/iceberg/rest/RESTSessionCatalog.java:
##########
@@ -378,7 +289,8 @@ public List<TableIdentifier> listTables(SessionContext 
context, Namespace ns) {
               paths.tables(ns),
               queryParams,
               ListTablesResponse.class,
-              headers(context),
+              ImmutableMap.of(),
+              authManager.contextualSession(context, catalogAuth),

Review Comment:
   It feels like we're repeating this same pattern for all client calls now.  
Wouldn't we be able to wrap the client so that all we need is the context here?



##########
core/src/main/java/org/apache/iceberg/rest/RESTSessionCatalog.java:
##########
@@ -1009,26 +910,13 @@ private FileIO tableFileIO(SessionContext context, 
Map<String, String> config) {
     return newFileIO(context, fullConf);
   }
 
-  private AuthSession tableSession(Map<String, String> tableConf, AuthSession 
parent) {
-    Map<String, String> credentials = 
Maps.newHashMapWithExpectedSize(tableConf.size());
-    for (String prop : tableConf.keySet()) {
-      if (TABLE_SESSION_ALLOW_LIST.contains(prop)) {
-        credentials.put(prop, tableConf.get(prop));
-      }
-    }
-
-    Pair<String, Supplier<AuthSession>> newSession = newSession(credentials, 
tableConf, parent);
-    if (null == newSession) {
-      return parent;
-    }
-
-    AuthSession session = tableSessions.get(newSession.first(), id -> 
newSession.second().get());
-
-    return session != null ? session : parent;
+  private AuthSession tableSession(
+      TableIdentifier id, Map<String, String> tableConf, AuthSession parent) {
+    return authManager.tableSession(id, tableConf, parent);
   }
 
   private static ConfigResponse fetchConfig(
-      RESTClient client, Map<String, String> headers, Map<String, String> 
properties) {
+      RESTClient client, AuthSession initialAuth, Map<String, String> 
properties) {

Review Comment:
   I'm concerned that we're replacing headers with session.  There are headers 
independent of the auth session.



##########
core/src/main/java/org/apache/iceberg/rest/RESTSessionCatalog.java:
##########
@@ -1009,26 +910,13 @@ private FileIO tableFileIO(SessionContext context, 
Map<String, String> config) {
     return newFileIO(context, fullConf);
   }
 
-  private AuthSession tableSession(Map<String, String> tableConf, AuthSession 
parent) {
-    Map<String, String> credentials = 
Maps.newHashMapWithExpectedSize(tableConf.size());
-    for (String prop : tableConf.keySet()) {
-      if (TABLE_SESSION_ALLOW_LIST.contains(prop)) {
-        credentials.put(prop, tableConf.get(prop));
-      }
-    }
-
-    Pair<String, Supplier<AuthSession>> newSession = newSession(credentials, 
tableConf, parent);
-    if (null == newSession) {
-      return parent;
-    }
-
-    AuthSession session = tableSessions.get(newSession.first(), id -> 
newSession.second().get());
-
-    return session != null ? session : parent;
+  private AuthSession tableSession(

Review Comment:
   This methods doesn't seem to provide value since we're just making the exact 
call to the AuthManager



##########
core/src/main/java/org/apache/iceberg/rest/RESTSessionCatalog.java:
##########
@@ -237,29 +199,21 @@ public void initialize(String name, Map<String, String> 
unresolved) {
           ResourcePaths.tokens(),
           OAuth2Properties.OAUTH2_SERVER_URI);
     }
-    String oauth2ServerUri =
-        props.getOrDefault(OAuth2Properties.OAUTH2_SERVER_URI, 
ResourcePaths.tokens());
+
+    this.authManager = AuthManagers.loadAuthManager(props);

Review Comment:
   We should probably create the auth manager for the initial config load as a 
separate instance that we discard.



-- 
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: issues-unsubscr...@iceberg.apache.org

For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


---------------------------------------------------------------------
To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org
For additional commands, e-mail: issues-h...@iceberg.apache.org

Reply via email to