yifan-c commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2437293610


##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/acl/RoleBasedAuthorizationIntegrationTest.java:
##########
@@ -656,6 +667,110 @@ void testGrantingCdcFeaturePermission() throws Exception
                                                
HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
     }
 
+    @Test
+    void testAuthorizationCaching()
+    {
+        SidecarMetrics metrics = 
serverWrapper.injector.getInstance(SidecarMetrics.class);
+
+        CacheStats baseline = 
metrics.server().cache().authorizationCacheMetrics.snapshot();
+
+        String keyspaceSchemaRoute = 
String.format("/api/v1/keyspaces/%s/schema", "non_admin_test_keyspace");
+
+        verifyAccess(HttpMethod.GET, keyspaceSchemaRoute, 
nonAdminClientKeystorePath, assertStatus(HttpResponseStatus.OK));
+        verifyAccess(HttpMethod.GET, keyspaceSchemaRoute, 
nonAdminClientKeystorePath, assertStatus(HttpResponseStatus.OK));
+
+        // Verify cache stats, 1 hit 1 miss
+        CacheStats callStats = 
metrics.server().cache().authorizationCacheMetrics.snapshot();
+        assertThat(callStats.missCount()).isEqualTo(1);
+        assertThat(callStats.hitCount()).isEqualTo(1);
+    }
+
+    @Test
+    void testAuthorizationCachingWithPermissionRevocation()
+    {
+        SidecarMetrics metrics = 
serverWrapper.injector.getInstance(SidecarMetrics.class);
+
+        CacheStats baseline = 
metrics.server().cache().authorizationCacheMetrics.snapshot();
+
+        String keyspaceSchemaRoute = 
String.format("/api/v1/keyspaces/%s/schema", 
"non_admin_cache_revocation_test_keyspace");
+
+        verifyAccess(HttpMethod.GET, keyspaceSchemaRoute, 
nonAdminClientKeystorePath, assertStatus(HttpResponseStatus.OK));
+
+        CacheStats firstCallStats = 
metrics.server().cache().authorizationCacheMetrics.snapshot();
+        assertThat(firstCallStats.missCount()).isEqualTo(1);
+        assertThat(firstCallStats.hitCount()).isEqualTo(0);
+
+        verifyAccess(HttpMethod.GET, keyspaceSchemaRoute, 
nonAdminClientKeystorePath, assertStatus(HttpResponseStatus.OK));
+
+        CacheStats secondCallStats = 
metrics.server().cache().authorizationCacheMetrics.snapshot();
+        assertThat(secondCallStats.missCount()).isEqualTo(0);
+        assertThat(secondCallStats.hitCount()).isEqualTo(1);
+
+        // Revoke permission
+        Path clientKeystorePath = cassandraIdentityClientKeyStore();
+        SSLOptions sslOptions = getSSLOptions(clientKeystorePath.toString(),
+                                              
mtlsTestHelper.clientKeyStorePassword(),
+                                              mtlsTestHelper.trustStorePath(),
+                                              
mtlsTestHelper.trustStorePassword());
+        withAuthenticatedSession(cluster.get(1), "cassandra", "cassandra", 
session -> {
+            session.execute(String.format("DELETE FROM 
sidecar_internal.role_permissions_v1 " +
+                                          "WHERE role = '%s' AND resource = 
'data/%s'", "non_admin_test_role",
+                                          
"non_admin_cache_revocation_test_keyspace"));
+        }, sslOptions);
+
+        // Wait for cache to expire without accessing it
+        Uninterruptibles.sleepUninterruptibly(3, TimeUnit.SECONDS);

Review Comment:
   nit: avoid 3 seconds sleep if possible.



##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/acl/RoleBasedAuthorizationIntegrationTest.java:
##########
@@ -463,23 +470,24 @@ void testEndpointRequiringMultipleActions()
                                     
"data/multiple_permissions_required_test_keyspace/test_table",
                                     "SNAPSHOT:READ");
 
