sarankk commented on code in PR #276:
URL: https://github.com/apache/cassandra-sidecar/pull/276#discussion_r2512371880


##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/BasicPermissions.java:
##########
@@ -39,6 +39,9 @@
  */
 public class BasicPermissions
 {
+    // Auth cache related permissions
+    public static final Permission AUTH_CACHE = new 
StandardPermission("AUTH_CACHE", CLUSTER_SCOPE);

Review Comment:
   Permissions are represented in format `resource:action`, I would suggest a 
`DomainAwarePermission` here with `CACHE:INVALIDATE`. We can reuse this 
permission for other caches too. 



##########
server/src/main/java/org/apache/cassandra/sidecar/modules/AuthModule.java:
##########
@@ -157,6 +163,23 @@ VertxRoute chainAuthHandler(Vertx vertx,
                                                  .handler(chainAuthHandler));
     }
 
+    @DELETE
+    @Path(ApiEndpointsV1.INVALIDATE_CACHE_ROUTE)
+    @Operation(summary = "Invalidate authentication or authorization cache",

Review Comment:
   We can use this endpoint for invalidating all caches, can you update summary 
to be generic?



##########
client-common/src/main/java/org/apache/cassandra/sidecar/common/ApiEndpointsV1.java:
##########
@@ -116,6 +116,10 @@ public final class ApiEndpointsV1
     public static final String ABORT_RESTORE_JOB_ROUTE = RESTORE_JOB_ROUTE + 
ABORT;
     public static final String RESTORE_JOB_PROGRESS_ROUTE = RESTORE_JOB_ROUTE 
+ PROGRESS;
 
+    // Auth related APIs
+    public static final String CACHE_NAME_PARAM = ":cacheName";
+    public static final String INVALIDATE_CACHE_ROUTE = API_V1 + "/caches/" + 
CACHE_NAME_PARAM + "/invalidate";

Review Comment:
   We should be able to invalidate with a specific key too. For e.g. If we want 
to invalidate a single identity in `identity_to_role_cache` 



##########
server/src/main/java/org/apache/cassandra/sidecar/acl/AuthCache.java:
##########
@@ -138,6 +138,18 @@ public void invalidate(K k)
         }
     }
 
