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: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]

