frankgh commented on code in PR #201: URL: https://github.com/apache/cassandra-sidecar/pull/201#discussion_r1980300064
########## conf/sidecar.yaml: ########## @@ -193,6 +197,17 @@ access_control: # # other options are, io.vertx.ext.auth.mtls.impl.SpiffeIdentityExtractor. certificate_identity_extractor: org.apache.cassandra.sidecar.acl.authentication.CassandraIdentityExtractor + # JwtAuthenticationHandlerFactory adds support to authenticate users with their JWT tokens. It also includes + # supports for OpenID discovery. + - class_name: org.apache.cassandra.sidecar.acl.authentication.JwtAuthenticationHandlerFactory + parameters: + # Site for sidecar to dynamically retrieve the configuration information of an OpenID provider, without + # having to manually configure settings like issuer etc. + site: https://authorization.com + # Client Id is a unique identifier assigned by OpenID provider. It is used to identity applications/users + # trying to connect. + client_id: recognized_client_id + config_discover_interval: 1m Review Comment: I think this is running too frequently. I suggest a default of 1 hour instead. What do you think? ```suggestion config_discover_interval: 1h ``` ########## server/src/main/java/org/apache/cassandra/sidecar/acl/authentication/JwtParameterExtractor.java: ########## @@ -0,0 +1,142 @@ +/* + * 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.authentication; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration; + +import static org.apache.cassandra.sidecar.common.utils.StringUtils.isNotEmpty; +import static org.apache.cassandra.sidecar.common.utils.StringUtils.isNullOrEmpty; + +/** + * {@link JwtParameterExtractor} parses necessary JWT configuration from parameters passed during authenticator setup. + */ +public class JwtParameterExtractor +{ + protected static final String SITE_SUFFIX = "/.well-known/openid-configuration"; + + private static final Logger LOGGER = LoggerFactory.getLogger(JwtParameterExtractor.class); + private static final String SITE_PARAM_KEY = "site"; + private static final String CLIENT_ID_PARAM_KEY = "client_id"; + private static final String SCOPE_SEPARATOR_PARAM_KEY = "scope_separator"; + private static final String DEFAULT_SCOPE_SEPARATOR = ","; + private static final String SCOPES_SUPPORTED_PARAM_KEY = "scopes_supported"; + private static final String CONFIG_DISCOVER_INTERVAL_PARAM_KEY = "config_discover_interval"; + private static final SecondBoundConfiguration DEFAULT_CONFIG_DISCOVER_INTERVAL + = SecondBoundConfiguration.parse("1m"); + + private final String site; + private final String clientId; + private final SecondBoundConfiguration configDiscoverInterval; + private final List<String> scopes; + + public JwtParameterExtractor(Map<String, String> parameters) + { + validate(parameters); + this.site = removeSiteSuffix(parameters); + this.clientId = parameters.get(CLIENT_ID_PARAM_KEY); + this.scopes = buildScopes(parameters); + this.configDiscoverInterval = parameters.containsKey(CONFIG_DISCOVER_INTERVAL_PARAM_KEY) + ? SecondBoundConfiguration.parse(parameters.get(CONFIG_DISCOVER_INTERVAL_PARAM_KEY)) + : DEFAULT_CONFIG_DISCOVER_INTERVAL; + } + + /** + * @return site to dynamically retrieve the configuration information of an OpenID provider + */ + public String site() + { + return site; + } + + /** + * @return clientId is a unique identifier used to identity applications/users + */ + public String clientId() + { + return clientId; + } + + /** + * @return scopes granted to a user + */ + public List<String> scopes() + { + return scopes; + } + + /** + * @return interval at which {@link io.vertx.ext.auth.oauth2.providers.OpenIDConnectAuth} discover is called to + * dynamically retrieve configuration information of an OpenID provider. + */ + public SecondBoundConfiguration configDiscoverInterval() + { + return configDiscoverInterval; + } + + private void validate(Map<String, String> parameters) + { + if (parameters == null) + { + throw new IllegalArgumentException("JWT parameters can not be null"); + } + + validateParameterPresence(parameters, SITE_PARAM_KEY); + validateParameterPresence(parameters, CLIENT_ID_PARAM_KEY); + } + + private void validateParameterPresence(Map<String, String> parameters, String paramKey) + { + if (!parameters.containsKey(paramKey) || isNullOrEmpty(parameters.get(paramKey))) Review Comment: minor NIT, no need to check if it doesn't contain. doing a get should be sufficient ```suggestion if (isNullOrEmpty(parameters.get(paramKey))) ``` ########## server/src/main/java/org/apache/cassandra/sidecar/acl/authentication/JwtParameterExtractor.java: ########## @@ -0,0 +1,142 @@ +/* + * 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.authentication; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.sidecar.common.server.utils.SecondBoundConfiguration; + +import static org.apache.cassandra.sidecar.common.utils.StringUtils.isNotEmpty; +import static org.apache.cassandra.sidecar.common.utils.StringUtils.isNullOrEmpty; + +/** + * {@link JwtParameterExtractor} parses necessary JWT configuration from parameters passed during authenticator setup. + */ +public class JwtParameterExtractor +{ + protected static final String SITE_SUFFIX = "/.well-known/openid-configuration"; + + private static final Logger LOGGER = LoggerFactory.getLogger(JwtParameterExtractor.class); + private static final String SITE_PARAM_KEY = "site"; + private static final String CLIENT_ID_PARAM_KEY = "client_id"; + private static final String SCOPE_SEPARATOR_PARAM_KEY = "scope_separator"; + private static final String DEFAULT_SCOPE_SEPARATOR = ","; + private static final String SCOPES_SUPPORTED_PARAM_KEY = "scopes_supported"; + private static final String CONFIG_DISCOVER_INTERVAL_PARAM_KEY = "config_discover_interval"; + private static final SecondBoundConfiguration DEFAULT_CONFIG_DISCOVER_INTERVAL + = SecondBoundConfiguration.parse("1m"); Review Comment: Can this be 1 hour instead? ########## server/src/main/java/org/apache/cassandra/sidecar/acl/authentication/ReloadingJwtAuthenticationHandler.java: ########## @@ -0,0 +1,179 @@ +/* + * 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.authentication; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.vertx.core.AsyncResult; +import io.vertx.core.Future; +import io.vertx.core.Handler; +import io.vertx.core.Promise; +import io.vertx.core.Vertx; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.auth.User; +import io.vertx.ext.auth.authentication.AuthenticationProvider; +import io.vertx.ext.auth.oauth2.OAuth2Options; +import io.vertx.ext.auth.oauth2.providers.OpenIDConnectAuth; +import io.vertx.ext.web.RoutingContext; +import io.vertx.ext.web.handler.HttpException; +import io.vertx.ext.web.handler.impl.AuthenticationHandlerImpl; +import io.vertx.ext.web.handler.impl.OAuth2AuthHandlerImpl; +import org.apache.cassandra.sidecar.common.server.utils.DurationSpec; +import org.apache.cassandra.sidecar.tasks.PeriodicTask; +import org.apache.cassandra.sidecar.tasks.PeriodicTaskExecutor; + +import static io.netty.handler.codec.http.HttpResponseStatus.SERVICE_UNAVAILABLE; +import static io.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED; +import static org.apache.cassandra.sidecar.utils.AuthUtils.CASSANDRA_ROLES_ATTRIBUTE_NAME; +import static org.apache.cassandra.sidecar.utils.AuthUtils.CASSANDRA_ROLE_SPLITTER; + +/** + * {@link ReloadingJwtAuthenticationHandler} validates JWT token of a user. It handles periodically calling + * {@link OpenIDConnectAuth} discover to fetch latest configuration and handles reloading {@link OAuth2AuthHandlerImpl}. + * It can be chained with other {@link io.vertx.ext.web.handler.AuthenticationHandler} implementations. + */ +public class ReloadingJwtAuthenticationHandler +extends AuthenticationHandlerImpl<ReloadingJwtAuthenticationHandler.NoOpAuthenticationProvider> +{ + private static final Logger LOGGER = LoggerFactory.getLogger(ReloadingJwtAuthenticationHandler.class); + + AtomicReference<OAuth2AuthHandlerImpl> delegateHandler = new AtomicReference<>(); + + private final Vertx vertx; + private final JwtParameterExtractor jwtParameterExtractor; + private final JwtRoleProcessor roleProcessor; + + public ReloadingJwtAuthenticationHandler(Vertx vertx, + JwtParameterExtractor jwtParameterExtractor, + JwtRoleProcessor roleProcessor, + PeriodicTaskExecutor periodicTaskExecutor) + { + super(NoOpAuthenticationProvider.INSTANCE); + this.vertx = vertx; + this.jwtParameterExtractor = jwtParameterExtractor; + this.roleProcessor = roleProcessor; + + periodicTaskExecutor.schedule(new OAuth2AuthHandlerGenerateTask()); + } + + @Override + public void authenticate(RoutingContext context, Handler<AsyncResult<User>> handler) + { + OAuth2AuthHandlerImpl oAuth2AuthHandler = delegateHandler.get(); + if (oAuth2AuthHandler == null) + { + handler.handle(Future.failedFuture(new HttpException(SERVICE_UNAVAILABLE.code(), + "JWT authentication handler unavailable"))); + return; + } + + oAuth2AuthHandler.authenticate(context, authN -> { + if (authN.failed()) + { + handler.handle(Future.failedFuture(new HttpException(UNAUTHORIZED.code(), authN.cause()))); + return; + } + + User user = authN.result(); + JsonObject decodedToken = user.attributes().containsKey("accessToken") + ? user.attributes().getJsonObject("accessToken") + : user.attributes().getJsonObject("idToken"); + + if (decodedToken == null) + { + handler.handle(Future.failedFuture(new HttpException(UNAUTHORIZED.code(), + "Could not process decoded JWT token"))); + return; + } + + try + { + List<String> roles = roleProcessor.processRoles(decodedToken); + if (!roles.isEmpty()) + { + user.attributes().put(CASSANDRA_ROLES_ATTRIBUTE_NAME, String.join(CASSANDRA_ROLE_SPLITTER, roles)); + } + handler.handle(Future.succeededFuture(user)); + } + catch (Exception e) + { + LOGGER.debug("Error processing cassandra role from JWT token", e); + handler.handle(Future.failedFuture(new HttpException(UNAUTHORIZED.code(), + "Error processing cassandra role from token"))); + } + }); + } + + /** + * {@link NoOpAuthenticationProvider} is used in {@link ReloadingJwtAuthenticationHandler}. + * {@link ReloadingJwtAuthenticationHandler} delegates authenticating user to delegate handler. + * Hence it uses no op authentication provider + */ + protected static class NoOpAuthenticationProvider implements AuthenticationProvider + { + public static final NoOpAuthenticationProvider INSTANCE = new NoOpAuthenticationProvider(); + + private NoOpAuthenticationProvider() + { + } + + @Override + public void authenticate(JsonObject credentials, Handler<AsyncResult<User>> resultHandler) + { + resultHandler.handle(Future.succeededFuture()); + } + } + + /** + * Periodic task to generate {@link OAuth2AuthHandlerImpl} with refreshed configuration from + * {@link OpenIDConnectAuth} discover. + */ + private class OAuth2AuthHandlerGenerateTask implements PeriodicTask + { + public DurationSpec delay() + { + return jwtParameterExtractor.configDiscoverInterval(); + } + + public void execute(Promise<Void> promise) Review Comment: ```suggestion @Override public void execute(Promise<Void> promise) ``` ########## server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationProvider.java: ########## @@ -64,29 +59,28 @@ public void getAuthorizations(User user, Handler<AsyncResult<Void>> handler) @Override public Future<Void> getAuthorizations(User user) { - List<String> identities = extractIdentities(user); + List<String> roles = extractCassandraRoles(user); - if (identities.isEmpty()) + if (roles.isEmpty()) { - return Future.failedFuture("Missing client identities"); + return Future.failedFuture("No cassandra roles found associated with the user"); } - Set<Authorization> authorizations = new HashSet<>(); - for (String identity : identities) + for (String role : roles) Review Comment: can role be null? I'm referring to the check in line 71. I guess it's fine to have the check, but it feels that it would be an error to return null ########## server/src/main/java/org/apache/cassandra/sidecar/acl/authentication/JwtRoleProcessorImpl.java: ########## @@ -0,0 +1,79 @@ +/* + * 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.authentication; + +import java.util.ArrayList; +import java.util.List; + +import io.vertx.core.json.JsonObject; +import org.apache.cassandra.sidecar.acl.IdentityToRoleCache; + +/** + * {@link JwtRoleProcessor} implementation. + */ +public class JwtRoleProcessorImpl implements JwtRoleProcessor +{ + private static final String SUB_KEY = "sub"; + private static final String IDENTITY_KEY = "identity"; + private static final String IDENTITIES_KEY = "identities"; + private final IdentityToRoleCache identityToRoleCache; + + public JwtRoleProcessorImpl(IdentityToRoleCache identityToRoleCache) + { + this.identityToRoleCache = identityToRoleCache; + } + + public List<String> processRoles(JsonObject decodedToken) Review Comment: ```suggestion @Override public List<String> processRoles(JsonObject decodedToken) ``` ########## server/src/main/java/org/apache/cassandra/sidecar/acl/authentication/ReloadingJwtAuthenticationHandler.java: ########## @@ -0,0 +1,179 @@ +/* + * 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.authentication; + +import java.util.List; +import java.util.concurrent.atomic.AtomicReference; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import io.vertx.core.AsyncResult; +import io.vertx.core.Future; +import io.vertx.core.Handler; +import io.vertx.core.Promise; +import io.vertx.core.Vertx; +import io.vertx.core.json.JsonObject; +import io.vertx.ext.auth.User; +import io.vertx.ext.auth.authentication.AuthenticationProvider; +import io.vertx.ext.auth.oauth2.OAuth2Options; +import io.vertx.ext.auth.oauth2.providers.OpenIDConnectAuth; +import io.vertx.ext.web.RoutingContext; +import io.vertx.ext.web.handler.HttpException; +import io.vertx.ext.web.handler.impl.AuthenticationHandlerImpl; +import io.vertx.ext.web.handler.impl.OAuth2AuthHandlerImpl; +import org.apache.cassandra.sidecar.common.server.utils.DurationSpec; +import org.apache.cassandra.sidecar.tasks.PeriodicTask; +import org.apache.cassandra.sidecar.tasks.PeriodicTaskExecutor; + +import static io.netty.handler.codec.http.HttpResponseStatus.SERVICE_UNAVAILABLE; +import static io.netty.handler.codec.http.HttpResponseStatus.UNAUTHORIZED; +import static org.apache.cassandra.sidecar.utils.AuthUtils.CASSANDRA_ROLES_ATTRIBUTE_NAME; +import static org.apache.cassandra.sidecar.utils.AuthUtils.CASSANDRA_ROLE_SPLITTER; + +/** + * {@link ReloadingJwtAuthenticationHandler} validates JWT token of a user. It handles periodically calling + * {@link OpenIDConnectAuth} discover to fetch latest configuration and handles reloading {@link OAuth2AuthHandlerImpl}. + * It can be chained with other {@link io.vertx.ext.web.handler.AuthenticationHandler} implementations. + */ +public class ReloadingJwtAuthenticationHandler +extends AuthenticationHandlerImpl<ReloadingJwtAuthenticationHandler.NoOpAuthenticationProvider> +{ + private static final Logger LOGGER = LoggerFactory.getLogger(ReloadingJwtAuthenticationHandler.class); + + AtomicReference<OAuth2AuthHandlerImpl> delegateHandler = new AtomicReference<>(); + + private final Vertx vertx; + private final JwtParameterExtractor jwtParameterExtractor; + private final JwtRoleProcessor roleProcessor; + + public ReloadingJwtAuthenticationHandler(Vertx vertx, + JwtParameterExtractor jwtParameterExtractor, + JwtRoleProcessor roleProcessor, + PeriodicTaskExecutor periodicTaskExecutor) + { + super(NoOpAuthenticationProvider.INSTANCE); + this.vertx = vertx; + this.jwtParameterExtractor = jwtParameterExtractor; + this.roleProcessor = roleProcessor; + + periodicTaskExecutor.schedule(new OAuth2AuthHandlerGenerateTask()); + } + + @Override + public void authenticate(RoutingContext context, Handler<AsyncResult<User>> handler) + { + OAuth2AuthHandlerImpl oAuth2AuthHandler = delegateHandler.get(); + if (oAuth2AuthHandler == null) + { + handler.handle(Future.failedFuture(new HttpException(SERVICE_UNAVAILABLE.code(), + "JWT authentication handler unavailable"))); + return; + } + + oAuth2AuthHandler.authenticate(context, authN -> { + if (authN.failed()) + { + handler.handle(Future.failedFuture(new HttpException(UNAUTHORIZED.code(), authN.cause()))); + return; + } + + User user = authN.result(); + JsonObject decodedToken = user.attributes().containsKey("accessToken") + ? user.attributes().getJsonObject("accessToken") + : user.attributes().getJsonObject("idToken"); + + if (decodedToken == null) + { + handler.handle(Future.failedFuture(new HttpException(UNAUTHORIZED.code(), + "Could not process decoded JWT token"))); + return; + } + + try + { + List<String> roles = roleProcessor.processRoles(decodedToken); + if (!roles.isEmpty()) + { + user.attributes().put(CASSANDRA_ROLES_ATTRIBUTE_NAME, String.join(CASSANDRA_ROLE_SPLITTER, roles)); + } + handler.handle(Future.succeededFuture(user)); + } + catch (Exception e) + { + LOGGER.debug("Error processing cassandra role from JWT token", e); + handler.handle(Future.failedFuture(new HttpException(UNAUTHORIZED.code(), + "Error processing cassandra role from token"))); + } + }); + } + + /** + * {@link NoOpAuthenticationProvider} is used in {@link ReloadingJwtAuthenticationHandler}. + * {@link ReloadingJwtAuthenticationHandler} delegates authenticating user to delegate handler. + * Hence it uses no op authentication provider + */ + protected static class NoOpAuthenticationProvider implements AuthenticationProvider + { + public static final NoOpAuthenticationProvider INSTANCE = new NoOpAuthenticationProvider(); + + private NoOpAuthenticationProvider() + { + } + + @Override + public void authenticate(JsonObject credentials, Handler<AsyncResult<User>> resultHandler) + { + resultHandler.handle(Future.succeededFuture()); + } + } + + /** + * Periodic task to generate {@link OAuth2AuthHandlerImpl} with refreshed configuration from + * {@link OpenIDConnectAuth} discover. + */ + private class OAuth2AuthHandlerGenerateTask implements PeriodicTask + { + public DurationSpec delay() Review Comment: ```suggestion @Override public DurationSpec delay() ``` ########## server/src/main/java/org/apache/cassandra/sidecar/acl/authentication/JwtRoleProcessorImpl.java: ########## @@ -0,0 +1,79 @@ +/* + * 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.authentication; + +import java.util.ArrayList; +import java.util.List; + +import io.vertx.core.json.JsonObject; +import org.apache.cassandra.sidecar.acl.IdentityToRoleCache; + +/** + * {@link JwtRoleProcessor} implementation. + */ +public class JwtRoleProcessorImpl implements JwtRoleProcessor +{ + private static final String SUB_KEY = "sub"; + private static final String IDENTITY_KEY = "identity"; + private static final String IDENTITIES_KEY = "identities"; + private final IdentityToRoleCache identityToRoleCache; + + public JwtRoleProcessorImpl(IdentityToRoleCache identityToRoleCache) + { + this.identityToRoleCache = identityToRoleCache; + } + + public List<String> processRoles(JsonObject decodedToken) + { + if (!decodedToken.containsKey(SUB_KEY) + && !decodedToken.containsKey(IDENTITY_KEY) + && !decodedToken.containsKey(IDENTITIES_KEY)) + { + return List.of(); + } + + String role = null; + if (decodedToken.containsKey(SUB_KEY)) + { + role = identityToRoleCache.get(decodedToken.getString(SUB_KEY)); + } + + if (decodedToken.containsKey(IDENTITY_KEY)) + { + role = identityToRoleCache.get(decodedToken.getString(IDENTITY_KEY)); + } + + if (role != null) + { + return List.of(role); + } + + List<String> identities = decodedToken.getJsonArray(IDENTITIES_KEY).getList(); + List<String> roles = new ArrayList<>(); + for (String identity : identities) + { + String roleFromIdentity = identityToRoleCache.get(identity); + if (roleFromIdentity != null) + { + roles.add(roleFromIdentity); + } + } + return roles; Review Comment: ```suggestion String role; if ((role = decodedToken.getString(IDENTITY_KEY)) != null) { return List.of(role); } if ((role = decodedToken.getString(SUB_KEY)) != null) { return List.of(role); } JsonArray identityKeyArray = decodedToken.getJsonArray(IDENTITIES_KEY); List<String> roles = new ArrayList<>(); if (identityKeyArray != null) { for (String identity : (List<String>) identityKeyArray.getList()) { String roleFromIdentity = identityToRoleCache.get(identity); if (roleFromIdentity != null) { roles.add(roleFromIdentity); } } } return List.copyOf(roles); ``` ########## server/src/test/java/org/apache/cassandra/sidecar/acl/authentication/ReloadingJwtAuthenticationHandlerTest.java: ########## @@ -0,0 +1,60 @@ +/* + * 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.authentication; + +import java.util.List; +import java.util.Map; + +import org.junit.jupiter.api.Test; + +import io.vertx.core.Vertx; +import io.vertx.ext.web.RoutingContext; +import org.apache.cassandra.sidecar.tasks.PeriodicTaskExecutor; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.doNothing; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +/** + * Test for {@link ReloadingJwtAuthenticationHandler} + */ +class ReloadingJwtAuthenticationHandlerTest +{ + Vertx vertx = Vertx.vertx(); Review Comment: close the resource after the test completes. ########## server/src/main/java/org/apache/cassandra/sidecar/acl/authentication/MutualTlsAuthenticationHandler.java: ########## @@ -54,6 +68,39 @@ public void authenticate(RoutingContext ctx, Handler<AsyncResult<User>> handler) .recover(cause -> { // converts any exception to unauthorized http exception throw new HttpException(HttpResponseStatus.UNAUTHORIZED.code(), cause); }) - .andThen(handler); + .andThen(authN-> { + if (authN.failed()) + { + handler.handle(Future.failedFuture(new HttpException(UNAUTHORIZED.code(), authN.cause()))); + return; + } + + List<String> identities = extractIdentities(authN.result()); + + if (identities.isEmpty()) + { + handler.handle(Future.failedFuture("Missing client identities")); Review Comment: maybe preserve the prior status code? ```suggestion handler.handle(Future.failedFuture(wrapHttpException(HttpResponseStatus.FORBIDDEN, "Client identities are missing"))); ``` -- 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-unsubscr...@cassandra.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: pr-unsubscr...@cassandra.apache.org For additional commands, e-mail: pr-h...@cassandra.apache.org