-            // wait for cache refresh
-            loopAssert(2, 100, () -> {
-                verifyAccess(HttpMethod.GET, listSnapshotRoute, 
nonAdminClientKeystorePath, response -> {
-                    assertThat(response).isNotNull();
-                    
assertThat(response.statusCode()).isEqualTo(HttpResponseStatus.OK.code());
-                    ListSnapshotFilesResponse snapshotFiles = 
response.bodyAsJson(ListSnapshotFilesResponse.class);
-                    List<ListSnapshotFilesResponse.FileInfo> filesToStream =
-                    snapshotFiles.snapshotFilesInfo()
-                                 .stream()
-                                 .filter(info -> 
info.fileName.endsWith("-Data.db"))
-                                 .sorted(Comparator.comparing(o -> o.fileName))
-                                 .collect(Collectors.toList());
-                    assertThat(filesToStream).isNotNull().isNotEmpty();
-                    componentDownloadUrl[0] = 
filesToStream.get(0).componentDownloadUrl();
-                });
+            // Wait for cache to expire without accessing it
+            Uninterruptibles.sleepUninterruptibly(3, TimeUnit.SECONDS);

Review Comment:
   nit: 3 seconds is long for unit test. How about explicitly invalidate the 
cache? I do not think cache eviction is the behavior you want to test in this 
test case. Invalidating the cache explicitly is deterministic and avoids 
potential flakiness. 



##########
server/src/main/java/org/apache/cassandra/bridge/CassandraBridgeFactory.java:
##########
@@ -133,8 +133,8 @@ public ClassLoader buildClassLoader(String... resourceNames)
                                }
                            }).toArray(URL[]::new);
 
-        return AccessController.doPrivileged((PrivilegedAction<ClassLoader>) 
() ->
-                                                                             
new PostDelegationClassLoader(urls, 
Thread.currentThread().getContextClassLoader()));
+        return AccessController.doPrivileged(
+        (PrivilegedAction<ClassLoader>) () -> new 
PostDelegationClassLoader(urls, 
Thread.currentThread().getContextClassLoader()));

Review Comment:
   Is it just reformatting? If so, please revert to preserve the git history. 



