You are viewing a plain text version of this content. The canonical link for it is here.
Posted to pr@cassandra.apache.org by "sarankk (via GitHub)" <gi...@apache.org> on 2025/10/16 18:52:33 UTC
[PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
sarankk opened a new pull request, #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270
(no comment)
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2441274589
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CachedAuthorizationHandler.java:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.Set;
+import java.util.concurrent.ConcurrentHashMap;
+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
+{
+ static final String POPULATE_AUTHORIZATION_CACHES_ENV_NAME = "populate_authorization_caches";
+ static final Set<Cache<AuthorizationCacheKey, Boolean>> AUTHORIZATION_CACHES = ConcurrentHashMap.newKeySet();
+ private static final HttpException FORBIDDEN_EXCEPTION = new HttpException(403);
Review Comment:
yeah, I saw what the super class was doing, I am questioning whether that's correct or not
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2450035571
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CachedAuthorizationHandler.java:
##########
@@ -0,0 +1,201 @@
+/*
+ * 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.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.github.benmanes.caffeine.cache.AsyncCache;
+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.metrics.SidecarMetrics;
+import org.apache.cassandra.sidecar.metrics.server.AuthMetrics;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
+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 Logger LOGGER = LoggerFactory.getLogger(CachedAuthorizationHandler.class);
+
+ // uniquely identities CachedAuthorizationHandler across different routes. Having same handlerId can lead
+ // to permission bypass across routes.
+ private static final AtomicInteger HANDLER_ID_GEN = new AtomicInteger(0);
+ private static final HttpException FORBIDDEN_EXCEPTION = new HttpException(403);
+ private final int handlerId;
+ private final AccessControlConfiguration accessControlConfiguration;
+ private final AuthorizationParameterValidateHandler authZParameterValidateHandler;
+ private final AdminIdentityResolver adminIdentityResolver;
+ private final AuthMetrics authMetrics;
+ private final AsyncCache<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,
+ AsyncCache<AuthorizationCacheKey, Boolean> authorizationCache)
+ {
+ this(HANDLER_ID_GEN.getAndIncrement(), accessControlConfiguration, authZParameterValidateHandler,
+ adminIdentityResolver, authorization, sidecarMetrics, authorizationCache);
+ }
+
+ @VisibleForTesting
+ public CachedAuthorizationHandler(int handlerId,
+ AccessControlConfiguration accessControlConfiguration,
+ AuthorizationParameterValidateHandler authZParameterValidateHandler,
+ AdminIdentityResolver adminIdentityResolver,
+ Authorization authorization,
+ SidecarMetrics sidecarMetrics,
+ AsyncCache<AuthorizationCacheKey, Boolean> authorizationCache)
+ {
+ super(authorization);
+ this.handlerId = handlerId;
+ this.accessControlConfiguration = accessControlConfiguration;
+ this.authZParameterValidateHandler = authZParameterValidateHandler;
+ this.adminIdentityResolver = adminIdentityResolver;
+ this.authMetrics = sidecarMetrics.server().auth();
+ this.authorizationCache = authorizationCache;
+ }
+
+ @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(handlerId, authorizationContext);
+ CompletableFuture<Boolean> authorizationFuture = checkAuthorization(key, ctx, ctxNextCalled, startTimeNanos);
Review Comment:
the reason for the client to use CompletableFuture is because the core project client project does not have any vertx dependencies
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2437544018
##########
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;
Review Comment:
Pulled the cache compute into a separate method.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2441339848
##########
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;
Review Comment:
Switched to AsyncCache as suggested
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
yifan-c commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2437395699
##########
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;
Review Comment:
I am concerned about the complexity in this mapping function. It is supposed to be simple and short.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2441336039
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CachedAuthorizationHandler.java:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.Set;
+import java.util.concurrent.ConcurrentHashMap;
+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
+{
+ static final String POPULATE_AUTHORIZATION_CACHES_ENV_NAME = "populate_authorization_caches";
+ static final Set<Cache<AuthorizationCacheKey, Boolean>> AUTHORIZATION_CACHES = ConcurrentHashMap.newKeySet();
+ private static final HttpException FORBIDDEN_EXCEPTION = new HttpException(403);
Review Comment:
What context are you referring you that we are missing, we don't get stack trace during these calls. We only see 403 exception.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2437355696
##########
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:
It was just redundant, removing it.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2437659118
##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationIntegrationTest.java:
##########
@@ -257,7 +268,7 @@ protected Function<SidecarConfigurationImpl.Builder, SidecarConfigurationImpl.Bu
Map.of());
CacheConfiguration permissionCacheConfiguration = CacheConfigurationImpl.builder()
- .expireAfterAccess(MillisecondBoundConfiguration.parse("100ms"))
+ .expireAfterAccess(MillisecondBoundConfiguration.parse("300ms"))
Review Comment:
can we keep it 100ms?
##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationIntegrationTest.java:
##########
@@ -497,7 +513,9 @@ void testEndpointRequiringMultipleActions()
grantTablePermission(session, "multiple_permissions_required_test_keyspace", "test_table", "non_admin_test_role");
}, sslOptions);
- loopAssert(2, 100, () -> {
+ invalidateAuthorizationHandlerCaches();
+
+ loopAssert(4, 100, () -> {
Review Comment:
can we keep this at 2?
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationCacheKeyImpl.java:
##########
@@ -0,0 +1,69 @@
+/*
+ * 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.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+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 Map<String, String> variables;
+
+ public AuthorizationCacheKeyImpl(User user, MultiMap variables)
+ {
+ this.roles = extractCassandraRoles(user);
+ // store an immutable copy of variables in a Map
+ this.variables = variables.entries()
Review Comment:
can we precompute the hash here?
##########
server/src/main/java/org/apache/cassandra/sidecar/metrics/server/AuthMetrics.java:
##########
@@ -32,17 +33,23 @@ public class AuthMetrics
private static final String DOMAIN = SERVER_PREFIX + ".Auth";
public final NamedMetric<Counter> jwtPemRefreshFailures;
public final NamedMetric<Counter> jwtPemRefreshSuccesses;
+ public final NamedMetric<Timer> authorizationTime;
Review Comment:
I think we should document that this authorization time is only taking into account authorizations that are not cached
##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationIntegrationTest.java:
##########
@@ -463,8 +475,10 @@ void testEndpointRequiringMultipleActions()
"data/multiple_permissions_required_test_keyspace/test_table",
"SNAPSHOT:READ");
+ invalidateAuthorizationHandlerCaches();
+
// wait for cache refresh
- loopAssert(2, 100, () -> {
+ loopAssert(4, 100, () -> {
Review Comment:
can we keep this at 2?
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationCacheKeyImpl.java:
##########
@@ -0,0 +1,69 @@
+/*
+ * 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.Map;
+import java.util.Objects;
+import java.util.stream.Collectors;
+
+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 Map<String, String> variables;
+
+ public AuthorizationCacheKeyImpl(User user, MultiMap variables)
Review Comment:
NIT : can we use the underlying interface here?
```suggestion
public AuthorizationCacheKeyImpl(User user, Iterable<Map.Entry<String, String>> variables)
```
##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationIntegrationTest.java:
##########
@@ -486,9 +500,11 @@ void testEndpointRequiringMultipleActions()
"data/multiple_permissions_required_test_keyspace/test_table",
"SNAPSHOT:STREAM");
+ invalidateAuthorizationHandlerCaches();
+
// STREAM SSTable request requires both Sidecar SNAPSHOT:STREAM permission and Cassandra's SELECT
// permission on a table it accesses data.
- loopAssert(2, 100, () -> {
+ loopAssert(4, 100, () -> {
Review Comment:
can we keep this at 2?
##########
server/src/main/java/org/apache/cassandra/sidecar/routes/RouteBuilder.java:
##########
@@ -206,25 +214,29 @@ public static class Factory
private final AuthorizationProvider authorizationProvider;
private final AdminIdentityResolver adminIdentityResolver;
private final AuthorizationParameterValidateHandler authZParameterValidateHandler;
+ private final SidecarMetrics sidecarMetrics;
public Factory(AccessControlConfiguration accessControlConfiguration,
AuthorizationProvider authorizationProvider,
AdminIdentityResolver adminIdentityResolver,
- AuthorizationParameterValidateHandler authZParameterValidateHandler)
+ AuthorizationParameterValidateHandler authZParameterValidateHandler,
+ SidecarMetrics sidecarMetrics)
{
this.accessControlConfiguration = accessControlConfiguration;
this.authorizationProvider = authorizationProvider;
this.adminIdentityResolver = adminIdentityResolver;
this.authZParameterValidateHandler = authZParameterValidateHandler;
+ this.sidecarMetrics = sidecarMetrics;
}
public RouteBuilder builderForRoute()
{
return new RouteBuilder(accessControlConfiguration,
authorizationProvider,
adminIdentityResolver,
- authZParameterValidateHandler);
+ authZParameterValidateHandler,
Review Comment:
NIT, we should instead modify the ctor to take the Factory. i.e new RouteBuilder(this);
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CachedAuthorizationHandler.java:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.Set;
+import java.util.concurrent.ConcurrentHashMap;
+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
+{
+ static final String POPULATE_AUTHORIZATION_CACHES_ENV_NAME = "populate_authorization_caches";
+ static final Set<Cache<AuthorizationCacheKey, Boolean>> AUTHORIZATION_CACHES = ConcurrentHashMap.newKeySet();
+ private static final HttpException FORBIDDEN_EXCEPTION = new HttpException(403);
Review Comment:
will we be losing the stacktrace by precreating the exception? is the stack trace something we care about?
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "frankgh (via GitHub)" <gi...@apache.org>.
frankgh commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2449997458
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CachedAuthorizationHandler.java:
##########
@@ -0,0 +1,201 @@
+/*
+ * 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.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.github.benmanes.caffeine.cache.AsyncCache;
+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.metrics.SidecarMetrics;
+import org.apache.cassandra.sidecar.metrics.server.AuthMetrics;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
+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 Logger LOGGER = LoggerFactory.getLogger(CachedAuthorizationHandler.class);
+
+ // uniquely identities CachedAuthorizationHandler across different routes. Having same handlerId can lead
+ // to permission bypass across routes.
+ private static final AtomicInteger HANDLER_ID_GEN = new AtomicInteger(0);
+ private static final HttpException FORBIDDEN_EXCEPTION = new HttpException(403);
+ private final int handlerId;
+ private final AccessControlConfiguration accessControlConfiguration;
+ private final AuthorizationParameterValidateHandler authZParameterValidateHandler;
+ private final AdminIdentityResolver adminIdentityResolver;
+ private final AuthMetrics authMetrics;
+ private final AsyncCache<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,
+ AsyncCache<AuthorizationCacheKey, Boolean> authorizationCache)
+ {
+ this(HANDLER_ID_GEN.getAndIncrement(), accessControlConfiguration, authZParameterValidateHandler,
+ adminIdentityResolver, authorization, sidecarMetrics, authorizationCache);
+ }
+
+ @VisibleForTesting
+ public CachedAuthorizationHandler(int handlerId,
+ AccessControlConfiguration accessControlConfiguration,
+ AuthorizationParameterValidateHandler authZParameterValidateHandler,
+ AdminIdentityResolver adminIdentityResolver,
+ Authorization authorization,
+ SidecarMetrics sidecarMetrics,
+ AsyncCache<AuthorizationCacheKey, Boolean> authorizationCache)
+ {
+ super(authorization);
+ this.handlerId = handlerId;
+ this.accessControlConfiguration = accessControlConfiguration;
+ this.authZParameterValidateHandler = authZParameterValidateHandler;
+ this.adminIdentityResolver = adminIdentityResolver;
+ this.authMetrics = sidecarMetrics.server().auth();
+ this.authorizationCache = authorizationCache;
+ }
+
+ @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(handlerId, authorizationContext);
+ CompletableFuture<Boolean> authorizationFuture = checkAuthorization(key, ctx, ctxNextCalled, startTimeNanos);
Review Comment:
`checkAuthorization` should not return a CompletableFuture. The code base is using vertx and we should consistently use vertx Futures instead here. Vertx provides ways to convert a CompletableFuture to Future, `Future.fromCompletionStage`.
If we start having an inconsistent code base it will become harder for new contributors to understand when to use one or the other. Having a single way of doing things will simplify this.
```suggestion
Future<Boolean> authorizationFuture = checkAuthorization(key, ctx, ctxNextCalled, startTimeNanos);
```
##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationIntegrationTest.java:
##########
@@ -769,6 +944,28 @@ private HttpResponse<Buffer> createRequest(WebClient client, HttpMethod method,
return getBlocking(client.request(method, serverWrapper.serverPort, "127.0.0.1", route).send());
}
+ private void createMultipleRequests(WebClient client, HttpMethod method, String route, int times,
+ int expectedResponseCode)
+ {
+ List<Future<HttpResponse<Buffer>>> futures = new ArrayList<>();
+ for (int i = 0; i < times; i++)
+ {
+ futures.add(createUnblockingRequest(client, method, route));
+ }
+
+ // Now block for response
+ for (int i = 0; i < times; i++)
+ {
+ HttpResponse<Buffer> response = getBlocking(futures.get(i));
+ assertThat(response.statusCode()).isEqualTo(expectedResponseCode);
+ }
+ }
+
+ private Future<HttpResponse<Buffer>> createUnblockingRequest(WebClient client, HttpMethod method, String route)
Review Comment:
NIT
```suggestion
private Future<HttpResponse<Buffer>> createNonBlockingRequest(WebClient client, HttpMethod method, String route)
```
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CachedAuthorizationHandler.java:
##########
@@ -0,0 +1,201 @@
+/*
+ * 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.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.github.benmanes.caffeine.cache.AsyncCache;
+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.metrics.SidecarMetrics;
+import org.apache.cassandra.sidecar.metrics.server.AuthMetrics;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
+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 Logger LOGGER = LoggerFactory.getLogger(CachedAuthorizationHandler.class);
+
+ // uniquely identities CachedAuthorizationHandler across different routes. Having same handlerId can lead
+ // to permission bypass across routes.
+ private static final AtomicInteger HANDLER_ID_GEN = new AtomicInteger(0);
+ private static final HttpException FORBIDDEN_EXCEPTION = new HttpException(403);
+ private final int handlerId;
+ private final AccessControlConfiguration accessControlConfiguration;
+ private final AuthorizationParameterValidateHandler authZParameterValidateHandler;
+ private final AdminIdentityResolver adminIdentityResolver;
+ private final AuthMetrics authMetrics;
+ private final AsyncCache<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,
+ AsyncCache<AuthorizationCacheKey, Boolean> authorizationCache)
+ {
+ this(HANDLER_ID_GEN.getAndIncrement(), accessControlConfiguration, authZParameterValidateHandler,
+ adminIdentityResolver, authorization, sidecarMetrics, authorizationCache);
+ }
+
+ @VisibleForTesting
+ public CachedAuthorizationHandler(int handlerId,
+ AccessControlConfiguration accessControlConfiguration,
+ AuthorizationParameterValidateHandler authZParameterValidateHandler,
+ AdminIdentityResolver adminIdentityResolver,
+ Authorization authorization,
+ SidecarMetrics sidecarMetrics,
+ AsyncCache<AuthorizationCacheKey, Boolean> authorizationCache)
+ {
+ super(authorization);
+ this.handlerId = handlerId;
+ this.accessControlConfiguration = accessControlConfiguration;
+ this.authZParameterValidateHandler = authZParameterValidateHandler;
+ this.adminIdentityResolver = adminIdentityResolver;
+ this.authMetrics = sidecarMetrics.server().auth();
+ this.authorizationCache = authorizationCache;
+ }
+
+ @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(handlerId, authorizationContext);
Review Comment:
Let's defer key creation for when we need it. The key won't be used in the case where the cache is not enabled.
##########
server/src/main/java/org/apache/cassandra/sidecar/metrics/server/AuthMetrics.java:
##########
@@ -32,17 +33,23 @@ public class AuthMetrics
private static final String DOMAIN = SERVER_PREFIX + ".Auth";
public final NamedMetric<Counter> jwtPemRefreshFailures;
public final NamedMetric<Counter> jwtPemRefreshSuccesses;
+ public final NamedMetric<Timer> authorizationTime;
Review Comment:
maybe we can add a comment like this?
```suggestion
/**
* Captures the time to successfully authorize non-cached requests. Cached authorization requests will
* not be recorded in this metric
*/
public final NamedMetric<Timer> authorizationTime;
```
##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationIntegrationTest.java:
##########
@@ -656,6 +667,157 @@ 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();
Review Comment:
is this needed?
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationCacheKeyImpl.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.cassandra.sidecar.acl.authorization;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+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 int handlerId;
+ private final List<String> roles;
+ private final Set<String> variables;
+ private final int hashCode;
+
+ /**
+ * Creates an instance of {@link AuthorizationCacheKeyImpl}
+ *
+ * @param handlerId an id used to uniquely represent an authorization handler used for a route
+ * @param user {@link User} represents an user in Vert.x
+ * @param variables resource mappings associated with a user request
+ */
+ public AuthorizationCacheKeyImpl(int handlerId, User user, Iterable<Map.Entry<String, String>> variables)
+ {
+ this.handlerId = handlerId;
+ this.roles = extractCassandraRoles(user);
+
+ if (variables == null || !variables.iterator().hasNext())
+ {
+ this.variables = Set.of();
+ }
+ else
+ {
+ // Vert.x HeadersMultimap and HeadersMultimap.MapEntry does not implement equals or hashCode,
+ // hence we store flattened variables in a Set
+ Set<String> flattenedVariables = new HashSet<>();
+ for (Map.Entry<String, String> entry : variables)
+ {
+ // We convert to lower case, since Vert.x Multimap representation is case insensitive for variables stored
+ flattenedVariables.add(entry.getKey().toLowerCase() + ":" + entry.getValue());
+ }
+ this.variables = Set.copyOf(flattenedVariables);
Review Comment:
we can probably avoid creating a copy here. The flattenedVariables set does not escape this class. If you prefer to keep an immutable set, I think we should use `Collections.unmodifiableSet` which avoids copying the values again
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk merged PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "yifan-c (via GitHub)" <gi...@apache.org>.
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2440568755
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CachedAuthorizationHandler.java:
##########
@@ -0,0 +1,171 @@
+/*
+ * 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.Set;
+import java.util.concurrent.ConcurrentHashMap;
+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
+{
+ static final String POPULATE_AUTHORIZATION_CACHES_ENV_NAME = "populate_authorization_caches";
+ static final Set<Cache<AuthorizationCacheKey, Boolean>> AUTHORIZATION_CACHES = ConcurrentHashMap.newKeySet();
+ private static final HttpException FORBIDDEN_EXCEPTION = new HttpException(403);
Review Comment:
No, even from `super.handle` we only get FORBIDDEN exception.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2450018834
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CachedAuthorizationHandler.java:
##########
@@ -0,0 +1,201 @@
+/*
+ * 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.CompletableFuture;
+import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.function.BiConsumer;
+
+import com.google.common.annotations.VisibleForTesting;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
+import com.github.benmanes.caffeine.cache.AsyncCache;
+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.metrics.SidecarMetrics;
+import org.apache.cassandra.sidecar.metrics.server.AuthMetrics;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.FORBIDDEN;
+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 Logger LOGGER = LoggerFactory.getLogger(CachedAuthorizationHandler.class);
+
+ // uniquely identities CachedAuthorizationHandler across different routes. Having same handlerId can lead
+ // to permission bypass across routes.
+ private static final AtomicInteger HANDLER_ID_GEN = new AtomicInteger(0);
+ private static final HttpException FORBIDDEN_EXCEPTION = new HttpException(403);
+ private final int handlerId;
+ private final AccessControlConfiguration accessControlConfiguration;
+ private final AuthorizationParameterValidateHandler authZParameterValidateHandler;
+ private final AdminIdentityResolver adminIdentityResolver;
+ private final AuthMetrics authMetrics;
+ private final AsyncCache<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,
+ AsyncCache<AuthorizationCacheKey, Boolean> authorizationCache)
+ {
+ this(HANDLER_ID_GEN.getAndIncrement(), accessControlConfiguration, authZParameterValidateHandler,
+ adminIdentityResolver, authorization, sidecarMetrics, authorizationCache);
+ }
+
+ @VisibleForTesting
+ public CachedAuthorizationHandler(int handlerId,
+ AccessControlConfiguration accessControlConfiguration,
+ AuthorizationParameterValidateHandler authZParameterValidateHandler,
+ AdminIdentityResolver adminIdentityResolver,
+ Authorization authorization,
+ SidecarMetrics sidecarMetrics,
+ AsyncCache<AuthorizationCacheKey, Boolean> authorizationCache)
+ {
+ super(authorization);
+ this.handlerId = handlerId;
+ this.accessControlConfiguration = accessControlConfiguration;
+ this.authZParameterValidateHandler = authZParameterValidateHandler;
+ this.adminIdentityResolver = adminIdentityResolver;
+ this.authMetrics = sidecarMetrics.server().auth();
+ this.authorizationCache = authorizationCache;
+ }
+
+ @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(handlerId, authorizationContext);
+ CompletableFuture<Boolean> authorizationFuture = checkAuthorization(key, ctx, ctxNextCalled, startTimeNanos);
Review Comment:
We have lot of usage of `CompletableFuture` in Sidecar project in client subproject.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2450013000
##########
server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationCacheKeyImpl.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.cassandra.sidecar.acl.authorization;
+
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+
+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 int handlerId;
+ private final List<String> roles;
+ private final Set<String> variables;
+ private final int hashCode;
+
+ /**
+ * Creates an instance of {@link AuthorizationCacheKeyImpl}
+ *
+ * @param handlerId an id used to uniquely represent an authorization handler used for a route
+ * @param user {@link User} represents an user in Vert.x
+ * @param variables resource mappings associated with a user request
+ */
+ public AuthorizationCacheKeyImpl(int handlerId, User user, Iterable<Map.Entry<String, String>> variables)
+ {
+ this.handlerId = handlerId;
+ this.roles = extractCassandraRoles(user);
+
+ if (variables == null || !variables.iterator().hasNext())
+ {
+ this.variables = Set.of();
+ }
+ else
+ {
+ // Vert.x HeadersMultimap and HeadersMultimap.MapEntry does not implement equals or hashCode,
+ // hence we store flattened variables in a Set
+ Set<String> flattenedVariables = new HashSet<>();
+ for (Map.Entry<String, String> entry : variables)
+ {
+ // We convert to lower case, since Vert.x Multimap representation is case insensitive for variables stored
+ flattenedVariables.add(entry.getKey().toLowerCase() + ":" + entry.getValue());
+ }
+ this.variables = Set.copyOf(flattenedVariables);
Review Comment:
Discussed we use the created Set as is.
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org
Re: [PR] CASSSIDECAR-357: Add cache for Authorization layer [cassandra-sidecar]
Posted by "sarankk (via GitHub)" <gi...@apache.org>.
sarankk commented on code in PR #270:
URL: https://github.com/apache/cassandra-sidecar/pull/270#discussion_r2450003595
##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationIntegrationTest.java:
##########
@@ -656,6 +667,157 @@ 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();
Review Comment:
Yes it is since cache stats are shared between test cases
--
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: pr-unsubscribe@cassandra.apache.org
For queries about this service, please contact Infrastructure at:
users@infra.apache.org
---------------------------------------------------------------------
To unsubscribe, e-mail: pr-unsubscribe@cassandra.apache.org
For additional commands, e-mail: pr-help@cassandra.apache.org