+    /**
+     * Invalidate all entries in this cache
+     */
+    public void invalidateAll()
+    {
+        if (cache != null)
+        {
+            cache.invalidateAll();

Review Comment:
   In Cassandra, we init the cache again instead of `invalidateAll` 
https://github.com/apache/cassandra/blob/9a534ba06f14729c08eb55b90878ef32d5423782/src/java/org/apache/cassandra/auth/AuthCache.java#L245.
 



##########
server/src/test/java/org/apache/cassandra/sidecar/handlers/InvalidateCacheHandlerTest.java:
##########
@@ -0,0 +1,336 @@
+/*
+ * 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.handlers;
+
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.github.benmanes.caffeine.cache.AsyncCache;
+import com.github.benmanes.caffeine.cache.Cache;
+import com.google.inject.AbstractModule;
+import com.google.inject.Guice;
+import com.google.inject.Injector;
+import com.google.inject.Module;
+import com.google.inject.Provides;
+import com.google.inject.Singleton;
+import com.google.inject.util.Modules;
+import io.vertx.core.Vertx;
+import io.vertx.ext.web.client.WebClient;
+import io.vertx.ext.web.client.predicate.ResponsePredicate;
+import io.vertx.junit5.VertxExtension;
+import io.vertx.junit5.VertxTestContext;
+import org.apache.cassandra.sidecar.TestModule;
+import org.apache.cassandra.sidecar.acl.IdentityToRoleCache;
+import org.apache.cassandra.sidecar.acl.authorization.AuthorizationCacheKey;
+import org.apache.cassandra.sidecar.acl.authorization.RoleAuthorizationsCache;
+import org.apache.cassandra.sidecar.acl.authorization.SuperUserCache;
+import org.apache.cassandra.sidecar.modules.SidecarModules;
+import org.apache.cassandra.sidecar.server.Server;
+import org.apache.cassandra.sidecar.utils.CacheFactory;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.NOT_FOUND;
+import static io.netty.handler.codec.http.HttpResponseStatus.OK;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.verifyNoInteractions;
+import static org.mockito.Mockito.when;
+
+/**
+ * Tests for the {@link InvalidateCacheHandler}
+ */
+@ExtendWith(VertxExtension.class)
+public class InvalidateCacheHandlerTest
+{
+    static final Logger LOGGER = 
LoggerFactory.getLogger(InvalidateCacheHandlerTest.class);
+    static final String TEST_ROUTE_TEMPLATE = "/api/v1/caches/%s/invalidate";
+
+    Vertx vertx;
+    Server server;
+    IdentityToRoleCache mockIdentityToRoleCache = 
mock(IdentityToRoleCache.class);
+    RoleAuthorizationsCache mockRoleAuthorizationsCache = 
mock(RoleAuthorizationsCache.class);
+    SuperUserCache mockSuperUserCache = mock(SuperUserCache.class);
+    AsyncCache<AuthorizationCacheKey, Boolean> mockEndpointAuthorizationCache 
= mock(AsyncCache.class);
+    Cache<AuthorizationCacheKey, Boolean> mockSyncCache = mock(Cache.class);
+
+    @BeforeEach
+    void before() throws InterruptedException
+    {
+        // Stub the AsyncCache.synchronous() to return the sync cache mock
+        
when(mockEndpointAuthorizationCache.synchronous()).thenReturn(mockSyncCache);
+
+        Injector injector;
+        Module testOverride = Modules.override(new TestModule())
+                                     .with(new InvalidateCacheTestModule());
+        injector = Guice.createInjector(Modules.override(SidecarModules.all())
+                                               .with(testOverride));
+        vertx = injector.getInstance(Vertx.class);
+        server = injector.getInstance(Server.class);
+        VertxTestContext context = new VertxTestContext();
+        server.start()
+              .onSuccess(s -> context.completeNow())
+              .onFailure(context::failNow);
+        context.awaitCompletion(5, TimeUnit.SECONDS);
+    }
+
+    @AfterEach
+    void after() throws InterruptedException
+    {
+        CountDownLatch closeLatch = new CountDownLatch(1);
+        server.close().onSuccess(res -> closeLatch.countDown());
+        if (closeLatch.await(60, TimeUnit.SECONDS))
+            LOGGER.info("Close event received before timeout.");
+        else
+            LOGGER.error("Close event timed out.");
+    }
+
+    @Test
+    void testInvalidateIdentityToRoleCache(VertxTestContext context)
+    {
+        String testRoute = String.format(TEST_ROUTE_TEMPLATE, 
"identity_to_role_cache");
+
+        WebClient client = WebClient.create(vertx);
+        client.delete(server.actualPort(), "127.0.0.1", testRoute)
+              .expect(ResponsePredicate.SC_OK)
+              .send(context.succeeding(response -> {
+                  assertThat(response.statusCode()).isEqualTo(OK.code());
+                  
assertThat(response.bodyAsJsonObject().getString("status")).isEqualTo("OK");
+
+                  // Verify the correct cache was invalidated
+                  verify(mockIdentityToRoleCache).invalidateAll();
+                  verifyNoInteractions(mockRoleAuthorizationsCache);
+                  verifyNoInteractions(mockSuperUserCache);
+
+                  context.completeNow();
+              }));
+    }
+
+    @Test
+    void testInvalidateIdentityToRoleCacheAlternativeName(VertxTestContext 
context)
+    {
+        String testRoute = String.format(TEST_ROUTE_TEMPLATE, 
"IdentityToRoleCache");
+
+        WebClient client = WebClient.create(vertx);
+        client.delete(server.actualPort(), "127.0.0.1", testRoute)
+              .expect(ResponsePredicate.SC_OK)
+              .send(context.succeeding(response -> {
+                  assertThat(response.statusCode()).isEqualTo(OK.code());
+                  
assertThat(response.bodyAsJsonObject().getString("status")).isEqualTo("OK");
+
+                  // Verify case-insensitive matching works
+                  verify(mockIdentityToRoleCache).invalidateAll();
+                  verifyNoInteractions(mockRoleAuthorizationsCache);
+                  verifyNoInteractions(mockSuperUserCache);
+
+                  context.completeNow();
+              }));
+    }
+
+    @Test
+    void testInvalidateRoleAuthorizationsCache(VertxTestContext context)
+    {
+        String testRoute = String.format(TEST_ROUTE_TEMPLATE, 
"role_permissions_cache");
+
+        WebClient client = WebClient.create(vertx);
+        client.delete(server.actualPort(), "127.0.0.1", testRoute)
+              .expect(ResponsePredicate.SC_OK)
+              .send(context.succeeding(response -> {
+                  assertThat(response.statusCode()).isEqualTo(OK.code());
+                  
assertThat(response.bodyAsJsonObject().getString("status")).isEqualTo("OK");
+
+                  // Verify the correct cache was invalidated
+                  verify(mockRoleAuthorizationsCache).invalidateAll();
+                  verifyNoInteractions(mockIdentityToRoleCache);
+                  verifyNoInteractions(mockSuperUserCache);
+
+                  context.completeNow();
+              }));
+    }
+
+    @Test
+    void testInvalidateRoleAuthorizationsCacheAlternativeName(VertxTestContext 
context)
+    {
+        String testRoute = String.format(TEST_ROUTE_TEMPLATE, 
"RoleAuthorizationsCache");
+
+        WebClient client = WebClient.create(vertx);

Review Comment:
   Nit: to avoid redundancy, can we pull out the test code and run test with 
parameters like testRoute, mocks to test for



##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/routes/InvalidateCacheIntegrationTest.java:
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.routes;
+
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+
+import org.junit.jupiter.api.Test;
+
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.github.benmanes.caffeine.cache.AsyncCache;
+import com.google.inject.AbstractModule;
+import com.google.inject.Provides;
+import com.google.inject.Singleton;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.buffer.Buffer;
+import io.vertx.core.http.HttpMethod;
+import io.vertx.ext.web.client.HttpResponse;
+import io.vertx.ext.web.client.WebClient;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.sidecar.acl.IdentityToRoleCache;
+import org.apache.cassandra.sidecar.acl.authorization.AuthorizationCacheKey;
+import org.apache.cassandra.sidecar.acl.authorization.RoleAuthorizationsCache;
+import org.apache.cassandra.sidecar.acl.authorization.SuperUserCache;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import 
org.apache.cassandra.sidecar.common.server.utils.MillisecondBoundConfiguration;
+import 
org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration;
+import org.apache.cassandra.sidecar.config.AccessControlConfiguration;
+import org.apache.cassandra.sidecar.config.CacheConfiguration;
+import org.apache.cassandra.sidecar.config.KeyStoreConfiguration;
+import org.apache.cassandra.sidecar.config.ParameterizedClassConfiguration;
+import org.apache.cassandra.sidecar.config.yaml.AccessControlConfigurationImpl;
+import org.apache.cassandra.sidecar.config.yaml.CacheConfigurationImpl;
+import org.apache.cassandra.sidecar.config.yaml.KeyStoreConfigurationImpl;
+import 
org.apache.cassandra.sidecar.config.yaml.ParameterizedClassConfigurationImpl;
+import org.apache.cassandra.sidecar.config.yaml.SidecarConfigurationImpl;
+import org.apache.cassandra.sidecar.config.yaml.SslConfigurationImpl;
+import org.apache.cassandra.sidecar.testing.MtlsTestHelper;
+import 
org.apache.cassandra.sidecar.testing.SharedClusterSidecarIntegrationTestBase;
+import org.apache.cassandra.sidecar.testing.TemporaryCqlSessionProvider;
+import org.apache.cassandra.sidecar.utils.CacheFactory;
+import org.apache.cassandra.sidecar.utils.SimpleCassandraVersion;
+import org.apache.cassandra.testing.ClusterBuilderConfiguration;
+
+import static org.apache.cassandra.testing.DriverTestUtils.buildContactPoints;
+import static org.apache.cassandra.testing.TestUtils.DC1_RF1;
+import static org.apache.cassandra.testing.TlsTestUtils.getSSLOptions;
+import static 
org.apache.cassandra.testing.TlsTestUtils.withAuthenticatedSession;
+import static org.apache.cassandra.testing.utils.AssertionUtils.getBlocking;
+import static org.apache.cassandra.testing.utils.AssertionUtils.loopAssert;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assumptions.assumeThat;
+
+/**
+ * Integration test for cache invalidation endpoints
+ */
+class InvalidateCacheIntegrationTest extends 
SharedClusterSidecarIntegrationTestBase
+{
+    protected static final int MIN_VERSION_WITH_MTLS = 5;
+    private static final String CASSANDRA_IDENTITY = 
"spiffe://cassandra/sidecar/cassandra_role";
+    private static final String SIDECAR_ROLE_IDENTITY = 
"spiffe://cassandra/sidecar/sidecar_role";
+    private static final String TEST_USER_IDENTITY = 
"spiffe://cassandra/sidecar/test_user";
+    private static final String TEST_SUPERUSER_IDENTITY = 
"spiffe://cassandra/sidecar/test_superuser";
+    private static final String SCHEMA_ROUTE = "/api/v1/cassandra/schema";
+
+    private Path testUserKeystorePath;
+    private Path superuserKeystorePath;
+
+    @Override
+    protected void beforeClusterProvisioning()
+    {
+        // mTLS authentication was added in Cassandra starting 5.0 version
+        assumeThat(SimpleCassandraVersion.create(testVersion.version()).major)
+        .as("mTLS authentication is not supported in 4.0 and 4.1 Cassandra 
versions")
+        .isGreaterThanOrEqualTo(MIN_VERSION_WITH_MTLS);
+    }
+
+    @Override
+    protected ClusterBuilderConfiguration testClusterConfiguration()
+    {
+        return super.testClusterConfiguration()
+                    .additionalInstanceConfig(Map.of("authenticator", 
"org.apache.cassandra.auth.PasswordAuthenticator"));
+    }
+
+    @Override
+    protected void afterClusterProvisioned()
+    {
+        IInstance instance = cluster.getFirstRunningInstance();
+        configureAdminAndSidecarIdentity(instance);
+
+        cluster.stopUnchecked(instance);
+
+        var instanceConfig = instance.config();
+        instanceConfig.set("authenticator.class_name", 
"org.apache.cassandra.auth.MutualTlsAuthenticator");
+        instanceConfig.set("authenticator.parameters", 
Map.of("validator_class_name",
+                                                              
"org.apache.cassandra.auth.SpiffeCertificateValidator"));
+        instanceConfig.set("role_manager", "CassandraRoleManager");
+        instanceConfig.set("authorizer", "CassandraAuthorizer");
+        instanceConfig.set("client_encryption_options.enabled", "true");
+        instanceConfig.set("client_encryption_options.optional", "true");
+        instanceConfig.set("client_encryption_options.require_client_auth", 
"true");
+        
instanceConfig.set("client_encryption_options.require_endpoint_verification", 
"false");
+        instanceConfig.set("client_encryption_options.keystore", 
mtlsTestHelper.serverKeyStorePath());
+        instanceConfig.set("client_encryption_options.keystore_password", 
mtlsTestHelper.serverKeyStorePassword());
+        instanceConfig.set("client_encryption_options.truststore", 
mtlsTestHelper.trustStorePath());
+        instanceConfig.set("client_encryption_options.truststore_password", 
mtlsTestHelper.trustStorePassword());
+        instanceConfig.set("credentials_update_interval", "50ms");
+
+        instance.startup();
+    }
+
+    @Override
+    protected Function<SidecarConfigurationImpl.Builder, 
SidecarConfigurationImpl.Builder> configurationOverrides()
+    {
+        return builder -> {
+            Map<String, String> params = Map.of("certificate_validator", 
"io.vertx.ext.auth.mtls.impl.CertificateValidatorImpl",
+                                                
"certificate_identity_extractor", 
"org.apache.cassandra.sidecar.acl.authentication.CassandraIdentityExtractor");
+            ParameterizedClassConfiguration mTLSConfig
+            = new 
ParameterizedClassConfigurationImpl("org.apache.cassandra.sidecar.acl.authentication.MutualTlsAuthenticationHandlerFactory",
+                                                      params);
+            ParameterizedClassConfiguration rbacConfig
+            = new 
ParameterizedClassConfigurationImpl("org.apache.cassandra.sidecar.acl.authorization.RoleBasedAuthorizationProvider",
+                                                      Map.of());
+
+            CacheConfiguration permissionCacheConfiguration = 
CacheConfigurationImpl.builder()
+                                                                               
     .expireAfterAccess(MillisecondBoundConfiguration.parse("5s"))
+                                                                               
     .build();
+
+            AccessControlConfiguration accessControlConfiguration = 
AccessControlConfigurationImpl.builder()
+                                                                               
                   .enabled(true)
+                                                                               
                   .authenticatorsConfiguration(List.of(mTLSConfig))
+                                                                               
                   .authorizerConfiguration(rbacConfig)
+                                                                               
                   .permissionCacheConfiguration(permissionCacheConfiguration)
+                                                                               
                   .build();
+
+            KeyStoreConfiguration truststoreConfiguration = new 
KeyStoreConfigurationImpl(mtlsTestHelper.trustStorePath(),
+                                                                               
           mtlsTestHelper.trustStorePassword(),
+                                                                               
           mtlsTestHelper.trustStoreType(),
+                                                                               
           SecondBoundConfiguration.parse("1d"));
+
+            KeyStoreConfiguration keyStoreConfiguration = new 
KeyStoreConfigurationImpl(mtlsTestHelper.serverKeyStorePath(),
+                                                                               
         mtlsTestHelper.serverKeyStorePassword(),
+                                                                               
         mtlsTestHelper.serverKeyStoreType(),
+                                                                               
         SecondBoundConfiguration.parse("1d"));
+
+            SslConfigurationImpl sslConfiguration = 
SslConfigurationImpl.builder()
+                                                                        
.enabled(true)
+                                                                        
.clientAuth("REQUEST")
+                                                                        
.keystore(keyStoreConfiguration)
+                                                                        
.truststore(truststoreConfiguration)
+                                                                        
.build();
+
+            return 
builder.accessControlConfiguration(accessControlConfiguration)
+                          .sslConfiguration(sslConfiguration);
+        };
+    }
+
+    @Override
+    protected void startSidecar(ICluster<? extends IInstance> cluster) throws 
InterruptedException
+    {
+        serverWrapper = startSidecarWithInstances(cluster, new 
TestModule(mtlsTestHelper, cluster));
+    }
+
+    @Override
+    protected void beforeTestStart()
+    {
+        waitForSchemaReady(10, TimeUnit.SECONDS);
+        try
+        {
+            testUserKeystorePath = 
mtlsTestHelper.issueClientKeyStore(certificateBuilder ->
+                                                                      
certificateBuilder.addSanUriName(TEST_USER_IDENTITY));
+            superuserKeystorePath = 
mtlsTestHelper.issueClientKeyStore(certificateBuilder ->
+                                                                       
certificateBuilder.addSanUriName(TEST_SUPERUSER_IDENTITY));
+        }
+        catch (Exception e)
+        {
+            throw new RuntimeException("Failed to create test keystores", e);
+        }
+    }
+
+    @Override
+    protected void initializeSchemaForTest()
+    {
+        Path clientKeystorePath = cassandraIdentityClientKeyStore();
+
+        SSLOptions sslOptions = getSSLOptions(clientKeystorePath.toString(),
+                                              
mtlsTestHelper.clientKeyStorePassword(),
+                                              mtlsTestHelper.trustStorePath(),
+                                              
mtlsTestHelper.trustStorePassword());
+        withAuthenticatedSession(cluster.get(1), "cassandra", "cassandra", 
session -> {
+            createTestKeyspace(session, "sidecar_internal", DC1_RF1);
+            createRolesPermissionsTable(session);
+            createTestRole(session);
+        }, sslOptions);
+    }
+
+    @Test
+    void testInvalidateIdentityToRoleCache()
+    {
+        IdentityToRoleCache identityToRoleCache = 
serverWrapper.injector.getInstance(IdentityToRoleCache.class);
+
+        // Populate the cache by making a request with test user identity
+        verifyAccess(HttpMethod.GET, SCHEMA_ROUTE, testUserKeystorePath, 
assertStatus(HttpResponseStatus.OK));
+
+        // Verify cache has entries using loopAssert as cache operation is 
asynchronous
+        loopAssert(3, () ->
+            assertThat(identityToRoleCache.getAll()).isNotEmpty());
+
+        // Invalidate the cache using superuser
+        String invalidateCacheRoute = 
"/api/v1/caches/identity_to_role_cache/invalidate";
+        verifyAccess(HttpMethod.DELETE, invalidateCacheRoute, 
superuserKeystorePath, assertStatus(HttpResponseStatus.OK));
+
+        // Verify cache is empty after invalidation using loopAssert as cache 
operation is asynchronous
+        loopAssert(3, () ->
+            assertThat(identityToRoleCache.getAll()).isEmpty());
+    }
+
+    @Test
+    void testInvalidateRoleAuthorizationsCache()
+    {
+        RoleAuthorizationsCache roleAuthorizationsCache = 
serverWrapper.injector.getInstance(RoleAuthorizationsCache.class);
+
+        // Populate the cache by making a request with test user identity
+        verifyAccess(HttpMethod.GET, SCHEMA_ROUTE, testUserKeystorePath, 
assertStatus(HttpResponseStatus.OK));

Review Comment:
   Nit: to avoid redundancy, shall we put out common code into a `runTest` or 
similar method?



##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/routes/InvalidateCacheIntegrationTest.java:
##########
@@ -0,0 +1,453 @@
+/*
+ * 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.routes;
+
+import java.nio.file.Path;
+import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
+import java.util.function.Function;
+
+import org.junit.jupiter.api.Test;
+
+import com.datastax.driver.core.SSLOptions;
+import com.datastax.driver.core.Session;
+import com.github.benmanes.caffeine.cache.AsyncCache;
+import com.google.inject.AbstractModule;
+import com.google.inject.Provides;
+import com.google.inject.Singleton;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.buffer.Buffer;
+import io.vertx.core.http.HttpMethod;
+import io.vertx.ext.web.client.HttpResponse;
+import io.vertx.ext.web.client.WebClient;
+import org.apache.cassandra.distributed.api.ICluster;
+import org.apache.cassandra.distributed.api.IInstance;
+import org.apache.cassandra.sidecar.acl.IdentityToRoleCache;
+import org.apache.cassandra.sidecar.acl.authorization.AuthorizationCacheKey;
+import org.apache.cassandra.sidecar.acl.authorization.RoleAuthorizationsCache;
+import org.apache.cassandra.sidecar.acl.authorization.SuperUserCache;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import 
org.apache.cassandra.sidecar.common.server.utils.MillisecondBoundConfiguration;
+import 
org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration;
+import org.apache.cassandra.sidecar.config.AccessControlConfiguration;
+import org.apache.cassandra.sidecar.config.CacheConfiguration;
+import org.apache.cassandra.sidecar.config.KeyStoreConfiguration;
+import org.apache.cassandra.sidecar.config.ParameterizedClassConfiguration;
+import org.apache.cassandra.sidecar.config.yaml.AccessControlConfigurationImpl;
+import org.apache.cassandra.sidecar.config.yaml.CacheConfigurationImpl;
+import org.apache.cassandra.sidecar.config.yaml.KeyStoreConfigurationImpl;
+import 
org.apache.cassandra.sidecar.config.yaml.ParameterizedClassConfigurationImpl;
+import org.apache.cassandra.sidecar.config.yaml.SidecarConfigurationImpl;
+import org.apache.cassandra.sidecar.config.yaml.SslConfigurationImpl;
+import org.apache.cassandra.sidecar.testing.MtlsTestHelper;
+import 
org.apache.cassandra.sidecar.testing.SharedClusterSidecarIntegrationTestBase;
+import org.apache.cassandra.sidecar.testing.TemporaryCqlSessionProvider;
+import org.apache.cassandra.sidecar.utils.CacheFactory;
+import org.apache.cassandra.sidecar.utils.SimpleCassandraVersion;
+import org.apache.cassandra.testing.ClusterBuilderConfiguration;
+
+import static org.apache.cassandra.testing.DriverTestUtils.buildContactPoints;
+import static org.apache.cassandra.testing.TestUtils.DC1_RF1;
+import static org.apache.cassandra.testing.TlsTestUtils.getSSLOptions;
+import static 
org.apache.cassandra.testing.TlsTestUtils.withAuthenticatedSession;
+import static org.apache.cassandra.testing.utils.AssertionUtils.getBlocking;
+import static org.apache.cassandra.testing.utils.AssertionUtils.loopAssert;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assumptions.assumeThat;
+
+/**
+ * Integration test for cache invalidation endpoints
+ */
+class InvalidateCacheIntegrationTest extends 
SharedClusterSidecarIntegrationTestBase
+{
+    protected static final int MIN_VERSION_WITH_MTLS = 5;
+    private static final String CASSANDRA_IDENTITY = 
"spiffe://cassandra/sidecar/cassandra_role";
+    private static final String SIDECAR_ROLE_IDENTITY = 
"spiffe://cassandra/sidecar/sidecar_role";
+    private static final String TEST_USER_IDENTITY = 
"spiffe://cassandra/sidecar/test_user";
+    private static final String TEST_SUPERUSER_IDENTITY = 
"spiffe://cassandra/sidecar/test_superuser";
+    private static final String SCHEMA_ROUTE = "/api/v1/cassandra/schema";
+
+    private Path testUserKeystorePath;
+    private Path superuserKeystorePath;
+
+    @Override
+    protected void beforeClusterProvisioning()
+    {
+        // mTLS authentication was added in Cassandra starting 5.0 version
+        assumeThat(SimpleCassandraVersion.create(testVersion.version()).major)
+        .as("mTLS authentication is not supported in 4.0 and 4.1 Cassandra 
versions")
+        .isGreaterThanOrEqualTo(MIN_VERSION_WITH_MTLS);
+    }
+
+    @Override
+    protected ClusterBuilderConfiguration testClusterConfiguration()
+    {
+        return super.testClusterConfiguration()
+                    .additionalInstanceConfig(Map.of("authenticator", 
"org.apache.cassandra.auth.PasswordAuthenticator"));
+    }
+
+    @Override
+    protected void afterClusterProvisioned()
+    {
+        IInstance instance = cluster.getFirstRunningInstance();
+        configureAdminAndSidecarIdentity(instance);
+
+        cluster.stopUnchecked(instance);
+
+        var instanceConfig = instance.config();
+        instanceConfig.set("authenticator.class_name", 
"org.apache.cassandra.auth.MutualTlsAuthenticator");
+        instanceConfig.set("authenticator.parameters", 
Map.of("validator_class_name",
+                                                              
"org.apache.cassandra.auth.SpiffeCertificateValidator"));
+        instanceConfig.set("role_manager", "CassandraRoleManager");
+        instanceConfig.set("authorizer", "CassandraAuthorizer");
+        instanceConfig.set("client_encryption_options.enabled", "true");
+        instanceConfig.set("client_encryption_options.optional", "true");
+        instanceConfig.set("client_encryption_options.require_client_auth", 
"true");
+        
instanceConfig.set("client_encryption_options.require_endpoint_verification", 
"false");
+        instanceConfig.set("client_encryption_options.keystore", 
mtlsTestHelper.serverKeyStorePath());
+        instanceConfig.set("client_encryption_options.keystore_password", 
mtlsTestHelper.serverKeyStorePassword());
+        instanceConfig.set("client_encryption_options.truststore", 
mtlsTestHelper.trustStorePath());
+        instanceConfig.set("client_encryption_options.truststore_password", 
mtlsTestHelper.trustStorePassword());
+        instanceConfig.set("credentials_update_interval", "50ms");
+
+        instance.startup();
+    }
+
+    @Override
+    protected Function<SidecarConfigurationImpl.Builder, 
SidecarConfigurationImpl.Builder> configurationOverrides()
+    {
+        return builder -> {
+            Map<String, String> params = Map.of("certificate_validator", 
"io.vertx.ext.auth.mtls.impl.CertificateValidatorImpl",
+                                                
"certificate_identity_extractor", 
"org.apache.cassandra.sidecar.acl.authentication.CassandraIdentityExtractor");
+            ParameterizedClassConfiguration mTLSConfig
+            = new 
ParameterizedClassConfigurationImpl("org.apache.cassandra.sidecar.acl.authentication.MutualTlsAuthenticationHandlerFactory",
+                                                      params);
+            ParameterizedClassConfiguration rbacConfig
+            = new 
ParameterizedClassConfigurationImpl("org.apache.cassandra.sidecar.acl.authorization.RoleBasedAuthorizationProvider",
+                                                      Map.of());
+
+            CacheConfiguration permissionCacheConfiguration = 
CacheConfigurationImpl.builder()
+                                                                               
     .expireAfterAccess(MillisecondBoundConfiguration.parse("5s"))
+                                                                               
     .build();
+
+            AccessControlConfiguration accessControlConfiguration = 
AccessControlConfigurationImpl.builder()
+                                                                               
                   .enabled(true)
+                                                                               
                   .authenticatorsConfiguration(List.of(mTLSConfig))
+                                                                               
                   .authorizerConfiguration(rbacConfig)
+                                                                               
                   .permissionCacheConfiguration(permissionCacheConfiguration)
+                                                                               
                   .build();
+
+            KeyStoreConfiguration truststoreConfiguration = new 
KeyStoreConfigurationImpl(mtlsTestHelper.trustStorePath(),
+                                                                               
           mtlsTestHelper.trustStorePassword(),
+                                                                               
           mtlsTestHelper.trustStoreType(),
+                                                                               
           SecondBoundConfiguration.parse("1d"));
+
+            KeyStoreConfiguration keyStoreConfiguration = new 
KeyStoreConfigurationImpl(mtlsTestHelper.serverKeyStorePath(),
+                                                                               
         mtlsTestHelper.serverKeyStorePassword(),
+                                                                               
         mtlsTestHelper.serverKeyStoreType(),
+                                                                               
         SecondBoundConfiguration.parse("1d"));
+
+            SslConfigurationImpl sslConfiguration = 
SslConfigurationImpl.builder()
+                                                                        
.enabled(true)
+                                                                        
.clientAuth("REQUEST")
+                                                                        
.keystore(keyStoreConfiguration)
+                                                                        
.truststore(truststoreConfiguration)
+                                                                        
.build();
+
+            return 
builder.accessControlConfiguration(accessControlConfiguration)
+                          .sslConfiguration(sslConfiguration);
+        };
+    }
+
+    @Override
+    protected void startSidecar(ICluster<? extends IInstance> cluster) throws 
InterruptedException
+    {
+        serverWrapper = startSidecarWithInstances(cluster, new 
TestModule(mtlsTestHelper, cluster));
+    }
+
+    @Override
+    protected void beforeTestStart()
+    {
+        waitForSchemaReady(10, TimeUnit.SECONDS);
+        try
+        {
+            testUserKeystorePath = 
mtlsTestHelper.issueClientKeyStore(certificateBuilder ->
+                                                                      
certificateBuilder.addSanUriName(TEST_USER_IDENTITY));
+            superuserKeystorePath = 
mtlsTestHelper.issueClientKeyStore(certificateBuilder ->
+                                                                       
certificateBuilder.addSanUriName(TEST_SUPERUSER_IDENTITY));
+        }
+        catch (Exception e)
+        {
+            throw new RuntimeException("Failed to create test keystores", e);
+        }
+    }
+
+    @Override
+    protected void initializeSchemaForTest()
+    {
+        Path clientKeystorePath = cassandraIdentityClientKeyStore();
+
+        SSLOptions sslOptions = getSSLOptions(clientKeystorePath.toString(),
+                                              
mtlsTestHelper.clientKeyStorePassword(),
+                                              mtlsTestHelper.trustStorePath(),
+                                              
mtlsTestHelper.trustStorePassword());
+        withAuthenticatedSession(cluster.get(1), "cassandra", "cassandra", 
session -> {
+            createTestKeyspace(session, "sidecar_internal", DC1_RF1);
+            createRolesPermissionsTable(session);
+            createTestRole(session);
+        }, sslOptions);
+    }
+
+    @Test
+    void testInvalidateIdentityToRoleCache()
+    {
+        IdentityToRoleCache identityToRoleCache = 
serverWrapper.injector.getInstance(IdentityToRoleCache.class);
+
+        // Populate the cache by making a request with test user identity
+        verifyAccess(HttpMethod.GET, SCHEMA_ROUTE, testUserKeystorePath, 
assertStatus(HttpResponseStatus.OK));
+
+        // Verify cache has entries using loopAssert as cache operation is 
asynchronous
+        loopAssert(3, () ->
+            assertThat(identityToRoleCache.getAll()).isNotEmpty());
+
+        // Invalidate the cache using superuser
+        String invalidateCacheRoute = 
"/api/v1/caches/identity_to_role_cache/invalidate";
+        verifyAccess(HttpMethod.DELETE, invalidateCacheRoute, 
superuserKeystorePath, assertStatus(HttpResponseStatus.OK));
+
+        // Verify cache is empty after invalidation using loopAssert as cache 
operation is asynchronous
+        loopAssert(3, () ->
+            assertThat(identityToRoleCache.getAll()).isEmpty());

Review Comment:
   can you also call the schema endpoint again and verify with cache metrics 
that it is a miss? 



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