##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CachedAuthorizationHandler.java:
##########
@@ -0,0 +1,157 @@
+/*
+ * 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.cassandra.sidecar.acl.authorization;
+
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.function.BiConsumer;
+
+import com.github.benmanes.caffeine.cache.Cache;
+import com.github.benmanes.caffeine.cache.Caffeine;
+import io.vertx.ext.auth.User;
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.auth.authorization.AuthorizationContext;
+import io.vertx.ext.web.RoutingContext;
+import io.vertx.ext.web.handler.AuthorizationHandler;
+import io.vertx.ext.web.handler.HttpException;
+import io.vertx.ext.web.handler.impl.AuthorizationHandlerImpl;
+import org.apache.cassandra.sidecar.acl.AdminIdentityResolver;
+import org.apache.cassandra.sidecar.config.AccessControlConfiguration;
+import org.apache.cassandra.sidecar.config.CacheConfiguration;
+import org.apache.cassandra.sidecar.exceptions.ConfigurationException;
+import org.apache.cassandra.sidecar.metrics.CacheStatsCounter;
+import org.apache.cassandra.sidecar.metrics.SidecarMetrics;
+import org.apache.cassandra.sidecar.metrics.server.AuthMetrics;
+
+import static org.apache.cassandra.sidecar.utils.AuthUtils.extractIdentities;
+
+/**
+ * {@link CachedAuthorizationHandler} caches all authorization requests using 
{@link AuthorizationCacheKey}.
+ */
+public class CachedAuthorizationHandler extends AuthorizationHandlerImpl
+{
+    private static final HttpException FORBIDDEN_EXCEPTION = new 
HttpException(403);
+    private final AccessControlConfiguration accessControlConfiguration;
+    private final AuthorizationParameterValidateHandler 
authZParameterValidateHandler;
+    private final AdminIdentityResolver adminIdentityResolver;
+    private final AuthMetrics authMetrics;
+    private final CacheStatsCounter cacheMetrics;
+    private final Cache<AuthorizationCacheKey, Boolean> authorizationCache;
+    // This is overridden since Vert.x does not expose this
+    private BiConsumer<RoutingContext, AuthorizationContext> variableHandler;
+
+    public CachedAuthorizationHandler(AccessControlConfiguration 
accessControlConfiguration,
+                                      AuthorizationParameterValidateHandler 
authZParameterValidateHandler,
+                                      AdminIdentityResolver 
adminIdentityResolver,
+                                      Authorization authorization,
+                                      SidecarMetrics sidecarMetrics)
+    {
+        super(authorization);
+        this.accessControlConfiguration = accessControlConfiguration;
+        this.authZParameterValidateHandler = authZParameterValidateHandler;
+        this.adminIdentityResolver = adminIdentityResolver;
+        this.authMetrics = sidecarMetrics.server().auth();
+        this.cacheMetrics = 
sidecarMetrics.server().cache().authorizationCacheMetrics;
+        this.authorizationCache = initCache();
+    }
+
+    @Override
+    public void handle(RoutingContext ctx)
+    {
+        long startTimeNanos = System.nanoTime();
+        authZParameterValidateHandler.handle(ctx);
+        if (ctx.failed()) // failed due to validation
+        {
+            return;
+        }
+
+        User user = ctx.user();
+        AuthorizationContext authorizationContext = 
AuthorizationContext.create(user);
+        if (this.variableHandler != null)
+        {
+            this.variableHandler.accept(ctx, authorizationContext);
+        }
+
+        AtomicBoolean ctxNextCalled = new AtomicBoolean(false);
+
+        AuthorizationCacheKey key = 
AuthorizationCacheKey.create(authorizationContext);
+        Boolean authorized = authorizationCache.get(key, k -> {
+            List<String> identities = extractIdentities(user);
+
+            // Admin identities bypass route specific authorization checks
+            if (!identities.isEmpty() && 
identities.stream().anyMatch(adminIdentityResolver::isAdmin))
+            {
+                return true;
+            }
+
+            super.handle(ctx);
+            if (!ctx.failed())
+            {
+                ctxNextCalled.set(true);
+                long durationNanos = System.nanoTime() - startTimeNanos;
+                authMetrics.authorizationTime.metric.update(durationNanos, 
TimeUnit.NANOSECONDS);
+                return true;
+            }
+            return false;
+        });
+
+        // We avoid calling ctx.next() and ctx.fail() when it is already done 
during cache value computation
+        if (Boolean.TRUE.equals(authorized))
+        {
+            if (!ctxNextCalled.get())
+            {
+                ctx.next();
+            }
+        }
+        else
+        {
+            if (!ctx.failed())
+            {
+                ctx.fail(403, FORBIDDEN_EXCEPTION);
+            }
+        }
+    }
+
+    private <K, V> Cache<K, V> initCache()
+    {
+        CacheConfiguration permissionCacheConfig = 
accessControlConfiguration.permissionCacheConfiguration();
+        if (permissionCacheConfig.expireAfterAccess() == null)
+        {
+            throw new ConfigurationException("Authorization handler cache must 
be configured with expireAfterAccess");
+        }
+        Caffeine<Object, Object> cacheBuilder = Caffeine.newBuilder()
+                                                        
.maximumSize(permissionCacheConfig.maximumSize())
+                                                        .recordStats(() -> 
cacheMetrics);
+        if (permissionCacheConfig.expireAfterAccess() != null)

Review Comment:
   null is already checked for `expireAfterAccess` at line 135. Do you mean 
`refreshAfterWrite()`? or is it just redundant? 



##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationCacheKeyImpl.java:
##########
@@ -0,0 +1,113 @@
+/*
+ * 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.cassandra.sidecar.acl.authorization;
+
+import java.util.List;
+import java.util.Objects;
+
+import io.vertx.core.MultiMap;
+import io.vertx.ext.auth.User;
+
+import static 
org.apache.cassandra.sidecar.utils.AuthUtils.extractCassandraRoles;
+
+/**
+ * Implementation of {@link AuthorizationCacheKey}, uniquely represents an 
authorization request with user and resource
+ * context.
+ */
+public class AuthorizationCacheKeyImpl implements AuthorizationCacheKey
+{
+    private final List<String> roles;
+    private final MultiMap variables;
+
+    public AuthorizationCacheKeyImpl(User user, MultiMap variables)
+    {
+        this.roles = extractCassandraRoles(user);
+        // Store a copy, otherwise Cache is not able to identity 2 keys with 
same values in MultiMap as same.

Review Comment:
   guess `identify` is what you want.
   ```suggestion
           // Store a copy, otherwise Cache is not able to identify 2 keys with 
same values in MultiMap as same.
   ```



##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/acl/RoleBasedAuthorizationIntegrationTest.java:
##########
@@ -488,19 +496,22 @@ void testEndpointRequiringMultipleActions()
 
             // STREAM SSTable request requires both Sidecar SNAPSHOT:STREAM 
permission and Cassandra's SELECT
             // permission on a table it accesses data.
-            loopAssert(2, 100, () -> {
-                // request denied without SELECT permission
-                verifyAccess(HttpMethod.GET, componentDownloadUrl[0], 
nonAdminClientKeystorePath, assertStatus(HttpResponseStatus.FORBIDDEN));
-            });
+
+            // Wait for cache to expire without accessing it
+            Uninterruptibles.sleepUninterruptibly(3, TimeUnit.SECONDS);

Review Comment:
   nit: avoid 3 seconds sleep if possible. 



##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationCacheKeyImpl.java:
##########
@@ -0,0 +1,113 @@
+/*
+ * 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.cassandra.sidecar.acl.authorization;
+
+import java.util.List;
+import java.util.Objects;
+
+import io.vertx.core.MultiMap;
+import io.vertx.ext.auth.User;
+
+import static 
org.apache.cassandra.sidecar.utils.AuthUtils.extractCassandraRoles;
+
+/**
+ * Implementation of {@link AuthorizationCacheKey}, uniquely represents an 
authorization request with user and resource
+ * context.
+ */
+public class AuthorizationCacheKeyImpl implements AuthorizationCacheKey
+{
+    private final List<String> roles;
+    private final MultiMap variables;
+
+    public AuthorizationCacheKeyImpl(User user, MultiMap variables)
+    {
+        this.roles = extractCassandraRoles(user);
+        // Store a copy, otherwise Cache is not able to identity 2 keys with 
same values in MultiMap as same.
+        // If MultiMap is modifiable the equality behaviour changes.
+        this.variables = MultiMap.caseInsensitiveMultiMap();
+        if (variables != null)
+        {
+            variables.forEach(entry -> this.variables.add(entry.getKey(), 
entry.getValue()));
+        }
+    }
+
+    @Override
+    public boolean equals(Object o)
+    {
+        if (this == o)
+        {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass())
+        {
+            return false;
+        }
+        AuthorizationCacheKeyImpl that = (AuthorizationCacheKeyImpl) o;
+        return roles.equals(that.roles) && variablesEqual(variables, 
that.variables);
+    }
+
+    private boolean variablesEqual(MultiMap map1, MultiMap map2)
+    {
+        if (map1 == map2)
+        {
+            return true;
+        }
+        if (map1 == null || map2 == null)
+        {
+            return false;
+        }
+        if (map1.size() != map2.size())
+        {
+            return false;
+        }
+        if (!map1.names().equals(map2.names()))
+        {
+            return false;
+        }
+
+        for (String name : map1.names())
+        {
+            if (!map1.getAll(name).equals(map2.getAll(name)))
+            {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public int hashCode()
+    {
+        return Objects.hash(roles, variablesHashCode(variables));
+    }
+
+    private int variablesHashCode(MultiMap variables)
+    {
+        if (variables == null)
+        {
+            return 0;
+        }
+        int hash = 0;
+        for (String name : variables.names())
+        {
+            hash += Objects.hash(name, variables.getAll(name));

Review Comment:
   Using addition for hashcode seems to be alerting. It will allow collisions 
more easily. Can you multiply by a prime? for example
   
   ```java
   hash = hash * 31 + Objects.hash(name, variables.getAll(name))
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationCacheKeyImpl.java:
##########
@@ -0,0 +1,113 @@
+/*
+ * 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.cassandra.sidecar.acl.authorization;
+
+import java.util.List;
+import java.util.Objects;
+
+import io.vertx.core.MultiMap;
+import io.vertx.ext.auth.User;
+
+import static 
org.apache.cassandra.sidecar.utils.AuthUtils.extractCassandraRoles;
+
+/**
+ * Implementation of {@link AuthorizationCacheKey}, uniquely represents an 
authorization request with user and resource
+ * context.
+ */
+public class AuthorizationCacheKeyImpl implements AuthorizationCacheKey
+{
+    private final List<String> roles;
+    private final MultiMap variables;
+
+    public AuthorizationCacheKeyImpl(User user, MultiMap variables)
+    {
+        this.roles = extractCassandraRoles(user);
+        // Store a copy, otherwise Cache is not able to identity 2 keys with 
same values in MultiMap as same.
+        // If MultiMap is modifiable the equality behaviour changes.
+        this.variables = MultiMap.caseInsensitiveMultiMap();
+        if (variables != null)
+        {
+            variables.forEach(entry -> this.variables.add(entry.getKey(), 
entry.getValue()));
+        }
+    }
+
+    @Override
+    public boolean equals(Object o)
+    {
+        if (this == o)
+        {
+            return true;
+        }
+        if (o == null || getClass() != o.getClass())
+        {
+            return false;
+        }
+        AuthorizationCacheKeyImpl that = (AuthorizationCacheKeyImpl) o;
+        return roles.equals(that.roles) && variablesEqual(variables, 
that.variables);
+    }
+
+    private boolean variablesEqual(MultiMap map1, MultiMap map2)
+    {
+        if (map1 == map2)
+        {
+            return true;
+        }
+        if (map1 == null || map2 == null)
+        {
+            return false;
+        }
+        if (map1.size() != map2.size())
+        {
+            return false;
+        }
+        if (!map1.names().equals(map2.names()))
+        {
+            return false;
+        }
+
+        for (String name : map1.names())
+        {
+            if (!map1.getAll(name).equals(map2.getAll(name)))
+            {
+                return false;
+            }
+        }
+        return true;
+    }
+
+    @Override
+    public int hashCode()
+    {
+        return Objects.hash(roles, variablesHashCode(variables));
+    }

Review Comment:
   The hashcode calculation is expensive. Can you pre-calculate the hashcode? 
   Also, a big question, is the `variables` immutable? If it is mutable, it 
cannot be used as key. 



##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/acl/RoleBasedAuthorizationIntegrationTest.java:
##########
@@ -488,19 +496,22 @@ void testEndpointRequiringMultipleActions()
 
             // STREAM SSTable request requires both Sidecar SNAPSHOT:STREAM 
permission and Cassandra's SELECT
             // permission on a table it accesses data.
-            loopAssert(2, 100, () -> {
-                // request denied without SELECT permission
-                verifyAccess(HttpMethod.GET, componentDownloadUrl[0], 
nonAdminClientKeystorePath, assertStatus(HttpResponseStatus.FORBIDDEN));
-            });
+
+            // Wait for cache to expire without accessing it
+            Uninterruptibles.sleepUninterruptibly(3, TimeUnit.SECONDS);
+
+            // request denied without SELECT permission
+            verifyAccess(HttpMethod.GET, componentDownloadUrl[0], 
nonAdminClientKeystorePath, assertStatus(HttpResponseStatus.FORBIDDEN));
 
             // grant SELECT permission to non_admin_test_role
             grantTablePermission(session, 
"multiple_permissions_required_test_keyspace", "test_table", 
"non_admin_test_role");
         }, sslOptions);
 
-        loopAssert(2, 100, () -> {
-            // request denied without SELECT permission
-            verifyAccess(HttpMethod.GET, componentDownloadUrl[0], 
nonAdminClientKeystorePath, assertStatus(HttpResponseStatus.OK));
-        });
+        // Wait for cache to expire without accessing it
+        Uninterruptibles.sleepUninterruptibly(3, TimeUnit.SECONDS);

Review Comment:
   nit: avoid 3 seconds sleep if possible.



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