You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cassandra.apache.org by fr...@apache.org on 2025/01/20 00:09:13 UTC
(cassandra-sidecar) branch trunk updated: CASSSIDECAR-161: Add RBAC Authorization support in Sidecar (#165)
This is an automated email from the ASF dual-hosted git repository.
frankgh pushed a commit to branch trunk
in repository https://gitbox.apache.org/repos/asf/cassandra-sidecar.git
The following commit(s) were added to refs/heads/trunk by this push:
new 5a19e344 CASSSIDECAR-161: Add RBAC Authorization support in Sidecar (#165)
5a19e344 is described below
commit 5a19e3448038fa4b2e9f497ab94dbbe911f44c29
Author: Saranya Krishnakumar <sa...@apple.com>
AuthorDate: Sun Jan 19 16:09:08 2025 -0800
CASSSIDECAR-161: Add RBAC Authorization support in Sidecar (#165)
Patch by Saranya Krishnakumar, Raymond Welgosh; reviewed by Bernardo Botella, Venkata Harikrishna Nukala, Yifan Cai, Francisco Guerrero for CASSSIDECAR-161
Co-authored-by: Raymond Welgosh <ra...@gmail.com>
Co-authored-by: Saranya Krishnakumar <sa...@apple.com>
---
CHANGES.txt | 1 +
.../cassandra/sidecar/common/ApiEndpointsV1.java | 7 +-
conf/sidecar.yaml | 10 +
.../sidecar/db/schema/AbstractSchema.java | 1 +
.../apache/cassandra/sidecar/acl/AuthCache.java | 5 +
.../acl/authorization/AdminIdentityResolver.java | 63 ++++
.../AllowAllAuthorizationProvider.java | 81 ++++
.../AuthorizationParameterValidateHandler.java | 83 ++++
.../AuthorizationWithAdminBypassHandler.java | 72 ++++
.../acl/authorization/BasicPermissions.java | 66 ++++
.../acl/authorization/CassandraPermissions.java | 39 ++
.../acl/authorization/DomainAwarePermission.java | 82 ++++
.../sidecar/acl/authorization/Permission.java | 79 ++++
.../acl/authorization/RoleAuthorizationsCache.java | 119 ++++++
.../RoleBasedAuthorizationProvider.java | 92 +++++
.../acl/authorization/StandardPermission.java | 60 +++
.../sidecar/acl/authorization/SuperUserCache.java | 54 +++
.../acl/authorization/VariableAwareResource.java | 110 ++++++
.../sidecar/config/AccessControlConfiguration.java | 5 +
.../yaml/AccessControlConfigurationImpl.java | 21 +-
.../db/SidecarPermissionsDatabaseAccessor.java | 87 +++++
.../sidecar/db/SystemAuthDatabaseAccessor.java | 68 +++-
.../db/schema/SidecarRolePermissionsSchema.java | 89 +++++
.../sidecar/db/schema/SystemAuthSchema.java | 62 ++-
.../cassandra/sidecar/routes/AccessProtected.java} | 34 +-
.../routes/AccessProtectedRouteBuilder.java | 221 +++++++++++
.../routes/ConnectedClientStatsHandler.java | 23 +-
.../sidecar/routes/GossipInfoHandler.java | 15 +-
.../{RingHandler.java => KeyspaceRingHandler.java} | 32 +-
...hemaHandler.java => KeyspaceSchemaHandler.java} | 25 +-
.../sidecar/routes/ListOperationalJobsHandler.java | 14 +-
.../sidecar/routes/NodeDecommissionHandler.java | 15 +-
.../sidecar/routes/OperationalJobHandler.java | 14 +-
.../cassandra/sidecar/routes/RingHandler.java | 58 +--
.../cassandra/sidecar/routes/SchemaHandler.java | 90 +----
.../routes/StreamSSTableComponentHandler.java | 18 +-
.../routes/TokenRangeReplicaMapHandler.java | 15 +-
.../routes/cassandra/NodeSettingsHandler.java | 7 +-
.../sidecar/routes/cdc/ListCdcDirHandler.java | 14 +-
.../routes/cdc/StreamCdcSegmentHandler.java | 15 +-
.../routes/restore/AbortRestoreJobHandler.java | 17 +-
.../routes/restore/CreateRestoreJobHandler.java | 16 +-
.../routes/restore/CreateRestoreSliceHandler.java | 16 +-
.../routes/restore/RestoreJobProgressHandler.java | 15 +-
.../routes/restore/RestoreJobSummaryHandler.java | 16 +-
.../routes/restore/UpdateRestoreJobHandler.java | 16 +-
.../routes/snapshots/ClearSnapshotHandler.java | 16 +-
.../routes/snapshots/CreateSnapshotHandler.java | 16 +-
.../routes/snapshots/ListSnapshotHandler.java | 15 +-
.../sstableuploads/SSTableCleanupHandler.java | 16 +-
.../sstableuploads/SSTableImportHandler.java | 20 +-
.../sstableuploads/SSTableUploadHandler.java | 16 +-
.../cassandra/sidecar/server/MainModule.java | 356 ++++++++++++------
.../apache/cassandra/sidecar/utils/AuthUtils.java | 84 +++++
.../MutualTLSAuthenticationIntegrationTest.java | 11 +
.../acl/RoleBasedAuthorizationIntegrationTest.java | 418 +++++++++++++++++++++
.../locator/CqlSessionProviderIntegrationTest.java | 95 +----
.../testing/CassandraSidecarTestContext.java | 6 -
.../sidecar/testing/IntegrationTestBase.java | 67 ++--
.../sidecar/testing/IntegrationTestModule.java | 10 +-
.../testing/AbstractCassandraTestContext.java | 18 +-
.../{CassandraTestContext.java => AuthMode.java} | 34 +-
.../testing/CassandraIntegrationTest.java | 15 +
.../cassandra/testing/CassandraTestContext.java | 8 +-
.../cassandra/testing/CassandraTestTemplate.java | 90 ++++-
.../testing/ConfigurableCassandraTestContext.java | 7 +-
.../sidecar/acl/RoleAuthorizationsCacheTest.java | 259 +++++++++++++
.../MutualTLSAuthenticationHandlerTest.java | 7 +-
.../authorization/AdminIdentityResolverTest.java | 86 +++++
.../authorization/AllowAllAuthorizationTest.java | 74 ++++
.../authorization/AuthorizationHandlerTest.java | 51 +++
.../sidecar/acl/authorization/PermissionTest.java | 103 +++++
.../RoleBasedAuthorizationProviderTest.java | 110 ++++++
.../acl/authorization/SuperUserCacheTest.java | 128 +++++++
.../sidecar/config/SidecarConfigurationTest.java | 3 +
.../db/BasicPermissionsDatabaseAccessorTest.java | 80 ++++
.../cassandra/sidecar/db/SidecarSchemaTest.java | 14 +-
.../sidecar/db/SystemAuthDatabaseAccessorTest.java | 4 +-
.../cassandra/sidecar/db/SystemAuthSchemaTest.java | 12 +-
.../routes/AccessProtectedRouteBuilderTest.java | 89 +++++
.../cassandra/sidecar/server/ServerTest.java | 10 +
.../config/sidecar_multiple_instances.yaml | 2 +
.../config/sidecar_unrecognized_authorizer.yaml | 122 ++++++
83 files changed, 4063 insertions(+), 471 deletions(-)
diff --git a/CHANGES.txt b/CHANGES.txt
index fa5eb0bd..357d3374 100644
--- a/CHANGES.txt
+++ b/CHANGES.txt
@@ -1,5 +1,6 @@
1.0.0
-----
+ * Add RBAC Authorization support in Sidecar (CASSSIDECAR-161)
* Standardize configuration for duration units (CASSSIDECAR-186)
* Adds sidecar endpoint for node decommissioning operation (CASSANDRASC-151)
* Rename field in ListCdcSegmentsResponse (CASSSIDECAR-184)
diff --git a/client-common/src/main/java/org/apache/cassandra/sidecar/common/ApiEndpointsV1.java b/client-common/src/main/java/org/apache/cassandra/sidecar/common/ApiEndpointsV1.java
index e608913e..ebe39a51 100644
--- a/client-common/src/main/java/org/apache/cassandra/sidecar/common/ApiEndpointsV1.java
+++ b/client-common/src/main/java/org/apache/cassandra/sidecar/common/ApiEndpointsV1.java
@@ -32,8 +32,10 @@ public final class ApiEndpointsV1
public static final String NATIVE = "/native";
public static final String JMX = "/jmx";
- public static final String KEYSPACE_PATH_PARAM = ":keyspace";
- public static final String TABLE_PATH_PARAM = ":table";
+ public static final String KEYSPACE = "keyspace";
+ public static final String TABLE = "table";
+ public static final String KEYSPACE_PATH_PARAM = ":" + KEYSPACE;
+ public static final String TABLE_PATH_PARAM = ":" + TABLE;
public static final String SNAPSHOT_PATH_PARAM = ":snapshot";
public static final String COMPONENT_PATH_PARAM = ":component";
public static final String INDEX_PATH_PARAM = ":index";
@@ -126,6 +128,7 @@ public final class ApiEndpointsV1
public static final String LIST_OPERATIONAL_JOBS_ROUTE = API_V1 + CASSANDRA + OPERATIONAL_JOBS;
public static final String OPERATIONAL_JOB_ROUTE = API_V1 + CASSANDRA + PER_OPERATIONAL_JOB;
public static final String NODE_DECOMMISSION_ROUTE = API_V1 + CASSANDRA + "/operations/decommission";
+
private ApiEndpointsV1()
{
throw new IllegalStateException(getClass() + " is a constants container and shall not be instantiated");
diff --git a/conf/sidecar.yaml b/conf/sidecar.yaml
index a20ac2d8..8bd5ae30 100644
--- a/conf/sidecar.yaml
+++ b/conf/sidecar.yaml
@@ -175,6 +175,16 @@ access_control:
#
# other options are, io.vertx.ext.auth.mtls.impl.SpiffeIdentityExtractor.
certificate_identity_extractor: org.apache.cassandra.sidecar.acl.authentication.CassandraIdentityExtractor
+ authorizer:
+ # Authorization backend, implementing io.vertx.ext.auth.authorization.AuthorizationProvider; used to
+ # provide permissions a user holds.
+ # Out of the box, Cassandra Sidecar provides
+ # org.apache.cassandra.sidecar.acl.authorization.{AllowAllAuthorizationProvider, RoleBasedAuthorizationProvider}.
+ #
+ # - AllowAllAuthorizationProvider allows any action to any user - use it to disable authorization.
+ # - RoleBasedAuthorizationProvider validates role associated with authenticated user has permission
+ # for resource it accesses.
+ - class_name: org.apache.cassandra.sidecar.acl.authorization.AllowAllAuthorizationProvider
# Identities that are authenticated and authorized.
admin_identities:
# - spiffe://authorized/admin/identities
diff --git a/server-common/src/main/java/org/apache/cassandra/sidecar/db/schema/AbstractSchema.java b/server-common/src/main/java/org/apache/cassandra/sidecar/db/schema/AbstractSchema.java
index 7b961d31..3ba5a7d4 100644
--- a/server-common/src/main/java/org/apache/cassandra/sidecar/db/schema/AbstractSchema.java
+++ b/server-common/src/main/java/org/apache/cassandra/sidecar/db/schema/AbstractSchema.java
@@ -80,6 +80,7 @@ public abstract class AbstractSchema
}
prepareStatements(session);
+ logger.debug("{} is initialized!", this.getClass().getSimpleName());
return true;
}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/AuthCache.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/AuthCache.java
index 9920e7eb..a2f6a4b0 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/acl/AuthCache.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/AuthCache.java
@@ -33,6 +33,7 @@ import io.vertx.core.eventbus.EventBus;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.concurrent.TaskExecutorPool;
import org.apache.cassandra.sidecar.config.CacheConfiguration;
+import org.apache.cassandra.sidecar.exceptions.SchemaUnavailableException;
import org.jetbrains.annotations.VisibleForTesting;
import static org.apache.cassandra.sidecar.server.SidecarServerEvents.ON_SIDECAR_SCHEMA_INITIALIZED;
@@ -163,6 +164,10 @@ public abstract class AuthCache<K, V>
{
cache.putAll(bulkLoadFunction.get());
}
+ catch (SchemaUnavailableException sue)
+ {
+ LOGGER.warn("system_auth schema is unavailable. Skip warming up cache", sue);
+ }
catch (Exception e)
{
LOGGER.warn("Unexpected error encountered during pre-warming of cache={} ", name, e);
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AdminIdentityResolver.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AdminIdentityResolver.java
new file mode 100644
index 00000000..1f4863d2
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AdminIdentityResolver.java
@@ -0,0 +1,63 @@
+/*
+ * 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.Set;
+
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.acl.IdentityToRoleCache;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+
+/**
+ * Evaluates if provided identity is an admin identity.
+ */
+@Singleton
+public class AdminIdentityResolver
+{
+ private final IdentityToRoleCache identityToRoleCache;
+ private final SuperUserCache superUserCache;
+ private final Set<String> adminIdentities;
+
+ @Inject
+ public AdminIdentityResolver(IdentityToRoleCache identityToRoleCache,
+ SuperUserCache superUserCache,
+ SidecarConfiguration sidecarConfiguration)
+ {
+ this.identityToRoleCache = identityToRoleCache;
+ this.superUserCache = superUserCache;
+ this.adminIdentities = sidecarConfiguration.accessControlConfiguration().adminIdentities();
+ }
+
+ public boolean isAdmin(String identity)
+ {
+ if (adminIdentities.contains(identity))
+ {
+ return true;
+ }
+
+ String role = identityToRoleCache.get(identity);
+ if (role == null)
+ {
+ return false;
+ }
+ // Cassandra superusers have admin privileges
+ return superUserCache.isSuperUser(role);
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AllowAllAuthorizationProvider.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AllowAllAuthorizationProvider.java
new file mode 100644
index 00000000..fd21dc58
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AllowAllAuthorizationProvider.java
@@ -0,0 +1,81 @@
+/*
+ * 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 io.vertx.core.AsyncResult;
+import io.vertx.core.Future;
+import io.vertx.core.Handler;
+import io.vertx.ext.auth.User;
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.auth.authorization.AuthorizationContext;
+import io.vertx.ext.auth.authorization.AuthorizationProvider;
+
+/**
+ * {@link AuthorizationProvider} implementation to allow all requests regardless of authorizations user holds.
+ */
+public class AllowAllAuthorizationProvider implements AuthorizationProvider
+{
+ final Authorization authorization;
+
+ public AllowAllAuthorizationProvider()
+ {
+ // Authorization that always allows
+ authorization = new Authorization()
+ {
+ @Override
+ public boolean match(AuthorizationContext context)
+ {
+ return true;
+ }
+
+ @Override
+ public boolean verify(Authorization authorization)
+ {
+ return true;
+ }
+ };
+ }
+
+ /**
+ * @return unique id representing {@code AllowAllAuthorizationProvider}
+ */
+ @Override
+ public String getId()
+ {
+ return "AllowAll";
+ }
+
+ @Override
+ public void getAuthorizations(User user, Handler<AsyncResult<Void>> handler)
+ {
+ getAuthorizations(user).onComplete(handler);
+ }
+
+ @Override
+ public Future<Void> getAuthorizations(User user)
+ {
+ if (user == null)
+ {
+ return Future.failedFuture("User cannot be null");
+ }
+
+ user.authorizations().add(getId(), authorization);
+ return Future.succeededFuture();
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationParameterValidateHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationParameterValidateHandler.java
new file mode 100644
index 00000000..ff3a4b9b
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationParameterValidateHandler.java
@@ -0,0 +1,83 @@
+/*
+ * 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 com.google.inject.Inject;
+import com.google.inject.Singleton;
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.common.server.data.Name;
+import org.apache.cassandra.sidecar.common.server.data.QualifiedTableName;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.RoutingContextUtils;
+import org.apache.cassandra.sidecar.snapshots.SnapshotPathBuilder;
+import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+
+/**
+ * Simple handler that extracts authorization parameters keyspace/table parameters from the path, validates them,
+ * and then adds them to the context.
+ */
+@Singleton
+public class AuthorizationParameterValidateHandler extends AbstractHandler<QualifiedTableName>
+{
+ private final SnapshotPathBuilder snapshotPathBuilder;
+
+ /**
+ * Constructs a handler with the provided {@code metadataFetcher}
+ *
+ * @param metadataFetcher the interface to retrieve instance metadata
+ * @param executorPools the executor pools for blocking executions
+ * @param validator a validator instance to validate Cassandra-specific input
+ */
+ @Inject
+ protected AuthorizationParameterValidateHandler(InstanceMetadataFetcher metadataFetcher,
+ ExecutorPools executorPools,
+ CassandraInputValidator validator,
+ SnapshotPathBuilder snapshotPathBuilder)
+ {
+ super(metadataFetcher, executorPools, validator);
+ this.snapshotPathBuilder = snapshotPathBuilder;
+ }
+
+ @Override
+ protected void handleInternal(RoutingContext context,
+ HttpServerRequest httpRequest,
+ String host,
+ SocketAddress remoteAddress,
+ QualifiedTableName qualifiedTableName)
+ {
+ RoutingContextUtils.put(context, RoutingContextUtils.SC_QUALIFIED_TABLE_NAME, qualifiedTableName);
+ }
+
+ @Override
+ protected QualifiedTableName extractParamsOrThrow(RoutingContext context)
+ {
+ Name tableName = null;
+ String tableNameParam = context.pathParam(TABLE_PATH_PARAM);
+ if (tableNameParam != null)
+ {
+ // Remove the tableId for routes that have the tableId as part of the path parameter
+ tableName = validator.validateTableName(snapshotPathBuilder.maybeRemoveTableId(tableNameParam));
+ }
+ return new QualifiedTableName(keyspace(context, false), tableName);
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationWithAdminBypassHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationWithAdminBypassHandler.java
new file mode 100644
index 00000000..26761e2d
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationWithAdminBypassHandler.java
@@ -0,0 +1,72 @@
+/*
+ * 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 io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.web.RoutingContext;
+import io.vertx.ext.web.handler.HttpException;
+import io.vertx.ext.web.handler.impl.AuthorizationHandlerImpl;
+
+import static org.apache.cassandra.sidecar.utils.AuthUtils.extractIdentities;
+
+/**
+ * Verifies user has required authorizations. Allows admin identities to bypass authorization checks.
+ */
+public class AuthorizationWithAdminBypassHandler extends AuthorizationHandlerImpl
+{
+ private final AuthorizationParameterValidateHandler authZParameterValidateHandler;
+ private final AdminIdentityResolver adminIdentityResolver;
+
+ public AuthorizationWithAdminBypassHandler(AuthorizationParameterValidateHandler authZParameterValidateHandler,
+ AdminIdentityResolver adminIdentityResolver,
+ Authorization authorization)
+ {
+ super(authorization);
+ this.authZParameterValidateHandler = authZParameterValidateHandler;
+ this.adminIdentityResolver = adminIdentityResolver;
+ }
+
+ @Override
+ public void handle(RoutingContext ctx)
+ {
+ authZParameterValidateHandler.handle(ctx);
+ if (ctx.failed()) // failed due to validation
+ {
+ return;
+ }
+
+ List<String> identities = extractIdentities(ctx.user());
+ if (identities.isEmpty())
+ {
+ throw new HttpException(HttpResponseStatus.FORBIDDEN.code(), "Client identities are missing");
+ }
+
+ // Admin identities bypass route specific authorization checks
+ if (identities.stream().anyMatch(adminIdentityResolver::isAdmin))
+ {
+ ctx.next();
+ return;
+ }
+
+ super.handle(ctx);
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/BasicPermissions.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/BasicPermissions.java
new file mode 100644
index 00000000..8074bca3
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/BasicPermissions.java
@@ -0,0 +1,66 @@
+/*
+ * 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;
+
+/**
+ * Basic permissions are the building blocks of the permission-ing system in Sidecar. It offers more granular
+ * permissions on specific targets which are listed here. The majority of Sidecar permissions are represented in
+ * format {@code domain}:{@code action}.
+ * <p>
+ * For example, the SNAPSHOT:CREATE permission, CREATE action is allowed for the SNAPSHOT domain. Sample actions are
+ * CREATE, READ, EDIT, DELETE, IMPORT, UPLOAD, START etc.
+ * <p>
+ * Domain aware permissions are supported with ':' wildcard parts divider. Wildcard token '*' is restricted
+ * to avoid unpredictable behavior.
+ * <p>
+ * Some examples of domain aware permissions are:
+ * - SNAPSHOT:CREATE,READ,DELETE allows SNAPSHOT:CREATE, SNAPSHOT:READ and SNAPSHOT:DELETE.
+ */
+public class BasicPermissions
+{
+ // SSTable staging related permissions
+ public static final Permission UPLOAD_STAGED_SSTABLE = new DomainAwarePermission("STAGED_SSTABLE:UPLOAD");
+ public static final Permission IMPORT_STAGED_SSTABLE = new DomainAwarePermission("STAGED_SSTABLE:IMPORT");
+ public static final Permission DELETE_STAGED_SSTABLE = new DomainAwarePermission("STAGED_SSTABLE:DELETE");
+
+ // snapshot related permissions
+ public static final Permission CREATE_SNAPSHOT = new DomainAwarePermission("SNAPSHOT:CREATE");
+ public static final Permission READ_SNAPSHOT = new DomainAwarePermission("SNAPSHOT:READ");
+ public static final Permission DELETE_SNAPSHOT = new DomainAwarePermission("SNAPSHOT:DELETE");
+ public static final Permission STREAM_SNAPSHOT = new DomainAwarePermission("SNAPSHOT:STREAM");
+
+ // restore job related permissions
+ public static final Permission CREATE_RESTORE_JOB = new DomainAwarePermission("RESTORE_JOB:CREATE");
+ public static final Permission READ_RESTORE_JOB = new DomainAwarePermission("RESTORE_JOB:READ");
+ public static final Permission EDIT_RESTORE_JOB = new DomainAwarePermission("RESTORE_JOB:EDIT");
+ public static final Permission DELETE_RESTORE_JOB = new DomainAwarePermission("RESTORE_JOB:DELETE");
+
+ // cdc related permissions
+ public static final Permission CDC = new StandardPermission("CDC");
+
+ // sidecar operation related permissions
+ public static final Permission READ_OPERATIONAL_JOB = new DomainAwarePermission("OPERATIONAL_JOB:READ");
+ public static final Permission DECOMMISSION_NODE = new DomainAwarePermission("NODE:DECOMMISSION");
+
+ // cassandra cluster related permissions
+ public static final Permission READ_SCHEMA = new DomainAwarePermission("SCHEMA:READ");
+ public static final Permission READ_GOSSIP = new DomainAwarePermission("GOSSIP:READ");
+ public static final Permission READ_RING = new DomainAwarePermission("RING:READ");
+ public static final Permission READ_TOPOLOGY = new DomainAwarePermission("TOPOLOGY:READ");
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CassandraPermissions.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CassandraPermissions.java
new file mode 100644
index 00000000..d6d67f62
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/CassandraPermissions.java
@@ -0,0 +1,39 @@
+/*
+ * 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;
+
+/**
+ * Cassandra permissions allowed. These map to Cassandra permissions in
+ * <a href="https://github.com/apache/cassandra/blob/trunk/src/java/org/apache/cassandra/auth/Permission.java">
+ * org.apache.cassandra.auth.Permission</a>
+ * under the Cassandra codebase.
+ */
+public class CassandraPermissions
+{
+ public static final Permission CREATE = new StandardPermission("CREATE");
+ public static final Permission ALTER = new StandardPermission("ALTER");
+ public static final Permission DROP = new StandardPermission("DROP");
+ public static final Permission SELECT = new StandardPermission("SELECT");
+ public static final Permission MODIFY = new StandardPermission("MODIFY");
+ public static final Permission AUTHORIZE = new StandardPermission("AUTHORIZE");
+ public static final Permission DESCRIBE = new StandardPermission("DESCRIBE");
+ public static final Permission EXECUTE = new StandardPermission("EXECUTE");
+ public static final Permission UNMASK = new StandardPermission("UNMASK");
+ public static final Permission SELECT_MASKED = new StandardPermission("SELECT_MASKED");
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/DomainAwarePermission.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/DomainAwarePermission.java
new file mode 100644
index 00000000..745fee21
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/DomainAwarePermission.java
@@ -0,0 +1,82 @@
+/*
+ * 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.Arrays;
+
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.auth.authorization.WildcardPermissionBasedAuthorization;
+import io.vertx.ext.auth.authorization.impl.WildcardPermissionBasedAuthorizationImpl;
+
+import static org.apache.cassandra.sidecar.common.utils.StringUtils.isNotEmpty;
+
+/**
+ * Domain aware permissions allow grouping allowed permissions for a domain. They can be represented with
+ * ':' wildcard parts divider. Wildcard sub parts divider token ',' can be used to group actions for a domain.
+ * Wildcard token '*' is restricted in {@link DomainAwarePermission} to avoid unpredictable behaviour. Majority
+ * of sidecar permissions are represented in format {@code domain}:{@code action}.
+ * <p>
+ * Example, with SNAPSHOT:CREATE permission, CREATE action is allowed for the SNAPSHOT domain. Sample actions are
+ * CREATE, READ, EDIT, UPDATE, DELETE, IMPORT, UPLOAD, START, ABORT etc.
+ * <p>
+ * Some examples of wildcard permissions are:
+ * - SNAPSHOT:CREATE,READ,DELETE allows SNAPSHOT:CREATE, SNAPSHOT:READ and SNAPSHOT:DELETE.
+ */
+public class DomainAwarePermission extends StandardPermission
+{
+ public static final String WILDCARD_TOKEN = "*";
+ public static final String WILDCARD_PART_DIVIDER_TOKEN = ":";
+
+ public DomainAwarePermission(String name)
+ {
+ super(name);
+ validate(name);
+ }
+
+ private void validate(String name)
+ {
+ if (name.contains(WILDCARD_TOKEN))
+ {
+ throw new IllegalArgumentException("DomainAwarePermission can not have " + WILDCARD_TOKEN +
+ " to avoid unpredictable behavior");
+ }
+ if (!name.contains(WILDCARD_PART_DIVIDER_TOKEN))
+ {
+ throw new IllegalArgumentException("DomainAwarePermission must have " + WILDCARD_PART_DIVIDER_TOKEN +
+ " to divide domain and action");
+ }
+ String[] wildcardParts = name.split(WILDCARD_PART_DIVIDER_TOKEN);
+ boolean hasEmptyParts = Arrays.stream(wildcardParts).anyMatch(String::isEmpty);
+ if (wildcardParts.length == 0 || hasEmptyParts)
+ {
+ throw new IllegalArgumentException("DomainAwarePermission parts can not be empty");
+ }
+ }
+
+ @Override
+ public Authorization toAuthorization(String resource)
+ {
+ WildcardPermissionBasedAuthorization authorization = new WildcardPermissionBasedAuthorizationImpl(name);
+ if (isNotEmpty(resource))
+ {
+ authorization.setResource(resource);
+ }
+ return authorization;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/Permission.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/Permission.java
new file mode 100644
index 00000000..f8c358bf
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/Permission.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.authorization;
+
+import java.util.List;
+
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.auth.authorization.OrAuthorization;
+import org.jetbrains.annotations.VisibleForTesting;
+
+/**
+ * Represents a permission that can be granted to a user
+ */
+public interface Permission
+{
+ /**
+ * @return name of permission
+ */
+ String name();
+
+ /**
+ * @return {@link Authorization} created from permission. Most sidecar endpoints require a resource.
+ * This method is currently only used in testing
+ */
+ @VisibleForTesting
+ default Authorization toAuthorization()
+ {
+ // When resource is empty, it is ignored
+ return toAuthorization("");
+ }
+
+ /**
+ * User authorization created with resource
+ *
+ * @param resource resource set for authorization matching
+ * @return {@link Authorization} created from permission for a resource.
+ */
+ Authorization toAuthorization(String resource);
+
+ /**
+ * User authorization created with eligible resources.
+ *
+ * @param eligibleResources authorization is created with all the eligible resources, so that if user holds grant
+ * for <b>any</b> of the eligibleResources, then they are granted access
+ * @return {@link Authorization} created with given eligibleResources, when empty list is passed
+ * {@link Authorization} is created with just permission {@link #name}
+ */
+ default Authorization toAuthorization(List<String> eligibleResources)
+ {
+ if (eligibleResources == null || eligibleResources.isEmpty())
+ {
+ // When resource is empty, it is ignored
+ return toAuthorization("");
+ }
+
+ OrAuthorization orAuthorization = OrAuthorization.create();
+ for (String resource : eligibleResources)
+ {
+ orAuthorization.addAuthorization(toAuthorization(resource));
+ }
+ return orAuthorization;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/RoleAuthorizationsCache.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/RoleAuthorizationsCache.java
new file mode 100644
index 00000000..7b04d2d3
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/RoleAuthorizationsCache.java
@@ -0,0 +1,119 @@
+/*
+ * 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.Collections;
+import java.util.Map;
+import java.util.Set;
+
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import io.vertx.core.Vertx;
+import io.vertx.ext.auth.authorization.Authorization;
+import org.apache.cassandra.sidecar.acl.AuthCache;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.SidecarPermissionsDatabaseAccessor;
+import org.apache.cassandra.sidecar.db.SystemAuthDatabaseAccessor;
+import org.apache.cassandra.sidecar.db.schema.SidecarSchema;
+
+/**
+ * Caches role and authorizations held by it. Entries from system_auth.role_permissions table in Cassandra and
+ * sidecar_internal.role_permissions_v1 table are processed into authorizations and cached here. All table entries are
+ * stored against a unique cache key. Caching against UNIQUE_CACHE_ENTRY is done to make sure new entries in the table
+ * are picked up during cache refreshes.
+ */
+@Singleton
+public class RoleAuthorizationsCache extends AuthCache<String, Map<String, Set<Authorization>>>
+{
+ private static final String NAME = "role_permissions_cache";
+ protected static final String UNIQUE_CACHE_ENTRY = "unique_cache_entry_key";
+
+ @Inject
+ public RoleAuthorizationsCache(Vertx vertx,
+ ExecutorPools executorPools,
+ SidecarConfiguration sidecarConfiguration,
+ SidecarSchema sidecarSchema,
+ SystemAuthDatabaseAccessor systemAuthDatabaseAccessor,
+ SidecarPermissionsDatabaseAccessor sidecarPermissionsDatabaseAccessor)
+ {
+ super(NAME,
+ vertx,
+ executorPools,
+ k -> loadAuthorizations(systemAuthDatabaseAccessor,
+ sidecarSchema,
+ sidecarPermissionsDatabaseAccessor),
+ () -> Collections.singletonMap(UNIQUE_CACHE_ENTRY,
+ loadAuthorizations(systemAuthDatabaseAccessor,
+ sidecarSchema,
+ sidecarPermissionsDatabaseAccessor)),
+ sidecarConfiguration.accessControlConfiguration().permissionCacheConfiguration());
+ }
+
+ /**
+ * {@code get} retrieves all role to authorizations mapping maintained in this cache.
+ *
+ * @param ignored key for retrieval. Cache always contains one entry stored against unique_cache_entry_key,
+ * hence key is ignored
+ * @return Cache entry stored against unique_cache_entry_key
+ */
+ @Override
+ public Map<String, Set<Authorization>> get(String ignored)
+ {
+ // RoleAuthorizationsCache stores all entries of role to authorizations mappings against a single key,
+ // which is unique_cache_entry_key. This is to refresh and pick up all entries and their changes from
+ // Cassandra's role_permissions table and Sidecar role_permissions_v1 table. Hence during cache retrieval
+ // key is ignored and entry stored against unique_cache_entry_key is returned
+ return super.get(UNIQUE_CACHE_ENTRY);
+ }
+
+ /**
+ * Provides authorizations given user's role.
+ *
+ * @param role a role a user holds
+ * @return a {@code Set} of {@link Authorization} a role holds.
+ */
+ public Set<Authorization> getAuthorizations(String role)
+ {
+ Map<String, Set<Authorization>> roleAuthorizations = get(UNIQUE_CACHE_ENTRY);
+ return roleAuthorizations != null ? roleAuthorizations.get(role) : Collections.emptySet();
+ }
+
+ private static Map<String, Set<Authorization>> loadAuthorizations(SystemAuthDatabaseAccessor systemAuthDatabaseAccessor,
+ SidecarSchema sidecarSchema,
+ SidecarPermissionsDatabaseAccessor sidecarPermissionsDatabaseAccessor)
+ {
+ Map<String, Set<Authorization>> roleAuthorizations = systemAuthDatabaseAccessor.findAllRolesAndPermissions();
+
+ if (sidecarSchema.isInitialized())
+ {
+ Map<String, Set<Authorization>> sidecarAuthorizations
+ = sidecarPermissionsDatabaseAccessor.rolesToAuthorizations();
+
+ // merge authorizations from Cassandra and Sidecar tables
+ sidecarAuthorizations.forEach((role, authorizations) -> {
+ roleAuthorizations.merge(role, authorizations, (existingAuthorizations, newAuthorizations) -> {
+ existingAuthorizations.addAll(newAuthorizations);
+ return existingAuthorizations;
+ });
+ });
+ }
+ return roleAuthorizations;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationProvider.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationProvider.java
new file mode 100644
index 00000000..40234b9b
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationProvider.java
@@ -0,0 +1,92 @@
+/*
+ * 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.Set;
+
+import io.vertx.core.AsyncResult;
+import io.vertx.core.Future;
+import io.vertx.core.Handler;
+import io.vertx.ext.auth.User;
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.auth.authorization.AuthorizationProvider;
+import org.apache.cassandra.sidecar.acl.IdentityToRoleCache;
+
+import static org.apache.cassandra.sidecar.utils.AuthUtils.extractIdentities;
+
+/**
+ * Provides authorizations based on user's role. Extracts permissions user holds from Cassandra's
+ * system_auth.role_permissions table and from Sidecar's sidecar_internal.role_permissions_v1 table and sets
+ * them in user.
+ */
+public class RoleBasedAuthorizationProvider implements AuthorizationProvider
+{
+ private final IdentityToRoleCache identityToRoleCache;
+ private final RoleAuthorizationsCache roleAuthorizationsCache;
+
+ public RoleBasedAuthorizationProvider(IdentityToRoleCache identityToRoleCache,
+ RoleAuthorizationsCache roleAuthorizationsCache)
+ {
+ this.identityToRoleCache = identityToRoleCache;
+ this.roleAuthorizationsCache = roleAuthorizationsCache;
+ }
+
+ @Override
+ public String getId()
+ {
+ return "RoleBasedAccessControl";
+ }
+
+ @Override
+ public void getAuthorizations(User user, Handler<AsyncResult<Void>> handler)
+ {
+ getAuthorizations(user).onComplete(handler);
+ }
+
+ @Override
+ public Future<Void> getAuthorizations(User user)
+ {
+ List<String> identities = extractIdentities(user);
+
+ if (identities.isEmpty())
+ {
+ return Future.failedFuture("Missing client identities");
+ }
+
+ Set<Authorization> authorizations = new HashSet<>();
+ for (String identity : identities)
+ {
+ String role = identityToRoleCache.get(identity);
+ if (role == null)
+ {
+ continue;
+ }
+ // when entries in cache are not found, null is returned. We can not add null in user.authorizations()
+ Set<Authorization> roleAuthorizations = roleAuthorizationsCache.getAuthorizations(role);
+ if (roleAuthorizations != null)
+ {
+ authorizations.addAll(roleAuthorizations);
+ }
+ }
+ user.authorizations().add(getId(), authorizations);
+ return Future.succeededFuture();
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/StandardPermission.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/StandardPermission.java
new file mode 100644
index 00000000..65f50200
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/StandardPermission.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.authorization;
+
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.auth.authorization.PermissionBasedAuthorization;
+
+import static org.apache.cassandra.sidecar.common.utils.StringUtils.isNotEmpty;
+import static org.apache.cassandra.sidecar.common.utils.StringUtils.isNullOrEmpty;
+
+/**
+ * {@link StandardPermission} needs an exact match between permission. If resource is set, exact match between
+ * resources if also required.
+ */
+public class StandardPermission implements Permission
+{
+ protected final String name;
+
+ public StandardPermission(String name)
+ {
+ if (isNullOrEmpty(name))
+ {
+ throw new IllegalArgumentException("Permission name can not be null or empty");
+ }
+ this.name = name;
+ }
+
+ @Override
+ public String name()
+ {
+ return name;
+ }
+
+ @Override
+ public Authorization toAuthorization(String resource)
+ {
+ PermissionBasedAuthorization authorization = PermissionBasedAuthorization.create(name);
+ if (isNotEmpty(resource))
+ {
+ authorization.setResource(resource);
+ }
+ return authorization;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/SuperUserCache.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/SuperUserCache.java
new file mode 100644
index 00000000..2769688c
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/SuperUserCache.java
@@ -0,0 +1,54 @@
+/*
+ * 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 com.google.inject.Inject;
+import io.vertx.core.Vertx;
+import org.apache.cassandra.sidecar.acl.AuthCache;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.SystemAuthDatabaseAccessor;
+
+/**
+ * Caches superuser status of cassandra roles.
+ */
+public class SuperUserCache extends AuthCache<String, Boolean>
+{
+ private static final String NAME = "super_user_cache";
+
+ @Inject
+ public SuperUserCache(Vertx vertx,
+ ExecutorPools executorPools,
+ SidecarConfiguration sidecarConfiguration,
+ SystemAuthDatabaseAccessor systemAuthDatabaseAccessor)
+ {
+ super(NAME,
+ vertx,
+ executorPools,
+ systemAuthDatabaseAccessor::isSuperUser,
+ systemAuthDatabaseAccessor::findAllRolesToSuperuserStatus,
+ sidecarConfiguration.accessControlConfiguration().permissionCacheConfiguration());
+ }
+
+ public boolean isSuperUser(String role)
+ {
+ Boolean superUserStatus = get(role);
+ return superUserStatus != null && superUserStatus;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/VariableAwareResource.java b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/VariableAwareResource.java
new file mode 100644
index 00000000..61df9eee
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/acl/authorization/VariableAwareResource.java
@@ -0,0 +1,110 @@
+/*
+ * 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.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.stream.Collectors;
+
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.KEYSPACE;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.TABLE;
+
+/**
+ * Resources sidecar can expect permissions for. This list is not exhaustive.
+ */
+public enum VariableAwareResource
+{
+ /**
+ * Signifies the Cassandra cluster resource. For example, to determine whether you have access to retrieve
+ * basic Cassandra ring, gossip, or other Cassandra-related information.
+ */
+ CLUSTER("cluster"),
+
+ /**
+ * Signifies the Cassandra Sidecar operations resource which allows a Sidecar operator with sufficient permissions
+ * run operations against both Cassandra Sidecar and Cassandra clusters that Sidecar is managing.
+ */
+ OPERATION("operation"),
+
+ // data resources
+
+ /**
+ * Cassandra stores data resource in the format data, data/keyspace or data/keyspace_name/table_name within
+ * the role_permissions table. A similar format is followed for storing data resources in sidecar permissions
+ * table role_permissions_v1. Hence, sidecar endpoints expect data resources to be provided in format
+ * data/keyspace_name/table_name.
+ * <p>
+ * In this context, curly braces are used to denote variable parts of the resource. For e.g., when permissions are
+ * checked for resource data/{keyspace} in an endpoint, the part within the curly braces ({keyspace})
+ * represents a placeholder for the actual keyspace name provided as a path parameter. For more context refer to
+ * io.vertx.ext.auth.authorization.impl.VariableAwareExpression
+ * <p>
+ * During the permission matching process, the placeholder {keyspace} is resolved to the actual keyspace
+ * being accessed by the endpoint. For e.g. data/{keyspace} resolves to data/university if the keyspace is
+ * "university".
+ * <p>
+ * User permissions are then extracted from both Cassandra and sidecar role permissions tables for
+ * the resolved resource and are matched against the expected permissions set defined in the endpoint's handler.
+ */
+ DATA("data"),
+
+ DATA_WITH_KEYSPACE(String.format("data/{%s}", KEYSPACE),
+ // can expand to DATA
+ DATA),
+
+ // TODO remove this hack once VariableAwareExpression bug is fixed
+ // VariableAwareExpression in vertx-auth-common package has a bug during String.substring() call, hence
+ // we cannot set resources that do not end in curly braces (e.g. data/keyspace/*) in
+ // PermissionBasedAuthorizationImpl or WildcardPermissionBasedAuthorizationImpl. data/{%s}/{TABLE_WILDCARD} treats
+ // TABLE_WILDCARD as a variable. This hack allows to read resource level permissions that could be set for all
+ // tables through data/<keyspace_name>/*. Bug should be fixed in 4.5.12
+ // Note: DATA_WITH_KEYSPACE_ALL_TABLES resource comprises all tables under the keyspace excluding the keyspace itself
+ DATA_WITH_KEYSPACE_ALL_TABLES(String.format("data/{%s}/{TABLE_WILDCARD}", KEYSPACE),
+ // can expand to DATA, DATA_WITH_KEYSPACE
+ DATA, DATA_WITH_KEYSPACE),
+
+ DATA_WITH_KEYSPACE_TABLE(String.format("data/{%s}/{%s}", KEYSPACE, TABLE),
+ // can expand to DATA, DATA_WITH_KEYSPACE and DATA_WITH_KEYSPACE_ALL_TABLES
+ DATA, DATA_WITH_KEYSPACE, DATA_WITH_KEYSPACE_ALL_TABLES);
+
+ private final String resource;
+ private final List<String> expandedResources;
+
+ VariableAwareResource(String resource, VariableAwareResource... expansions)
+ {
+ this.resource = resource;
+ List<String> expandedResources = Arrays.stream(expansions).map(r -> r.resource).collect(Collectors.toList());
+ expandedResources.add(resource);
+ this.expandedResources = Collections.unmodifiableList(expandedResources);
+ }
+
+ public String resource()
+ {
+ return resource;
+ }
+
+ /**
+ * @return the list of expanded resources eligible to match the resources a user holds
+ */
+ public List<String> expandedResources()
+ {
+ return expandedResources;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/config/AccessControlConfiguration.java b/server/src/main/java/org/apache/cassandra/sidecar/config/AccessControlConfiguration.java
index 6850a825..8456d700 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/config/AccessControlConfiguration.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/config/AccessControlConfiguration.java
@@ -37,6 +37,11 @@ public interface AccessControlConfiguration
*/
List<ParameterizedClassConfiguration> authenticatorsConfiguration();
+ /**
+ * @return configuration needed for setting up authorizer in Sidecar
+ */
+ ParameterizedClassConfiguration authorizerConfiguration();
+
/**
* @return A {@code Set<String>} of administrative identities that are always authenticated and authorized
*/
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/config/yaml/AccessControlConfigurationImpl.java b/server/src/main/java/org/apache/cassandra/sidecar/config/yaml/AccessControlConfigurationImpl.java
index 07f5cab9..bca14fca 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/config/yaml/AccessControlConfigurationImpl.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/config/yaml/AccessControlConfigurationImpl.java
@@ -23,6 +23,7 @@ import java.util.List;
import java.util.Set;
import com.fasterxml.jackson.annotation.JsonProperty;
+import org.apache.cassandra.sidecar.acl.authorization.AllowAllAuthorizationProvider;
import org.apache.cassandra.sidecar.common.server.utils.MillisecondBoundConfiguration;
import org.apache.cassandra.sidecar.config.AccessControlConfiguration;
import org.apache.cassandra.sidecar.config.CacheConfiguration;
@@ -35,6 +36,8 @@ public class AccessControlConfigurationImpl implements AccessControlConfiguratio
{
private static final boolean DEFAULT_ENABLED = false;
private static final List<ParameterizedClassConfiguration> DEFAULT_AUTHENTICATORS_CONFIGURATION = Collections.emptyList();
+ private static final ParameterizedClassConfiguration DEFAULT_AUTHORIZER_CONFIGURATION
+ = new ParameterizedClassConfigurationImpl(AllowAllAuthorizationProvider.class.getName(), Collections.emptyMap());
private static final Set<String> DEFAULT_ADMIN_IDENTITIES = Collections.emptySet();
private static final CacheConfiguration DEFAULT_PERMISSION_CACHE_CONFIGURATION =
new CacheConfigurationImpl(MillisecondBoundConfiguration.parse("2h"), 1_000);
@@ -45,6 +48,9 @@ public class AccessControlConfigurationImpl implements AccessControlConfiguratio
@JsonProperty(value = "authenticators")
protected final List<ParameterizedClassConfiguration> authenticatorsConfiguration;
+ @JsonProperty(value = "authorizer")
+ protected final ParameterizedClassConfiguration authorizerConfiguration;
+
@JsonProperty(value = "admin_identities")
protected final Set<String> adminIdentities;
@@ -53,16 +59,19 @@ public class AccessControlConfigurationImpl implements AccessControlConfiguratio
public AccessControlConfigurationImpl()
{
- this(DEFAULT_ENABLED, DEFAULT_AUTHENTICATORS_CONFIGURATION, DEFAULT_ADMIN_IDENTITIES, DEFAULT_PERMISSION_CACHE_CONFIGURATION);
+ this(DEFAULT_ENABLED, DEFAULT_AUTHENTICATORS_CONFIGURATION, DEFAULT_AUTHORIZER_CONFIGURATION,
+ DEFAULT_ADMIN_IDENTITIES, DEFAULT_PERMISSION_CACHE_CONFIGURATION);
}
public AccessControlConfigurationImpl(boolean enabled,
List<ParameterizedClassConfiguration> authenticatorsConfiguration,
+ ParameterizedClassConfiguration authorizerConfiguration,
Set<String> adminIdentities,
CacheConfiguration permissionCacheConfiguration)
{
this.enabled = enabled;
this.authenticatorsConfiguration = authenticatorsConfiguration;
+ this.authorizerConfiguration = authorizerConfiguration;
this.adminIdentities = adminIdentities;
this.permissionCacheConfiguration = permissionCacheConfiguration;
}
@@ -87,6 +96,16 @@ public class AccessControlConfigurationImpl implements AccessControlConfiguratio
return authenticatorsConfiguration;
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ @JsonProperty(value = "authorizer")
+ public ParameterizedClassConfiguration authorizerConfiguration()
+ {
+ return authorizerConfiguration;
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/db/SidecarPermissionsDatabaseAccessor.java b/server/src/main/java/org/apache/cassandra/sidecar/db/SidecarPermissionsDatabaseAccessor.java
new file mode 100644
index 00000000..e0d9a115
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/db/SidecarPermissionsDatabaseAccessor.java
@@ -0,0 +1,87 @@
+/*
+ * 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.db;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import com.datastax.driver.core.BoundStatement;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import io.vertx.ext.auth.authorization.Authorization;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import org.apache.cassandra.sidecar.db.schema.SidecarRolePermissionsSchema;
+
+import static org.apache.cassandra.sidecar.utils.AuthUtils.permissionFromName;
+
+/**
+ * {@link SidecarPermissionsDatabaseAccessor} is an accessor for role_permissions_v1 table under sidecar_internal
+ * keyspace. Custom sidecar specific permissions are stored in this table.
+ */
+@Singleton
+public class SidecarPermissionsDatabaseAccessor extends DatabaseAccessor<SidecarRolePermissionsSchema>
+{
+ @Inject
+ protected SidecarPermissionsDatabaseAccessor(SidecarRolePermissionsSchema tableSchema,
+ CQLSessionProvider sessionProvider)
+ {
+ super(tableSchema, sessionProvider);
+ }
+
+ /**
+ * Queries Sidecar for all rows in sidecar_internal.role_permissions_v1 table. This table maps permissions of a
+ * role into {@link Authorization} and returns a {@code Map} of user role to authorizations.
+ *
+ * @return {@code Map} contains role and granted authorizations
+ */
+ public Map<String, Set<Authorization>> rolesToAuthorizations()
+ {
+ BoundStatement statement = tableSchema.allRolesPermissions().bind();
+ ResultSet result = execute(statement);
+ Map<String, Set<Authorization>> roleAuthorizations = new HashMap<>();
+ for (Row row : result)
+ {
+ String role = row.getString("role");
+ String resource = row.getString("resource");
+ Set<String> permissions = row.getSet("permissions", String.class);
+ Set<Authorization> authorizations = new HashSet<>();
+ for (String permission : permissions)
+ {
+ try
+ {
+ authorizations.add(permissionFromName(permission).toAuthorization(resource));
+ }
+ catch (Exception e)
+ {
+ logger.error("Error parsing Sidecar permission={} resource={} role={}",
+ permission, resource, role, e);
+ }
+ }
+ if (!authorizations.isEmpty())
+ {
+ roleAuthorizations.computeIfAbsent(role, k -> new HashSet<>()).addAll(authorizations);
+ }
+ }
+ return roleAuthorizations;
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/db/SystemAuthDatabaseAccessor.java b/server/src/main/java/org/apache/cassandra/sidecar/db/SystemAuthDatabaseAccessor.java
index dfbb395a..db95ad60 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/db/SystemAuthDatabaseAccessor.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/db/SystemAuthDatabaseAccessor.java
@@ -19,16 +19,21 @@
package org.apache.cassandra.sidecar.db;
import java.util.HashMap;
+import java.util.HashSet;
import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
import com.datastax.driver.core.BoundStatement;
import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.google.inject.Inject;
import com.google.inject.Singleton;
+import io.vertx.ext.auth.authorization.Authorization;
import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
import org.apache.cassandra.sidecar.db.schema.SystemAuthSchema;
-import org.apache.cassandra.sidecar.exceptions.SchemaUnavailableException;
+
+import static org.apache.cassandra.sidecar.utils.AuthUtils.permissionFromName;
/**
* Database Accessor that queries cassandra to get information maintained under system_auth keyspace.
@@ -46,14 +51,12 @@ public class SystemAuthDatabaseAccessor extends DatabaseAccessor<SystemAuthSchem
/**
* Queries Cassandra for the role associated with given identity.
*
- * @param identity Identity of user extracted
+ * @param identity identity of user extracted
* @return the role associated with the given identity in Cassandra
*/
public String findRoleFromIdentity(String identity)
{
- ensureIdentityToRoleTableAccess();
- BoundStatement statement = tableSchema.selectRoleFromIdentity()
- .bind(identity);
+ BoundStatement statement = tableSchema.roleFromIdentity().bind(identity);
ResultSet result = execute(statement);
Row row = result.one();
return row != null ? row.getString("role") : null;
@@ -66,9 +69,7 @@ public class SystemAuthDatabaseAccessor extends DatabaseAccessor<SystemAuthSchem
*/
public Map<String, String> findAllIdentityToRoles()
{
- ensureIdentityToRoleTableAccess();
- BoundStatement statement = tableSchema.getAllRolesAndIdentities().bind();
-
+ BoundStatement statement = tableSchema.allRolesAndIdentities().bind();
ResultSet resultSet = execute(statement);
Map<String, String> results = new HashMap<>();
for (Row row : resultSet)
@@ -78,11 +79,56 @@ public class SystemAuthDatabaseAccessor extends DatabaseAccessor<SystemAuthSchem
return results;
}
- private void ensureIdentityToRoleTableAccess()
+ /**
+ * Queries Cassandra for all rows in system_auth.role_permissions table. Maps permissions of a role into
+ * {@link Authorization} and returns a {@code Map} of cassandra role to authorizations
+ *
+ * @return - {@code Map} contains role and granted authorizations
+ */
+ public Map<String, Set<Authorization>> findAllRolesAndPermissions()
+ {
+ BoundStatement statement = tableSchema.allRolesAndPermissions().bind();
+ ResultSet result = execute(statement);
+ Map<String, Set<Authorization>> roleAuthorizations = new HashMap<>();
+ for (Row row : result)
+ {
+ String role = row.getString("role");
+ String resource = row.getString("resource");
+ Set<Authorization> authorizations = row.getSet("permissions", String.class)
+ .stream()
+ .map(permission -> permissionFromName(permission).toAuthorization(resource))
+ .collect(Collectors.toSet());
+ roleAuthorizations.computeIfAbsent(role, k -> new HashSet<>()).addAll(authorizations);
+ }
+ return roleAuthorizations;
+ }
+
+ /**
+ * Queries Cassandra for superuser status of a given role.
+ *
+ * @param role role in Cassandra
+ * @return {@code true} if given role is a superuser, {@code false} otherwise
+ */
+ public boolean isSuperUser(String role)
{
- if (tableSchema.selectRoleFromIdentity() == null || tableSchema.getAllRolesAndIdentities() == null)
+ BoundStatement statement = tableSchema.roleSuperuserStatus().bind(role);
+ ResultSet result = execute(statement);
+ Row row = result.one();
+ return row != null && row.getBool("is_superuser");
+ }
+
+ /**
+ * @return a map of roles to superuser status
+ */
+ public Map<String, Boolean> findAllRolesToSuperuserStatus()
+ {
+ BoundStatement statement = tableSchema.allRoles().bind();
+ ResultSet result = execute(statement);
+ Map<String, Boolean> roles = new HashMap<>();
+ for (Row row : result)
{
- throw new SchemaUnavailableException("SystemAuthSchema was not prepared, values cannot be retrieved from table");
+ roles.put(row.getString("role"), row.getBool("is_superuser"));
}
+ return roles;
}
}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/db/schema/SidecarRolePermissionsSchema.java b/server/src/main/java/org/apache/cassandra/sidecar/db/schema/SidecarRolePermissionsSchema.java
new file mode 100644
index 00000000..8cb75dd6
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/db/schema/SidecarRolePermissionsSchema.java
@@ -0,0 +1,89 @@
+/*
+ * 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.db.schema;
+
+import com.datastax.driver.core.PreparedStatement;
+import com.datastax.driver.core.Session;
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.config.SchemaKeyspaceConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * sidecar_internal.role_permissions_v1 table holds custom sidecar permissions that are not stored in Cassandra.
+ * Permissions are stored against resource.
+ */
+@Singleton
+public class SidecarRolePermissionsSchema extends TableSchema
+{
+ private static final String ROLE_PERMISSIONS_TABLE = "role_permissions_v1";
+
+ private final SchemaKeyspaceConfiguration keyspaceConfig;
+
+ private PreparedStatement allRolesAndPermissions;
+
+ @Inject
+ public SidecarRolePermissionsSchema(SidecarConfiguration sidecarConfiguration)
+ {
+ this.keyspaceConfig = sidecarConfiguration.serviceConfiguration().schemaKeyspaceConfiguration();
+ }
+
+ @Override
+ protected String tableName()
+ {
+ return ROLE_PERMISSIONS_TABLE;
+ }
+
+ @Override
+ protected String keyspaceName()
+ {
+ return keyspaceConfig.keyspace();
+ }
+
+ @Override
+ protected void prepareStatements(@NotNull Session session)
+ {
+ allRolesAndPermissions = prepare(allRolesAndPermissions, session, CqlLiterals.allRolesAndPermissions(keyspaceConfig));
+ }
+
+ @Override
+ protected String createSchemaStatement()
+ {
+ return String.format("CREATE TABLE IF NOT EXISTS %s.%s ("
+ + "role text,"
+ + "resource text,"
+ + "permissions set<text>,"
+ + "PRIMARY KEY(role, resource))",
+ keyspaceConfig.keyspace(), ROLE_PERMISSIONS_TABLE);
+ }
+
+ public PreparedStatement allRolesPermissions()
+ {
+ return allRolesAndPermissions;
+ }
+
+ private static class CqlLiterals
+ {
+ static String allRolesAndPermissions(SchemaKeyspaceConfiguration config)
+ {
+ return String.format("SELECT * FROM %s.%s", config.keyspace(), ROLE_PERMISSIONS_TABLE);
+ }
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/db/schema/SystemAuthSchema.java b/server/src/main/java/org/apache/cassandra/sidecar/db/schema/SystemAuthSchema.java
index e96b21b5..274b2696 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/db/schema/SystemAuthSchema.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/db/schema/SystemAuthSchema.java
@@ -22,8 +22,8 @@ import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.PreparedStatement;
import com.datastax.driver.core.Session;
import com.google.inject.Singleton;
+import org.apache.cassandra.sidecar.exceptions.SchemaUnavailableException;
import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
/**
* Schema for getting information stored in system_auth keyspace.
@@ -32,8 +32,12 @@ import org.jetbrains.annotations.Nullable;
public class SystemAuthSchema extends CassandraSystemTableSchema
{
private static final String IDENTITY_TO_ROLE_TABLE = "identity_to_role";
- private PreparedStatement selectRoleFromIdentity;
- private PreparedStatement getAllRolesAndIdentities;
+
+ private PreparedStatement roleFromIdentity;
+ private PreparedStatement allRolesAndIdentities;
+ private PreparedStatement roleSuperuserStatus;
+ private PreparedStatement allRoles;
+ private PreparedStatement allRolesAndPermissions;
@Override
protected String keyspaceName()
@@ -44,19 +48,19 @@ public class SystemAuthSchema extends CassandraSystemTableSchema
@Override
protected void prepareStatements(@NotNull Session session)
{
+ roleSuperuserStatus = prepare(roleSuperuserStatus, session, "SELECT is_superuser FROM system_auth.roles WHERE role = ?");
+ allRoles = prepare(allRoles, session, "SELECT * FROM system_auth.roles");
+ allRolesAndPermissions = prepare(allRolesAndPermissions, session, "SELECT * FROM system_auth.role_permissions");
+
KeyspaceMetadata keyspaceMetadata = session.getCluster().getMetadata().getKeyspace(keyspaceName());
// identity_to_role table exists in Cassandra versions starting 5.x
if (keyspaceMetadata == null || keyspaceMetadata.getTable(IDENTITY_TO_ROLE_TABLE) == null)
{
+ logger.info("Auth table does not exist. Skip preparing. table={}.{}", keyspaceName(), IDENTITY_TO_ROLE_TABLE);
return;
}
- selectRoleFromIdentity = prepare(selectRoleFromIdentity,
- session,
- CqlLiterals.SELECT_ROLE_FROM_IDENTITY);
-
- getAllRolesAndIdentities = prepare(getAllRolesAndIdentities,
- session,
- CqlLiterals.GET_ALL_ROLES_AND_IDENTITIES);
+ roleFromIdentity = prepare(roleFromIdentity, session, "SELECT role FROM system_auth.identity_to_role WHERE identity = ?");
+ allRolesAndIdentities = prepare(allRolesAndIdentities, session, "SELECT role, identity FROM system_auth.identity_to_role");
}
@Override
@@ -66,21 +70,41 @@ public class SystemAuthSchema extends CassandraSystemTableSchema
"tables in system_auth keyspace");
}
- @Nullable
- public PreparedStatement selectRoleFromIdentity()
+ @NotNull
+ public PreparedStatement roleFromIdentity()
+ {
+ ensureSchemaAvailable();
+ return roleFromIdentity;
+ }
+
+ @NotNull
+ public PreparedStatement allRolesAndIdentities()
+ {
+ ensureSchemaAvailable();
+ return allRolesAndIdentities;
+ }
+
+ public PreparedStatement allRolesAndPermissions()
{
- return selectRoleFromIdentity;
+ return allRolesAndPermissions;
}
- @Nullable
- public PreparedStatement getAllRolesAndIdentities()
+ public PreparedStatement roleSuperuserStatus()
{
- return getAllRolesAndIdentities;
+ return roleSuperuserStatus;
}
- private static class CqlLiterals
+ public PreparedStatement allRoles()
{
- static final String SELECT_ROLE_FROM_IDENTITY = "SELECT role FROM system_auth.identity_to_role WHERE identity = ?";
- static final String GET_ALL_ROLES_AND_IDENTITIES = "SELECT * FROM system_auth.identity_to_role";
+ return allRoles;
+ }
+
+ protected void ensureSchemaAvailable() throws SchemaUnavailableException
+ {
+ if (roleFromIdentity == null || allRolesAndIdentities == null)
+ {
+ throw new SchemaUnavailableException(String.format("Table %s.%s does not exist",
+ keyspaceName(), IDENTITY_TO_ROLE_TABLE));
+ }
}
}
diff --git a/server/src/test/integration/org/apache/cassandra/testing/CassandraTestContext.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/AccessProtected.java
similarity index 51%
copy from server/src/test/integration/org/apache/cassandra/testing/CassandraTestContext.java
copy to server/src/main/java/org/apache/cassandra/sidecar/routes/AccessProtected.java
index 09afe242..cf5b6985 100644
--- a/server/src/test/integration/org/apache/cassandra/testing/CassandraTestContext.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/AccessProtected.java
@@ -16,31 +16,21 @@
* limitations under the License.
*/
-package org.apache.cassandra.testing;
+package org.apache.cassandra.sidecar.routes;
-import org.apache.cassandra.distributed.UpgradeableCluster;
+import java.util.Set;
+
+import io.vertx.core.Handler;
+import io.vertx.ext.auth.authorization.Authorization;
/**
- * Passed to integration tests.
- * See {@link CassandraIntegrationTest} for the required annotation
- * See {@link CassandraTestTemplate} for the Test Template
+ * Interface for authorized routes that defines the set of {@link Authorization}s required by the implementing
+ * {@link Handler}.
*/
-public class CassandraTestContext extends AbstractCassandraTestContext
+public interface AccessProtected
{
-
- public CassandraTestContext(SimpleCassandraVersion version,
- UpgradeableCluster cluster,
- CassandraIntegrationTest annotation)
- {
- super(version, cluster, annotation);
- }
-
- @Override
- public String toString()
- {
- return "CassandraTestContext{"
- + "version=" + version
- + ", cluster=" + cluster
- + '}';
- }
+ /**
+ * @return the set of required authorizations
+ */
+ Set<Authorization> requiredAuthorizations();
}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/AccessProtectedRouteBuilder.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/AccessProtectedRouteBuilder.java
new file mode 100644
index 00000000..601f3620
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/AccessProtectedRouteBuilder.java
@@ -0,0 +1,221 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.sidecar.routes;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Objects;
+import java.util.Optional;
+import java.util.Set;
+import java.util.function.BiConsumer;
+import java.util.stream.Collectors;
+
+import io.vertx.core.Handler;
+import io.vertx.core.http.HttpMethod;
+import io.vertx.ext.auth.authorization.AndAuthorization;
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.auth.authorization.AuthorizationContext;
+import io.vertx.ext.auth.authorization.AuthorizationProvider;
+import io.vertx.ext.web.Route;
+import io.vertx.ext.web.Router;
+import io.vertx.ext.web.RoutingContext;
+import io.vertx.ext.web.handler.BodyHandler;
+import org.apache.cassandra.sidecar.acl.authorization.AdminIdentityResolver;
+import org.apache.cassandra.sidecar.acl.authorization.AuthorizationParameterValidateHandler;
+import org.apache.cassandra.sidecar.acl.authorization.AuthorizationWithAdminBypassHandler;
+import org.apache.cassandra.sidecar.common.server.data.QualifiedTableName;
+import org.apache.cassandra.sidecar.common.utils.Preconditions;
+import org.apache.cassandra.sidecar.config.AccessControlConfiguration;
+import org.apache.cassandra.sidecar.exceptions.ConfigurationException;
+
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.KEYSPACE;
+import static org.apache.cassandra.sidecar.common.ApiEndpointsV1.TABLE;
+import static org.apache.cassandra.sidecar.routes.RoutingContextUtils.SC_QUALIFIED_TABLE_NAME;
+
+/**
+ * Builder for building authorized routes
+ */
+public class AccessProtectedRouteBuilder
+{
+ private final AccessControlConfiguration accessControlConfiguration;
+ private final AuthorizationProvider authorizationProvider;
+ private final AdminIdentityResolver adminIdentityResolver;
+ private final AuthorizationParameterValidateHandler authZParameterValidateHandler;
+
+ private Router router;
+ private HttpMethod method;
+ private String endpoint;
+ private boolean setBodyHandler;
+ private final List<Handler<RoutingContext>> handlers = new ArrayList<>();
+
+ public AccessProtectedRouteBuilder(AccessControlConfiguration accessControlConfiguration,
+ AuthorizationProvider authorizationProvider,
+ AdminIdentityResolver adminIdentityResolver,
+ AuthorizationParameterValidateHandler authZParameterValidateHandler)
+ {
+ this.accessControlConfiguration = accessControlConfiguration;
+ this.authorizationProvider = authorizationProvider;
+ this.adminIdentityResolver = adminIdentityResolver;
+ this.authZParameterValidateHandler = authZParameterValidateHandler;
+ }
+
+ /**
+ * Sets {@link Router} authorized route is built for
+ *
+ * @param router Router authorized route is built for
+ * @return a reference to {@link AccessProtectedRouteBuilder} for chaining
+ */
+ public AccessProtectedRouteBuilder router(Router router)
+ {
+ this.router = router;
+ return this;
+ }
+
+ /**
+ * Sets {@link HttpMethod} for route
+ *
+ * @param method HttpMethod set for route
+ * @return a reference to {@link AccessProtectedRouteBuilder} for chaining
+ */
+ public AccessProtectedRouteBuilder method(HttpMethod method)
+ {
+ this.method = method;
+ return this;
+ }
+
+ /**
+ * Sets path for route
+ *
+ * @param endpoint REST path for route
+ * @return a reference to {@link AccessProtectedRouteBuilder} for chaining
+ */
+ public AccessProtectedRouteBuilder endpoint(String endpoint)
+ {
+ this.endpoint = endpoint;
+ return this;
+ }
+
+ /**
+ * Sets if BodyHandler should be created for the route.
+ *
+ * @param setBodyHandler boolean flag indicating if route requires BodyHandler
+ * @return a reference to {@link AccessProtectedRouteBuilder} for chaining
+ */
+ public AccessProtectedRouteBuilder setBodyHandler(Boolean setBodyHandler)
+ {
+ this.setBodyHandler = setBodyHandler;
+ return this;
+ }
+
+ /**
+ * Adds handler to handler chain of route. Handlers are ordered, they are called in order they are set in chain.
+ *
+ * @param handler handler for route
+ * @return a reference to {@link AccessProtectedRouteBuilder} for chaining
+ */
+ public AccessProtectedRouteBuilder handler(Handler<RoutingContext> handler)
+ {
+ this.handlers.add(handler);
+ return this;
+ }
+
+ /**
+ * Builds an authorized route. Adds {@link io.vertx.ext.web.handler.AuthorizationHandler} at top of handler
+ * chain if access control is enabled.
+ */
+ public void build()
+ {
+ Objects.requireNonNull(router, "Router must be set");
+ Objects.requireNonNull(method, "Http method must be set");
+ Preconditions.checkArgument(endpoint != null && !endpoint.isEmpty(), "Endpoint must be set");
+ Preconditions.checkArgument(!handlers.isEmpty(), "Handler chain can not be empty");
+
+ Route route = router.route(method, endpoint);
+
+ // BodyHandler must be placed before Authorization handler
+ // See io.vertx.ext.web.impl.RouteState.Priority
+ if (setBodyHandler)
+ {
+ route.handler(BodyHandler.create());
+ }
+
+ if (accessControlConfiguration.enabled())
+ {
+ // authorization handler added before route specific handler chain
+ AuthorizationWithAdminBypassHandler authorizationHandler
+ = new AuthorizationWithAdminBypassHandler(authZParameterValidateHandler, adminIdentityResolver,
+ requiredAuthorization());
+ authorizationHandler.addAuthorizationProvider(authorizationProvider);
+ authorizationHandler.variableConsumer(routeGenericVariableConsumer());
+
+ route.handler(authorizationHandler);
+ }
+
+ handlers.forEach(route::handler);
+ }
+
+ private Authorization requiredAuthorization()
+ {
+ Set<Authorization> requiredAuthorizations = handlers
+ .stream()
+ .filter(handler -> handler instanceof AccessProtected)
+ .map(handler -> (AccessProtected) handler)
+ .flatMap(handler -> handler.requiredAuthorizations().stream())
+ .collect(Collectors.toSet());
+ if (requiredAuthorizations.isEmpty())
+ {
+ throw new ConfigurationException("Authorized route must have authorizations declared");
+ }
+ AndAuthorization andAuthorization = AndAuthorization.create();
+ requiredAuthorizations.forEach(andAuthorization::addAuthorization);
+ return andAuthorization;
+ }
+
+ private BiConsumer<RoutingContext, AuthorizationContext> routeGenericVariableConsumer()
+ {
+ return (routingCtx, authZContext) -> {
+ Optional<QualifiedTableName> optional = RoutingContextUtils.getAsOptional(routingCtx, SC_QUALIFIED_TABLE_NAME);
+ String keyspace = null;
+ String table = null;
+ if (optional.isPresent())
+ {
+ QualifiedTableName qualifiedTableName = optional.get();
+ keyspace = qualifiedTableName.keyspace();
+ table = qualifiedTableName.tableName();
+ }
+
+ if (keyspace != null)
+ {
+ authZContext.variables().add(KEYSPACE, keyspace);
+ }
+ if (table != null)
+ {
+ authZContext.variables().add(TABLE, table);
+ }
+
+ // TODO remove this hack once VariableAwareExpression bug is fixed
+ // VariableAwareExpression in vertx-auth-common package has a bug during String.substring() call, hence
+ // we cannot set resources that do not end in curly braces (e.g. data/keyspace/*) in
+ // PermissionBasedAuthorizationImpl or WildcardPermissionBasedAuthorizationImpl. hence we treat
+ // TABLE_WILDCARD as a variable and set it always. This hack allows to read
+ // resource level permissions that could be set for all tables through data/<keyspace_name>/*
+ authZContext.variables().add("TABLE_WILDCARD", "*");
+ };
+ }
+}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/ConnectedClientStatsHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/ConnectedClientStatsHandler.java
index d58ca8f7..ff45674a 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/ConnectedClientStatsHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/ConnectedClientStatsHandler.java
@@ -18,10 +18,18 @@
package org.apache.cassandra.sidecar.routes;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
import com.google.inject.Inject;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.CassandraPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.server.MetricsOperations;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
@@ -31,7 +39,7 @@ import static org.apache.cassandra.sidecar.utils.RequestUtils.parseBooleanQueryP
/**
* Handler for retrieving stats for connected clients
*/
-public class ConnectedClientStatsHandler extends AbstractHandler<Boolean>
+public class ConnectedClientStatsHandler extends AbstractHandler<Boolean> implements AccessProtected
{
/**
* Constructs a handler with the provided {@code metadataFetcher}
@@ -45,6 +53,19 @@ public class ConnectedClientStatsHandler extends AbstractHandler<Boolean>
super(metadataFetcher, executorPools, null);
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = Arrays.asList(VariableAwareResource.DATA.resource(),
+ // Keyspace access to system_views
+ "data/system_views",
+ // Access to all tables in keyspace system_views
+ "data/system_views/*",
+ // Access to the clients table in the system_views keyspace
+ "data/system_views/clients");
+ return Collections.singleton(CassandraPermissions.SELECT.toAuthorization(eligibleResources));
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/GossipInfoHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/GossipInfoHandler.java
index 2f05cc6a..786e5d06 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/GossipInfoHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/GossipInfoHandler.java
@@ -18,12 +18,18 @@
package org.apache.cassandra.sidecar.routes;
+import java.util.Collections;
+import java.util.Set;
+
import com.google.common.base.Preconditions;
import com.google.inject.Inject;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.cluster.CassandraAdapterDelegate;
import org.apache.cassandra.sidecar.common.server.ClusterMembershipOperations;
import org.apache.cassandra.sidecar.common.server.utils.GossipInfoParser;
@@ -34,7 +40,7 @@ import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
/**
* Handler for retrieving gossip info
*/
-public class GossipInfoHandler extends AbstractHandler<Void>
+public class GossipInfoHandler extends AbstractHandler<Void> implements AccessProtected
{
/**
* Constructs a handler with the provided {@code metadataFetcher}
@@ -48,6 +54,13 @@ public class GossipInfoHandler extends AbstractHandler<Void>
super(metadataFetcher, executorPools, null);
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ String resource = VariableAwareResource.CLUSTER.resource();
+ return Collections.singleton(BasicPermissions.READ_GOSSIP.toAuthorization(resource));
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/RingHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/KeyspaceRingHandler.java
similarity index 74%
copy from server/src/main/java/org/apache/cassandra/sidecar/routes/RingHandler.java
copy to server/src/main/java/org/apache/cassandra/sidecar/routes/KeyspaceRingHandler.java
index 1e86cad7..cd271061 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/RingHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/KeyspaceRingHandler.java
@@ -18,6 +18,10 @@
package org.apache.cassandra.sidecar.routes;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
import org.apache.commons.lang3.StringUtils;
import com.google.inject.Inject;
@@ -25,7 +29,10 @@ import com.google.inject.Singleton;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.server.StorageOperations;
import org.apache.cassandra.sidecar.common.server.data.Name;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
@@ -35,19 +42,29 @@ import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpException;
/**
- * A handler that provides ring information for the Cassandra cluster
+ * A handler that provides ring information for a specific keyspace for the Cassandra cluster
*/
@Singleton
-public class RingHandler extends AbstractHandler<Name>
+public class KeyspaceRingHandler extends AbstractHandler<Name> implements AccessProtected
{
@Inject
- public RingHandler(InstanceMetadataFetcher metadataFetcher,
- CassandraInputValidator validator,
- ExecutorPools executorPools)
+ public KeyspaceRingHandler(InstanceMetadataFetcher metadataFetcher,
+ ExecutorPools executorPools,
+ CassandraInputValidator validator)
{
super(metadataFetcher, executorPools, validator);
}
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE.expandedResources();
+ return Collections.singleton(BasicPermissions.READ_RING.toAuthorization(eligibleResources));
+ }
+
/**
* {@inheritDoc}
*/
@@ -65,6 +82,9 @@ public class RingHandler extends AbstractHandler<Name>
.onFailure(cause -> processFailure(cause, context, host, remoteAddress, keyspace));
}
+ /**
+ * {@inheritDoc}
+ */
@Override
protected void processFailure(Throwable cause,
RoutingContext context,
@@ -88,6 +108,6 @@ public class RingHandler extends AbstractHandler<Name>
@Override
protected Name extractParamsOrThrow(RoutingContext context)
{
- return keyspace(context, false);
+ return keyspace(context, true);
}
}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/SchemaHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/KeyspaceSchemaHandler.java
similarity index 82%
copy from server/src/main/java/org/apache/cassandra/sidecar/routes/SchemaHandler.java
copy to server/src/main/java/org/apache/cassandra/sidecar/routes/KeyspaceSchemaHandler.java
index fe1d96b7..7506292c 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/SchemaHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/KeyspaceSchemaHandler.java
@@ -17,6 +17,10 @@
*/
package org.apache.cassandra.sidecar.routes;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.Metadata;
import com.google.inject.Inject;
@@ -25,7 +29,10 @@ import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.response.SchemaResponse;
import org.apache.cassandra.sidecar.common.server.data.Name;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
@@ -36,10 +43,10 @@ import org.apache.cassandra.sidecar.utils.MetadataUtils;
import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpException;
/**
- * The {@link SchemaHandler} class handles schema requests
+ * The {@link KeyspaceSchemaHandler} class handles keyspace schema requests
*/
@Singleton
-public class SchemaHandler extends AbstractHandler<Name>
+public class KeyspaceSchemaHandler extends AbstractHandler<Name> implements AccessProtected
{
/**
* Constructs a handler with the provided {@code metadataFetcher}
@@ -49,12 +56,20 @@ public class SchemaHandler extends AbstractHandler<Name>
* @param validator a validator instance to validate Cassandra-specific input
*/
@Inject
- protected SchemaHandler(InstanceMetadataFetcher metadataFetcher, ExecutorPools executorPools,
- CassandraInputValidator validator)
+ protected KeyspaceSchemaHandler(InstanceMetadataFetcher metadataFetcher,
+ ExecutorPools executorPools,
+ CassandraInputValidator validator)
{
super(metadataFetcher, executorPools, validator);
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE.expandedResources();
+ return Collections.singleton(BasicPermissions.READ_SCHEMA.toAuthorization(eligibleResources));
+ }
+
/**
* {@inheritDoc}
*/
@@ -126,6 +141,6 @@ public class SchemaHandler extends AbstractHandler<Name>
@Override
protected Name extractParamsOrThrow(RoutingContext context)
{
- return keyspace(context, false);
+ return keyspace(context, true);
}
}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/ListOperationalJobsHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/ListOperationalJobsHandler.java
index 93a0861d..7a3bf2e3 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/ListOperationalJobsHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/ListOperationalJobsHandler.java
@@ -18,11 +18,16 @@
package org.apache.cassandra.sidecar.routes;
+import java.util.Collections;
+import java.util.Set;
import javax.inject.Inject;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.response.ListOperationalJobsResponse;
import org.apache.cassandra.sidecar.common.response.OperationalJobResponse;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
@@ -35,7 +40,7 @@ import static org.apache.cassandra.sidecar.common.data.OperationalJobStatus.RUNN
/**
* Handler for retrieving the all the jobs running on the sidecar
*/
-public class ListOperationalJobsHandler extends AbstractHandler<Void>
+public class ListOperationalJobsHandler extends AbstractHandler<Void> implements AccessProtected
{
private final OperationalJobManager jobManager;
@@ -49,6 +54,13 @@ public class ListOperationalJobsHandler extends AbstractHandler<Void>
this.jobManager = jobManager;
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ String resource = VariableAwareResource.OPERATION.resource();
+ return Collections.singleton(BasicPermissions.READ_OPERATIONAL_JOB.toAuthorization(resource));
+ }
+
@Override
protected Void extractParamsOrThrow(RoutingContext context)
{
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/NodeDecommissionHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/NodeDecommissionHandler.java
index ab9bbf06..941146b3 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/NodeDecommissionHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/NodeDecommissionHandler.java
@@ -18,12 +18,18 @@
package org.apache.cassandra.sidecar.routes;
+import java.util.Collections;
+import java.util.Set;
+
import com.datastax.driver.core.utils.UUIDs;
import com.google.inject.Inject;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.data.OperationalJobStatus;
import org.apache.cassandra.sidecar.common.response.OperationalJobResponse;
import org.apache.cassandra.sidecar.common.server.StorageOperations;
@@ -41,7 +47,7 @@ import static org.apache.cassandra.sidecar.utils.RequestUtils.parseBooleanQueryP
/**
* Provides REST API for asynchronously decommissioning the corresponding Cassandra node
*/
-public class NodeDecommissionHandler extends AbstractHandler<Boolean>
+public class NodeDecommissionHandler extends AbstractHandler<Boolean> implements AccessProtected
{
private final OperationalJobManager jobManager;
private final ServiceConfiguration config;
@@ -65,6 +71,13 @@ public class NodeDecommissionHandler extends AbstractHandler<Boolean>
this.config = serviceConfiguration;
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ String resource = VariableAwareResource.OPERATION.resource();
+ return Collections.singleton(BasicPermissions.DECOMMISSION_NODE.toAuthorization(resource));
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/OperationalJobHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/OperationalJobHandler.java
index 1f0eb12f..ba774e88 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/OperationalJobHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/OperationalJobHandler.java
@@ -18,13 +18,18 @@
package org.apache.cassandra.sidecar.routes;
+import java.util.Collections;
+import java.util.Set;
import java.util.UUID;
import javax.inject.Inject;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.job.OperationalJob;
import org.apache.cassandra.sidecar.job.OperationalJobManager;
@@ -38,7 +43,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
/**
* Handler for retrieving the status of async operational jobs running on the sidecar
*/
-public class OperationalJobHandler extends AbstractHandler<UUID>
+public class OperationalJobHandler extends AbstractHandler<UUID> implements AccessProtected
{
private final OperationalJobManager jobManager;
@@ -52,6 +57,13 @@ public class OperationalJobHandler extends AbstractHandler<UUID>
this.jobManager = jobManager;
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ String resource = VariableAwareResource.OPERATION.resource();
+ return Collections.singleton(BasicPermissions.READ_OPERATIONAL_JOB.toAuthorization(resource));
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/RingHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/RingHandler.java
index 1e86cad7..a2546766 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/RingHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/RingHandler.java
@@ -18,76 +18,48 @@
package org.apache.cassandra.sidecar.routes;
-import org.apache.commons.lang3.StringUtils;
+import java.util.Collections;
+import java.util.Set;
import com.google.inject.Inject;
import com.google.inject.Singleton;
-import io.netty.handler.codec.http.HttpResponseStatus;
-import io.vertx.core.http.HttpServerRequest;
-import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
-import org.apache.cassandra.sidecar.common.server.StorageOperations;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.server.data.Name;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
-import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpException;
-
/**
- * A handler that provides ring information for the Cassandra cluster
+ * A handler that provides ring information for a specific keyspace for the Cassandra cluster
*/
@Singleton
-public class RingHandler extends AbstractHandler<Name>
+public class RingHandler extends KeyspaceRingHandler
{
@Inject
public RingHandler(InstanceMetadataFetcher metadataFetcher,
- CassandraInputValidator validator,
- ExecutorPools executorPools)
+ ExecutorPools executorPools,
+ CassandraInputValidator validator)
{
super(metadataFetcher, executorPools, validator);
}
- /**
- * {@inheritDoc}
- */
- @Override
- public void handleInternal(RoutingContext context,
- HttpServerRequest httpRequest,
- String host,
- SocketAddress remoteAddress,
- Name keyspace)
- {
- StorageOperations operations = metadataFetcher.delegate(host).storageOperations();
- executorPools.service()
- .executeBlocking(() -> operations.ring(keyspace))
- .onSuccess(context::json)
- .onFailure(cause -> processFailure(cause, context, host, remoteAddress, keyspace));
- }
-
@Override
- protected void processFailure(Throwable cause,
- RoutingContext context,
- String host,
- SocketAddress remoteAddress,
- Name keyspace)
+ public Set<Authorization> requiredAuthorizations()
{
- if (cause instanceof IllegalArgumentException &&
- StringUtils.contains(cause.getMessage(), ", does not exist"))
- {
- context.fail(wrapHttpException(HttpResponseStatus.NOT_FOUND, cause.getMessage(), cause));
- return;
- }
-
- super.processFailure(cause, context, host, remoteAddress, keyspace);
+ String resource = VariableAwareResource.CLUSTER.resource();
+ return Collections.singleton(BasicPermissions.READ_RING.toAuthorization(resource));
}
/**
- * {@inheritDoc}
+ * @param context the request context
+ * @return {@code null} to signify no keyspace for the request
*/
@Override
protected Name extractParamsOrThrow(RoutingContext context)
{
- return keyspace(context, false);
+ return null;
}
}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/SchemaHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/SchemaHandler.java
index fe1d96b7..6f40c71f 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/SchemaHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/SchemaHandler.java
@@ -17,29 +17,25 @@
*/
package org.apache.cassandra.sidecar.routes;
-import com.datastax.driver.core.KeyspaceMetadata;
-import com.datastax.driver.core.Metadata;
+import java.util.Collections;
+import java.util.Set;
+
import com.google.inject.Inject;
import com.google.inject.Singleton;
-import io.netty.handler.codec.http.HttpResponseStatus;
-import io.vertx.core.Future;
-import io.vertx.core.http.HttpServerRequest;
-import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
-import org.apache.cassandra.sidecar.common.response.SchemaResponse;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.server.data.Name;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
-import org.apache.cassandra.sidecar.utils.MetadataUtils;
-
-import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpException;
/**
* The {@link SchemaHandler} class handles schema requests
*/
@Singleton
-public class SchemaHandler extends AbstractHandler<Name>
+public class SchemaHandler extends KeyspaceSchemaHandler
{
/**
* Constructs a handler with the provided {@code metadataFetcher}
@@ -49,83 +45,27 @@ public class SchemaHandler extends AbstractHandler<Name>
* @param validator a validator instance to validate Cassandra-specific input
*/
@Inject
- protected SchemaHandler(InstanceMetadataFetcher metadataFetcher, ExecutorPools executorPools,
+ protected SchemaHandler(InstanceMetadataFetcher metadataFetcher,
+ ExecutorPools executorPools,
CassandraInputValidator validator)
{
super(metadataFetcher, executorPools, validator);
}
- /**
- * {@inheritDoc}
- */
@Override
- public void handleInternal(RoutingContext context,
- HttpServerRequest httpRequest,
- String host,
- SocketAddress remoteAddress,
- Name keyspace)
- {
- metadata(host)
- .onFailure(cause -> processFailure(cause, context, host, remoteAddress, keyspace))
- .onSuccess(metadata -> handleWithMetadata(context, keyspace, metadata));
- }
-
- /**
- * Handles the request with the Cassandra {@link Metadata metadata}.
- *
- * @param context the event to handle
- * @param keyspace the keyspace parsed from the request
- * @param metadata the metadata on the connected cluster, including known nodes and schema definitions
- */
- private void handleWithMetadata(RoutingContext context, Name keyspace, Metadata metadata)
+ public Set<Authorization> requiredAuthorizations()
{
- if (keyspace == null)
- {
- SchemaResponse schemaResponse = new SchemaResponse(metadata.exportSchemaAsString());
- context.json(schemaResponse);
- return;
- }
-
- // retrieve keyspace metadata
- KeyspaceMetadata ksMetadata = MetadataUtils.keyspace(metadata, keyspace);
-
- if (ksMetadata == null)
- {
- // set request as failed and return
- // keyspace does not exist
- String errorMessage = String.format("Keyspace '%s' does not exist.", keyspace);
- context.fail(wrapHttpException(HttpResponseStatus.NOT_FOUND, errorMessage));
- return;
- }
-
- SchemaResponse schemaResponse = new SchemaResponse(keyspace.name(),
- ksMetadata.exportAsString());
- context.json(schemaResponse);
- }
-
- /**
- * Gets cluster metadata asynchronously.
- *
- * @param host the Cassandra instance host
- * @return {@link Future} containing {@link Metadata}
- */
- private Future<Metadata> metadata(String host)
- {
- return executorPools.service().executeBlocking(() -> {
- // metadata can block so we need to run in a blocking thread
- return metadataFetcher.delegate(host).metadata();
- });
+ String resource = VariableAwareResource.CLUSTER.resource();
+ return Collections.singleton(BasicPermissions.READ_SCHEMA.toAuthorization(resource));
}
/**
- * Parses the request parameters
- *
- * @param context the event to handle
- * @return the keyspace parsed from the request
+ * @param context the request context
+ * @return {@code null} to signify no keyspace for the request
*/
@Override
protected Name extractParamsOrThrow(RoutingContext context)
{
- return keyspace(context, false);
+ return null;
}
}
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/StreamSSTableComponentHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/StreamSSTableComponentHandler.java
index 37bd9e13..4622f9ce 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/StreamSSTableComponentHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/StreamSSTableComponentHandler.java
@@ -21,15 +21,22 @@ package org.apache.cassandra.sidecar.routes;
import java.nio.file.NoSuchFileException;
import java.util.List;
+import java.util.Set;
import javax.management.InstanceNotFoundException;
+import com.google.common.collect.ImmutableSet;
+
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.CassandraPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.server.StorageOperations;
import org.apache.cassandra.sidecar.common.server.TableOperations;
import org.apache.cassandra.sidecar.common.server.data.Name;
@@ -48,7 +55,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
* for the {@link FileStreamHandler} to stream the component back to the client
*/
@Singleton
-public class StreamSSTableComponentHandler extends AbstractHandler<StreamSSTableComponentRequestParam>
+public class StreamSSTableComponentHandler extends AbstractHandler<StreamSSTableComponentRequestParam> implements AccessProtected
{
private final SnapshotPathBuilder snapshotPathBuilder;
@@ -62,6 +69,15 @@ public class StreamSSTableComponentHandler extends AbstractHandler<StreamSSTable
this.snapshotPathBuilder = snapshotPathBuilder;
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ Authorization stream = BasicPermissions.STREAM_SNAPSHOT.toAuthorization(eligibleResources);
+ Authorization select = CassandraPermissions.SELECT.toAuthorization(eligibleResources);
+ return ImmutableSet.of(stream, select);
+ }
+
@Override
public void handleInternal(RoutingContext context,
HttpServerRequest httpRequest,
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/TokenRangeReplicaMapHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/TokenRangeReplicaMapHandler.java
index d53c4268..324a5348 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/TokenRangeReplicaMapHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/TokenRangeReplicaMapHandler.java
@@ -18,6 +18,9 @@
package org.apache.cassandra.sidecar.routes;
+import java.util.Collections;
+import java.util.Set;
+
import org.apache.commons.lang3.StringUtils;
import com.google.inject.Inject;
@@ -25,7 +28,10 @@ import com.google.inject.Singleton;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.cluster.CassandraAdapterDelegate;
import org.apache.cassandra.sidecar.common.response.NodeSettings;
import org.apache.cassandra.sidecar.common.server.StorageOperations;
@@ -47,7 +53,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
* {@code org.apache.cassandra.sidecar.adapters.base.TokenRangeReplicaProvider.StateWithReplacement}
*/
@Singleton
-public class TokenRangeReplicaMapHandler extends AbstractHandler<Name>
+public class TokenRangeReplicaMapHandler extends AbstractHandler<Name> implements AccessProtected
{
@Inject
@@ -58,6 +64,13 @@ public class TokenRangeReplicaMapHandler extends AbstractHandler<Name>
super(metadataFetcher, executorPools, validator);
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ String resource = VariableAwareResource.DATA_WITH_KEYSPACE.resource();
+ return Collections.singleton(BasicPermissions.READ_TOPOLOGY.toAuthorization(resource));
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/cassandra/NodeSettingsHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/cassandra/NodeSettingsHandler.java
index af696345..9e8222b7 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/cassandra/NodeSettingsHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/cassandra/NodeSettingsHandler.java
@@ -18,7 +18,6 @@
package org.apache.cassandra.sidecar.routes.cassandra;
-
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.vertx.core.http.HttpServerRequest;
@@ -29,7 +28,11 @@ import org.apache.cassandra.sidecar.routes.AbstractHandler;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
/**
- * Provides REST endpoint to get the configured settings of a cassandra node
+ * Provides REST endpoint to get the configured settings of a cassandra node.
+ * <p>
+ * Note: {@link NodeSettingsHandler} is not Access protected. Any user who can log in into Cassandra is able to view
+ * node settings information. Since sidecar and cassandra share list of authenticated identities, sidecar's
+ * authenticated users can also read node settings information.
*/
@Singleton
public class NodeSettingsHandler extends AbstractHandler<Void>
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/cdc/ListCdcDirHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/cdc/ListCdcDirHandler.java
index 2f7a2540..74e902fb 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/cdc/ListCdcDirHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/cdc/ListCdcDirHandler.java
@@ -24,6 +24,7 @@ import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.ArrayList;
+import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@@ -36,7 +37,10 @@ import com.google.inject.Singleton;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.response.ListCdcSegmentsResponse;
import org.apache.cassandra.sidecar.common.response.data.CdcSegmentInfo;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
@@ -44,6 +48,7 @@ import org.apache.cassandra.sidecar.concurrent.TaskExecutorPool;
import org.apache.cassandra.sidecar.config.ServiceConfiguration;
import org.apache.cassandra.sidecar.config.SidecarConfiguration;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.CdcUtil;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
@@ -57,7 +62,7 @@ import static org.apache.cassandra.sidecar.utils.CdcUtil.parseIndexFile;
* Provides REST endpoint for listing commit logs in CDC directory.
*/
@Singleton
-public class ListCdcDirHandler extends AbstractHandler<Void>
+public class ListCdcDirHandler extends AbstractHandler<Void> implements AccessProtected
{
private static final Logger LOGGER = LoggerFactory.getLogger(ListCdcDirHandler.class);
private final ServiceConfiguration config;
@@ -74,6 +79,13 @@ public class ListCdcDirHandler extends AbstractHandler<Void>
this.serviceExecutorPool = executorPools.service();
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ String resource = VariableAwareResource.CLUSTER.resource();
+ return Collections.singleton(BasicPermissions.CDC.toAuthorization(resource));
+ }
+
@Override
protected void handleInternal(RoutingContext context,
HttpServerRequest httpRequest,
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/cdc/StreamCdcSegmentHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/cdc/StreamCdcSegmentHandler.java
index 0c184e77..cf7cbc8a 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/cdc/StreamCdcSegmentHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/cdc/StreamCdcSegmentHandler.java
@@ -20,6 +20,8 @@ package org.apache.cassandra.sidecar.routes.cdc;
import java.io.File;
import java.io.IOException;
+import java.util.Collections;
+import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -31,14 +33,18 @@ import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.HttpException;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.cdc.CdcLogCache;
import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.concurrent.TaskExecutorPool;
import org.apache.cassandra.sidecar.models.HttpResponse;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.CdcUtil;
import org.apache.cassandra.sidecar.utils.FileStreamer;
@@ -54,7 +60,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
* Provides REST endpoint for streaming cdc commit logs.
*/
@Singleton
-public class StreamCdcSegmentHandler extends AbstractHandler<String>
+public class StreamCdcSegmentHandler extends AbstractHandler<String> implements AccessProtected
{
private static final Logger LOGGER = LoggerFactory.getLogger(StreamCdcSegmentHandler.class);
@@ -75,6 +81,13 @@ public class StreamCdcSegmentHandler extends AbstractHandler<String>
this.serviceExecutorPool = executorPools.service();
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ String resource = VariableAwareResource.CLUSTER.resource();
+ return Collections.singleton(BasicPermissions.CDC.toAuthorization(resource));
+ }
+
@Override
protected void handleInternal(RoutingContext context,
HttpServerRequest httpRequest,
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/AbortRestoreJobHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/AbortRestoreJobHandler.java
index 38453a95..4d5cce09 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/AbortRestoreJobHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/AbortRestoreJobHandler.java
@@ -18,19 +18,27 @@
package org.apache.cassandra.sidecar.routes.restore;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
+
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.Json;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.request.data.AbortRestoreJobRequestPayload;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.db.RestoreJobDatabaseAccessor;
import org.apache.cassandra.sidecar.metrics.RestoreMetrics;
import org.apache.cassandra.sidecar.metrics.SidecarMetrics;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.routes.RoutingContextUtils;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
@@ -44,7 +52,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
* {@link org.apache.cassandra.sidecar.db.RestoreJob}
*/
@Singleton
-public class AbortRestoreJobHandler extends AbstractHandler<AbortRestoreJobRequestPayload>
+public class AbortRestoreJobHandler extends AbstractHandler<AbortRestoreJobRequestPayload> implements AccessProtected
{
private static final AbortRestoreJobRequestPayload EMPTY_PAYLOAD = new AbortRestoreJobRequestPayload(null);
@@ -63,6 +71,13 @@ public class AbortRestoreJobHandler extends AbstractHandler<AbortRestoreJobReque
this.metrics = metrics.server().restore();
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ return Collections.singleton(BasicPermissions.DELETE_RESTORE_JOB.toAuthorization(eligibleResources));
+ }
+
@Override
protected void handleInternal(RoutingContext context,
HttpServerRequest httpRequest,
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/CreateRestoreJobHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/CreateRestoreJobHandler.java
index 22a9e53a..b419a18a 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/CreateRestoreJobHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/CreateRestoreJobHandler.java
@@ -18,6 +18,9 @@
package org.apache.cassandra.sidecar.routes.restore;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
import java.util.UUID;
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -28,13 +31,17 @@ import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.Json;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.request.data.CreateRestoreJobRequestPayload;
import org.apache.cassandra.sidecar.common.response.data.CreateRestoreJobResponsePayload;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.db.RestoreJob;
import org.apache.cassandra.sidecar.db.RestoreJobDatabaseAccessor;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.routes.RoutingContextUtils;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
@@ -46,7 +53,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
* Provides REST API for creating a new restore job for restoring data into Cassandra through Sidecar
*/
@Singleton
-public class CreateRestoreJobHandler extends AbstractHandler<CreateRestoreJobRequestPayload>
+public class CreateRestoreJobHandler extends AbstractHandler<CreateRestoreJobRequestPayload> implements AccessProtected
{
private final RestoreJobDatabaseAccessor restoreJobDatabaseAccessor;
@@ -60,6 +67,13 @@ public class CreateRestoreJobHandler extends AbstractHandler<CreateRestoreJobReq
this.restoreJobDatabaseAccessor = restoreJobDatabaseAccessor;
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ return Collections.singleton(BasicPermissions.CREATE_RESTORE_JOB.toAuthorization(eligibleResources));
+ }
+
@Override
protected void handleInternal(RoutingContext context,
HttpServerRequest httpRequest,
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/CreateRestoreSliceHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/CreateRestoreSliceHandler.java
index ad7f6297..1c49e533 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/CreateRestoreSliceHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/CreateRestoreSliceHandler.java
@@ -19,6 +19,9 @@
package org.apache.cassandra.sidecar.routes.restore;
import java.nio.file.Paths;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
import javax.inject.Inject;
import io.netty.handler.codec.http.HttpResponseStatus;
@@ -27,7 +30,10 @@ import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.Json;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
import org.apache.cassandra.sidecar.common.request.data.CreateSliceRequestPayload;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
@@ -40,6 +46,7 @@ import org.apache.cassandra.sidecar.restore.RestoreJobManagerGroup;
import org.apache.cassandra.sidecar.restore.RestoreJobProgressTracker;
import org.apache.cassandra.sidecar.restore.RestoreJobUtil;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.routes.RoutingContextUtils;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
@@ -51,7 +58,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
/**
* Provides a REST API for creating new {@link RestoreSlice} under a {@link RestoreJob}
*/
-public class CreateRestoreSliceHandler extends AbstractHandler<CreateSliceRequestPayload>
+public class CreateRestoreSliceHandler extends AbstractHandler<CreateSliceRequestPayload> implements AccessProtected
{
private static final int SERVER_ERROR_RESTORE_JOB_FAILED = 550;
private final RestoreJobManagerGroup restoreJobManagerGroup;
@@ -69,6 +76,13 @@ public class CreateRestoreSliceHandler extends AbstractHandler<CreateSliceReques
this.restoreSliceDatabaseAccessor = restoreSliceDatabaseAccessor;
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ return Collections.singleton(BasicPermissions.CREATE_RESTORE_JOB.toAuthorization(eligibleResources));
+ }
+
@Override
protected void handleInternal(RoutingContext context,
HttpServerRequest httpRequest,
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/RestoreJobProgressHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/RestoreJobProgressHandler.java
index 84bb5165..5bf73486 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/RestoreJobProgressHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/RestoreJobProgressHandler.java
@@ -16,14 +16,19 @@
package org.apache.cassandra.sidecar.routes.restore;
+import java.util.Collections;
import java.util.List;
+import java.util.Set;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.ApiEndpointsV1;
import org.apache.cassandra.sidecar.common.data.RestoreJobProgressFetchPolicy;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
@@ -31,6 +36,7 @@ import org.apache.cassandra.sidecar.db.RestoreJob;
import org.apache.cassandra.sidecar.restore.RestoreJobConsistencyLevelChecker;
import org.apache.cassandra.sidecar.restore.RestoreJobProgress;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.routes.RoutingContextUtils;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
@@ -43,7 +49,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
* The response content can vary based on the {@link RestoreJobProgressFetchPolicy}
*/
@Singleton
-public class RestoreJobProgressHandler extends AbstractHandler<RestoreJobProgressFetchPolicy>
+public class RestoreJobProgressHandler extends AbstractHandler<RestoreJobProgressFetchPolicy> implements AccessProtected
{
private final RestoreJobConsistencyLevelChecker consistencyLevelChecker;
@@ -64,6 +70,13 @@ public class RestoreJobProgressHandler extends AbstractHandler<RestoreJobProgres
this.consistencyLevelChecker = consistencyLevelChecker;
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ return Collections.singleton(BasicPermissions.READ_RESTORE_JOB.toAuthorization(eligibleResources));
+ }
+
@Override
protected RestoreJobProgressFetchPolicy extractParamsOrThrow(RoutingContext context)
{
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/RestoreJobSummaryHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/RestoreJobSummaryHandler.java
index 4831b344..c3186f6e 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/RestoreJobSummaryHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/RestoreJobSummaryHandler.java
@@ -18,6 +18,9 @@
package org.apache.cassandra.sidecar.routes.restore;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
import javax.inject.Inject;
import javax.inject.Singleton;
@@ -25,10 +28,14 @@ import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.response.data.RestoreJobSummaryResponsePayload;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.routes.RoutingContextUtils;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
@@ -40,7 +47,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
* Provides a REST API for providing summary of restore job maintained by Sidecar
*/
@Singleton
-public class RestoreJobSummaryHandler extends AbstractHandler<String>
+public class RestoreJobSummaryHandler extends AbstractHandler<String> implements AccessProtected
{
@Inject
public RestoreJobSummaryHandler(ExecutorPools executorPools,
@@ -50,6 +57,13 @@ public class RestoreJobSummaryHandler extends AbstractHandler<String>
super(instanceMetadataFetcher, executorPools, validator);
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ return Collections.singleton(BasicPermissions.READ_RESTORE_JOB.toAuthorization(eligibleResources));
+ }
+
@Override
protected void handleInternal(RoutingContext context,
HttpServerRequest httpRequest,
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/UpdateRestoreJobHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/UpdateRestoreJobHandler.java
index 60b7687b..0145b2e3 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/UpdateRestoreJobHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/restore/UpdateRestoreJobHandler.java
@@ -18,6 +18,9 @@
package org.apache.cassandra.sidecar.routes.restore;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.datastax.driver.core.utils.UUIDs;
@@ -29,7 +32,10 @@ import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.DecodeException;
import io.vertx.core.json.Json;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.data.RestoreJobStatus;
import org.apache.cassandra.sidecar.common.request.data.UpdateRestoreJobRequestPayload;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
@@ -38,6 +44,7 @@ import org.apache.cassandra.sidecar.db.RestoreJobDatabaseAccessor;
import org.apache.cassandra.sidecar.metrics.RestoreMetrics;
import org.apache.cassandra.sidecar.metrics.SidecarMetrics;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.routes.RoutingContextUtils;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
@@ -49,7 +56,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
* Provides a REST API to update {@link RestoreJob}
*/
@Singleton
-public class UpdateRestoreJobHandler extends AbstractHandler<UpdateRestoreJobRequestPayload>
+public class UpdateRestoreJobHandler extends AbstractHandler<UpdateRestoreJobRequestPayload> implements AccessProtected
{
private final RestoreJobDatabaseAccessor restoreJobDatabaseAccessor;
private final RestoreMetrics metrics;
@@ -66,6 +73,13 @@ public class UpdateRestoreJobHandler extends AbstractHandler<UpdateRestoreJobReq
this.metrics = metrics.server().restore();
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ return Collections.singleton(BasicPermissions.EDIT_RESTORE_JOB.toAuthorization(eligibleResources));
+ }
+
@Override
protected void handleInternal(RoutingContext context,
HttpServerRequest httpRequest,
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/ClearSnapshotHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/ClearSnapshotHandler.java
index 3fdf21f4..9abfd15b 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/ClearSnapshotHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/ClearSnapshotHandler.java
@@ -20,16 +20,23 @@ package org.apache.cassandra.sidecar.routes.snapshots;
import java.io.FileNotFoundException;
import java.nio.file.NoSuchFileException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.server.StorageOperations;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.routes.data.SnapshotRequestParam;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
@@ -40,7 +47,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
* The <b>DELETE</b> verb deletes an existing snapshot for the given keyspace and table.
*/
@Singleton
-public class ClearSnapshotHandler extends AbstractHandler<SnapshotRequestParam>
+public class ClearSnapshotHandler extends AbstractHandler<SnapshotRequestParam> implements AccessProtected
{
@Inject
public ClearSnapshotHandler(InstanceMetadataFetcher metadataFetcher,
@@ -50,6 +57,13 @@ public class ClearSnapshotHandler extends AbstractHandler<SnapshotRequestParam>
super(metadataFetcher, executorPools, validator);
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ return Collections.singleton(BasicPermissions.DELETE_SNAPSHOT.toAuthorization(eligibleResources));
+ }
+
/**
* Clears a snapshot for the given keyspace and table. **Note**: Currently, Cassandra does not support
* the table parameter. We can add support in Cassandra for the additional parameter.
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/CreateSnapshotHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/CreateSnapshotHandler.java
index 9adb8e04..35a4a13f 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/CreateSnapshotHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/CreateSnapshotHandler.java
@@ -18,7 +18,10 @@
package org.apache.cassandra.sidecar.routes.snapshots;
+import java.util.Collections;
+import java.util.List;
import java.util.Map;
+import java.util.Set;
import com.google.common.collect.ImmutableMap;
import org.apache.commons.lang3.StringUtils;
@@ -29,12 +32,16 @@ import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.server.StorageOperations;
import org.apache.cassandra.sidecar.common.server.exceptions.NodeBootstrappingException;
import org.apache.cassandra.sidecar.common.server.exceptions.SnapshotAlreadyExistsException;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.routes.data.SnapshotRequestParam;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
@@ -45,7 +52,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
* The <b>PUT</b> verb creates a new snapshot for the given keyspace and table
*/
@Singleton
-public class CreateSnapshotHandler extends AbstractHandler<SnapshotRequestParam>
+public class CreateSnapshotHandler extends AbstractHandler<SnapshotRequestParam> implements AccessProtected
{
private static final String TTL_QUERY_PARAM = "ttl";
@@ -57,6 +64,13 @@ public class CreateSnapshotHandler extends AbstractHandler<SnapshotRequestParam>
super(metadataFetcher, executorPools, validator);
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ return Collections.singleton(BasicPermissions.CREATE_SNAPSHOT.toAuthorization(eligibleResources));
+ }
+
/**
* Creates a new snapshot for the given keyspace and table.
*
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/ListSnapshotHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/ListSnapshotHandler.java
index bdf1ad92..1909626a 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/ListSnapshotHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/snapshots/ListSnapshotHandler.java
@@ -20,7 +20,9 @@ package org.apache.cassandra.sidecar.routes.snapshots;
import java.io.FileNotFoundException;
import java.nio.file.NoSuchFileException;
+import java.util.Collections;
import java.util.List;
+import java.util.Set;
import java.util.stream.Stream;
import com.github.benmanes.caffeine.cache.Cache;
@@ -31,7 +33,10 @@ import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.response.ListSnapshotFilesResponse;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.config.CacheConfiguration;
@@ -39,6 +44,7 @@ import org.apache.cassandra.sidecar.config.ServiceConfiguration;
import org.apache.cassandra.sidecar.metrics.CacheStatsCounter;
import org.apache.cassandra.sidecar.metrics.SidecarMetrics;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.routes.data.SnapshotRequestParam;
import org.apache.cassandra.sidecar.snapshots.SnapshotPathBuilder;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
@@ -63,7 +69,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
* <i>"testSnapshot"</i> snapshot for the <i>"ks"</i> keyspace and the <i>"tbl"</i> table
*/
@Singleton
-public class ListSnapshotHandler extends AbstractHandler<SnapshotRequestParam>
+public class ListSnapshotHandler extends AbstractHandler<SnapshotRequestParam> implements AccessProtected
{
private static final String INCLUDE_SECONDARY_INDEX_FILES_QUERY_PARAM = "includeSecondaryIndexFiles";
public static final String SNAPSHOT_CACHE_NAME = "snapshot_cache";
@@ -87,6 +93,13 @@ public class ListSnapshotHandler extends AbstractHandler<SnapshotRequestParam>
this.cache = initializeCache(cacheConfiguration, sidecarMetrics.server().cache().snapshotCacheMetrics);
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ return Collections.singleton(BasicPermissions.READ_SNAPSHOT.toAuthorization(eligibleResources));
+ }
+
/**
* Lists paths of all the snapshot files of a given snapshot name.
* <p>
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableCleanupHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableCleanupHandler.java
index bffb9a54..cff3ad9a 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableCleanupHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableCleanupHandler.java
@@ -19,21 +19,28 @@
package org.apache.cassandra.sidecar.routes.sstableuploads;
import java.nio.file.NoSuchFileException;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
import com.google.inject.Inject;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
import org.apache.cassandra.sidecar.utils.SSTableUploadsPathBuilder;
/**
* Manages cleaning up uploaded SSTables
*/
-public class SSTableCleanupHandler extends AbstractHandler<String>
+public class SSTableCleanupHandler extends AbstractHandler<String> implements AccessProtected
{
private static final String UPLOAD_ID_PARAM = "uploadId";
private final SSTableUploadsPathBuilder uploadPathBuilder;
@@ -54,6 +61,13 @@ public class SSTableCleanupHandler extends AbstractHandler<String>
this.uploadPathBuilder = uploadPathBuilder;
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ return Collections.singleton(BasicPermissions.DELETE_STAGED_SSTABLE.toAuthorization(eligibleResources));
+ }
+
/**
* Handles cleaning up the SSTable upload staging directory
*
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableImportHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableImportHandler.java
index 847fc688..368dafcb 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableImportHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableImportHandler.java
@@ -19,6 +19,10 @@
package org.apache.cassandra.sidecar.routes.sstableuploads;
import java.nio.file.NoSuchFileException;
+import java.util.List;
+import java.util.Set;
+
+import com.google.common.collect.ImmutableSet;
import com.github.benmanes.caffeine.cache.Cache;
import com.google.inject.Inject;
@@ -26,12 +30,17 @@ import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Future;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
import io.vertx.ext.web.handler.HttpException;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.CassandraPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.response.SSTableImportResponse;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
import org.apache.cassandra.sidecar.exceptions.CassandraUnavailableException;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.routes.data.SSTableImportRequestParam;
import org.apache.cassandra.sidecar.utils.CacheFactory;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
@@ -44,7 +53,7 @@ import static org.apache.cassandra.sidecar.utils.HttpExceptions.wrapHttpExceptio
/**
* Imports SSTables, that have been previously uploaded, into Cassandra
*/
-public class SSTableImportHandler extends AbstractHandler<SSTableImportRequestParam>
+public class SSTableImportHandler extends AbstractHandler<SSTableImportRequestParam> implements AccessProtected
{
private final SSTableImporter importer;
private final SSTableUploadsPathBuilder uploadPathBuilder;
@@ -75,6 +84,15 @@ public class SSTableImportHandler extends AbstractHandler<SSTableImportRequestPa
this.cache = cacheFactory.ssTableImportCache();
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ Authorization modifyAuthorization = CassandraPermissions.MODIFY.toAuthorization(eligibleResources);
+ Authorization importAuthorization = BasicPermissions.IMPORT_STAGED_SSTABLE.toAuthorization(eligibleResources);
+ return ImmutableSet.of(modifyAuthorization, importAuthorization);
+ }
+
/**
* Import SSTables, that have been previously uploaded, into the Cassandra service
*
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableUploadHandler.java b/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableUploadHandler.java
index 67b6f653..8a062277 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableUploadHandler.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/routes/sstableuploads/SSTableUploadHandler.java
@@ -18,6 +18,9 @@
package org.apache.cassandra.sidecar.routes.sstableuploads;
+import java.util.Collections;
+import java.util.List;
+import java.util.Set;
import java.util.concurrent.TimeUnit;
import com.datastax.driver.core.KeyspaceMetadata;
@@ -29,7 +32,10 @@ import io.vertx.core.Vertx;
import io.vertx.core.file.FileSystem;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
import io.vertx.ext.web.RoutingContext;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.VariableAwareResource;
import org.apache.cassandra.sidecar.common.response.SSTableUploadResponse;
import org.apache.cassandra.sidecar.concurrent.ConcurrencyLimiter;
import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
@@ -40,6 +46,7 @@ import org.apache.cassandra.sidecar.metrics.instance.InstanceMetrics;
import org.apache.cassandra.sidecar.metrics.instance.InstanceResourceMetrics;
import org.apache.cassandra.sidecar.metrics.instance.UploadSSTableMetrics;
import org.apache.cassandra.sidecar.routes.AbstractHandler;
+import org.apache.cassandra.sidecar.routes.AccessProtected;
import org.apache.cassandra.sidecar.routes.data.SSTableUploadRequestParam;
import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
import org.apache.cassandra.sidecar.utils.DigestVerifier;
@@ -56,7 +63,7 @@ import static org.apache.cassandra.sidecar.utils.MetricUtils.parseSSTableCompone
* Handler for managing uploaded SSTable components
*/
@Singleton
-public class SSTableUploadHandler extends AbstractHandler<SSTableUploadRequestParam>
+public class SSTableUploadHandler extends AbstractHandler<SSTableUploadRequestParam> implements AccessProtected
{
private final FileSystem fs;
private final SSTableUploadConfiguration configuration;
@@ -96,6 +103,13 @@ public class SSTableUploadHandler extends AbstractHandler<SSTableUploadRequestPa
this.digestVerifierFactory = digestVerifierFactory;
}
+ @Override
+ public Set<Authorization> requiredAuthorizations()
+ {
+ List<String> eligibleResources = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.expandedResources();
+ return Collections.singleton(BasicPermissions.UPLOAD_STAGED_SSTABLE.toAuthorization(eligibleResources));
+ }
+
/**
* {@inheritDoc}
*/
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/server/MainModule.java b/server/src/main/java/org/apache/cassandra/sidecar/server/MainModule.java
index 609a9124..293075bd 100644
--- a/server/src/main/java/org/apache/cassandra/sidecar/server/MainModule.java
+++ b/server/src/main/java/org/apache/cassandra/sidecar/server/MainModule.java
@@ -23,6 +23,7 @@ import java.nio.file.Path;
import java.util.Collections;
import java.util.List;
import java.util.Map;
+import java.util.function.Supplier;
import java.util.stream.Collectors;
import com.google.common.util.concurrent.SidecarRateLimiter;
@@ -39,19 +40,26 @@ import io.netty.handler.codec.http.HttpResponseStatus;
import io.vertx.core.Vertx;
import io.vertx.core.VertxOptions;
import io.vertx.core.file.FileSystemOptions;
+import io.vertx.core.http.HttpMethod;
+import io.vertx.ext.auth.authorization.AuthorizationProvider;
import io.vertx.ext.dropwizard.DropwizardMetricsOptions;
import io.vertx.ext.dropwizard.Match;
import io.vertx.ext.dropwizard.MatchType;
import io.vertx.ext.web.Router;
-import io.vertx.ext.web.handler.BodyHandler;
import io.vertx.ext.web.handler.ChainAuthHandler;
import io.vertx.ext.web.handler.ErrorHandler;
import io.vertx.ext.web.handler.LoggerHandler;
import io.vertx.ext.web.handler.StaticHandler;
import io.vertx.ext.web.handler.TimeoutHandler;
+import org.apache.cassandra.sidecar.acl.IdentityToRoleCache;
import org.apache.cassandra.sidecar.acl.authentication.AuthenticationHandlerFactory;
import org.apache.cassandra.sidecar.acl.authentication.AuthenticationHandlerFactoryRegistry;
import org.apache.cassandra.sidecar.acl.authentication.MutualTlsAuthenticationHandlerFactory;
+import org.apache.cassandra.sidecar.acl.authorization.AdminIdentityResolver;
+import org.apache.cassandra.sidecar.acl.authorization.AllowAllAuthorizationProvider;
+import org.apache.cassandra.sidecar.acl.authorization.AuthorizationParameterValidateHandler;
+import org.apache.cassandra.sidecar.acl.authorization.RoleAuthorizationsCache;
+import org.apache.cassandra.sidecar.acl.authorization.RoleBasedAuthorizationProvider;
import org.apache.cassandra.sidecar.adapters.base.CassandraFactory;
import org.apache.cassandra.sidecar.adapters.cassandra41.Cassandra41Factory;
import org.apache.cassandra.sidecar.cluster.CQLSessionProviderImpl;
@@ -90,6 +98,7 @@ import org.apache.cassandra.sidecar.db.schema.RestoreRangesSchema;
import org.apache.cassandra.sidecar.db.schema.RestoreSlicesSchema;
import org.apache.cassandra.sidecar.db.schema.SidecarInternalKeyspace;
import org.apache.cassandra.sidecar.db.schema.SidecarLeaseSchema;
+import org.apache.cassandra.sidecar.db.schema.SidecarRolePermissionsSchema;
import org.apache.cassandra.sidecar.db.schema.SidecarSchema;
import org.apache.cassandra.sidecar.db.schema.SystemAuthSchema;
import org.apache.cassandra.sidecar.exceptions.ConfigurationException;
@@ -99,12 +108,15 @@ import org.apache.cassandra.sidecar.metrics.SchemaMetrics;
import org.apache.cassandra.sidecar.metrics.SidecarMetrics;
import org.apache.cassandra.sidecar.metrics.SidecarMetricsImpl;
import org.apache.cassandra.sidecar.metrics.instance.InstanceHealthMetrics;
+import org.apache.cassandra.sidecar.routes.AccessProtectedRouteBuilder;
import org.apache.cassandra.sidecar.routes.CassandraHealthHandler;
import org.apache.cassandra.sidecar.routes.ConnectedClientStatsHandler;
import org.apache.cassandra.sidecar.routes.DiskSpaceProtectionHandler;
import org.apache.cassandra.sidecar.routes.FileStreamHandler;
import org.apache.cassandra.sidecar.routes.GossipInfoHandler;
import org.apache.cassandra.sidecar.routes.JsonErrorHandler;
+import org.apache.cassandra.sidecar.routes.KeyspaceRingHandler;
+import org.apache.cassandra.sidecar.routes.KeyspaceSchemaHandler;
import org.apache.cassandra.sidecar.routes.ListOperationalJobsHandler;
import org.apache.cassandra.sidecar.routes.NodeDecommissionHandler;
import org.apache.cassandra.sidecar.routes.OperationalJobHandler;
@@ -246,11 +258,54 @@ public class MainModule extends AbstractModule
return chainAuthHandler;
}
+ @Provides
+ @Singleton
+ public AuthorizationProvider authorizationProvider(SidecarConfiguration sidecarConfiguration,
+ IdentityToRoleCache identityToRoleCache,
+ RoleAuthorizationsCache roleAuthorizationsCache)
+ {
+ AccessControlConfiguration accessControlConfiguration = sidecarConfiguration.accessControlConfiguration();
+ if (!accessControlConfiguration.enabled())
+ {
+ return new AllowAllAuthorizationProvider();
+ }
+
+ ParameterizedClassConfiguration config = accessControlConfiguration.authorizerConfiguration();
+ if (config == null)
+ {
+ throw new ConfigurationException("Access control is enabled, but authorizer not set");
+ }
+
+ if (config.className().equalsIgnoreCase(AllowAllAuthorizationProvider.class.getName()))
+ {
+ return new AllowAllAuthorizationProvider();
+ }
+ if (config.className().equalsIgnoreCase(RoleBasedAuthorizationProvider.class.getName()))
+ {
+ return new RoleBasedAuthorizationProvider(identityToRoleCache, roleAuthorizationsCache);
+ }
+ throw new ConfigurationException("Unrecognized authorization provider " + config.className() + " set");
+ }
+
+ @Provides
+ @Singleton
+ public Supplier<AccessProtectedRouteBuilder> accessProtectedRouteBuilderFactory(SidecarConfiguration sidecarConfiguration,
+ AuthorizationProvider authorizationProvider,
+ AdminIdentityResolver adminIdentityResolver,
+ AuthorizationParameterValidateHandler authorizationParameterValidateHandler)
+ {
+ return () -> new AccessProtectedRouteBuilder(sidecarConfiguration.accessControlConfiguration(),
+ authorizationProvider,
+ adminIdentityResolver,
+ authorizationParameterValidateHandler);
+ }
+
@Provides
@Singleton
public Router vertxRouter(Vertx vertx,
SidecarConfiguration sidecarConfiguration,
ChainAuthHandler chainAuthHandler,
+ Supplier<AccessProtectedRouteBuilder> protectedRouteBuilderFactory,
CassandraHealthHandler cassandraHealthHandler,
StreamSSTableComponentHandler streamSSTableComponentHandler,
FileStreamHandler fileStreamHandler,
@@ -258,7 +313,9 @@ public class MainModule extends AbstractModule
CreateSnapshotHandler createSnapshotHandler,
ListSnapshotHandler listSnapshotHandler,
SchemaHandler schemaHandler,
+ KeyspaceSchemaHandler keyspaceSchemaHandler,
RingHandler ringHandler,
+ KeyspaceRingHandler keyspaceRingHandler,
TokenRangeReplicaMapHandler tokenRangeHandler,
LoggerHandler loggerHandler,
GossipInfoHandler gossipInfoHandler,
@@ -309,7 +366,8 @@ public class MainModule extends AbstractModule
.handler(docs);
// Add custom routers
- // Provides a simple REST endpoint to determine if Sidecar is available
+ // Provides a simple REST endpoint to determine if Sidecar is available. Health endpoints in Sidecar are
+ // authenticated and exempted from authorization.
router.get(ApiEndpointsV1.HEALTH_ROUTE)
.handler(context -> context.json(OK_STATUS));
@@ -324,130 +382,197 @@ public class MainModule extends AbstractModule
router.get(ApiEndpointsV1.CASSANDRA_JMX_HEALTH_ROUTE)
.handler(cassandraHealthHandler);
- //noinspection deprecation
- router.get(ApiEndpointsV1.DEPRECATED_COMPONENTS_ROUTE)
- .handler(streamSSTableComponentHandler)
- .handler(fileStreamHandler);
+ // Node settings endpoint is not Access protected. Any user who can log in into Cassandra is able to view
+ // node settings information. Since sidecar and cassandra share list of authenticated identities, sidecar's
+ // authenticated users can also read node settings information.
+ router.get(ApiEndpointsV1.NODE_SETTINGS_ROUTE)
+ .handler(nodeSettingsHandler);
- router.get(ApiEndpointsV1.COMPONENTS_ROUTE)
- .handler(streamSSTableComponentHandler)
- .handler(fileStreamHandler);
+ router.get(ApiEndpointsV1.TIME_SKEW_ROUTE)
+ .handler(timeSkewHandler);
- // Support for routes that want to stream SStable index components
- router.get(ApiEndpointsV1.COMPONENTS_WITH_SECONDARY_INDEX_ROUTE_SUPPORT)
- .handler(streamSSTableComponentHandler)
- .handler(fileStreamHandler);
+ // NOTE: All routes in Sidecar must be built with AccessProtectedRouteBuilder. AccessProtectedRouteBuilder,
+ // skips adding AuthorizationHandler in handler chain if access control is disabled.
//noinspection deprecation
- router.get(ApiEndpointsV1.DEPRECATED_SNAPSHOTS_ROUTE)
- .handler(listSnapshotHandler);
-
- router.get(ApiEndpointsV1.SNAPSHOTS_ROUTE)
- .handler(listSnapshotHandler);
-
- router.delete(ApiEndpointsV1.SNAPSHOTS_ROUTE)
- // Leverage the validateTableExistence. Currently, JMX does not validate for non-existent keyspace.
- // Additionally, the current JMX implementation to clear snapshots does not support passing a table
- // as a parameter.
- .handler(validateTableExistence)
- .handler(clearSnapshotHandler);
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.DEPRECATED_COMPONENTS_ROUTE)
+ .handler(streamSSTableComponentHandler)
+ .handler(fileStreamHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.COMPONENTS_ROUTE)
+ .handler(streamSSTableComponentHandler)
+ .handler(fileStreamHandler)
+ .build();
- router.put(ApiEndpointsV1.SNAPSHOTS_ROUTE)
- .handler(createSnapshotHandler);
+ // Support for routes that want to stream SStable index components
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.COMPONENTS_WITH_SECONDARY_INDEX_ROUTE_SUPPORT)
+ .handler(streamSSTableComponentHandler)
+ .handler(fileStreamHandler)
+ .build();
//noinspection deprecation
- router.get(ApiEndpointsV1.DEPRECATED_ALL_KEYSPACES_SCHEMA_ROUTE)
- .handler(schemaHandler);
-
- router.get(ApiEndpointsV1.ALL_KEYSPACES_SCHEMA_ROUTE)
- .handler(schemaHandler);
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.DEPRECATED_SNAPSHOTS_ROUTE)
+ .handler(listSnapshotHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.SNAPSHOTS_ROUTE)
+ .handler(listSnapshotHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.DELETE)
+ .endpoint(ApiEndpointsV1.SNAPSHOTS_ROUTE)
+ // Leverage the validateTableExistence. Currently, JMX does not validate for non-existent keyspace.
+ // Additionally, the current JMX implementation to clear snapshots does not support passing a table
+ // as a parameter.
+ .handler(validateTableExistence)
+ .handler(clearSnapshotHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.PUT)
+ .endpoint(ApiEndpointsV1.SNAPSHOTS_ROUTE)
+ .handler(createSnapshotHandler)
+ .build();
//noinspection deprecation
- router.get(ApiEndpointsV1.DEPRECATED_KEYSPACE_SCHEMA_ROUTE)
- .handler(schemaHandler);
-
- router.get(ApiEndpointsV1.KEYSPACE_SCHEMA_ROUTE)
- .handler(schemaHandler);
-
- router.get(ApiEndpointsV1.RING_ROUTE)
- .handler(ringHandler);
-
- router.get(ApiEndpointsV1.CONNECTED_CLIENT_STATS_ROUTE)
- .handler(connectedClientStatsHandler);
-
- router.get(ApiEndpointsV1.OPERATIONAL_JOB_ROUTE)
- .handler(operationalJobHandler);
-
- router.get(ApiEndpointsV1.LIST_OPERATIONAL_JOBS_ROUTE)
- .handler(listOperationalJobsHandler);
-
- router.put(ApiEndpointsV1.NODE_DECOMMISSION_ROUTE)
- .handler(nodeDecommissionHandler);
-
- router.get(ApiEndpointsV1.RING_ROUTE_PER_KEYSPACE)
- .handler(ringHandler);
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.DEPRECATED_ALL_KEYSPACES_SCHEMA_ROUTE)
+ .handler(schemaHandler)
+ .build();
- router.put(ApiEndpointsV1.SSTABLE_UPLOAD_ROUTE)
- .handler(ssTableUploadHandler);
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.ALL_KEYSPACES_SCHEMA_ROUTE)
+ .handler(schemaHandler)
+ .build();
- router.get(ApiEndpointsV1.KEYSPACE_TOKEN_MAPPING_ROUTE)
- .handler(tokenRangeHandler);
-
- router.put(ApiEndpointsV1.SSTABLE_IMPORT_ROUTE)
- .handler(ssTableImportHandler);
-
- router.delete(ApiEndpointsV1.SSTABLE_CLEANUP_ROUTE)
- .handler(ssTableCleanupHandler);
-
- router.get(ApiEndpointsV1.GOSSIP_INFO_ROUTE)
- .handler(gossipInfoHandler);
-
- router.get(ApiEndpointsV1.TIME_SKEW_ROUTE)
- .handler(timeSkewHandler);
-
- router.get(ApiEndpointsV1.NODE_SETTINGS_ROUTE)
- .handler(nodeSettingsHandler);
-
- router.post(ApiEndpointsV1.CREATE_RESTORE_JOB_ROUTE)
- .handler(BodyHandler.create())
- .handler(validateTableExistence)
- .handler(validateRestoreJobRequest)
- .handler(createRestoreJobHandler);
-
- router.post(ApiEndpointsV1.RESTORE_JOB_SLICES_ROUTE)
- .handler(BodyHandler.create())
- .handler(diskSpaceProtection) // reject creating slice if short of disk space
- .handler(validateTableExistence)
- .handler(validateRestoreJobRequest)
- .handler(createRestoreSliceHandler);
-
- router.get(ApiEndpointsV1.RESTORE_JOB_ROUTE)
- .handler(validateTableExistence)
- .handler(validateRestoreJobRequest)
- .handler(restoreJobSummaryHandler);
-
- router.patch(ApiEndpointsV1.RESTORE_JOB_ROUTE)
- .handler(BodyHandler.create())
- .handler(validateTableExistence)
- .handler(validateRestoreJobRequest)
- .handler(updateRestoreJobHandler);
-
- router.post(ApiEndpointsV1.ABORT_RESTORE_JOB_ROUTE)
- .handler(BodyHandler.create())
- .handler(validateTableExistence)
- .handler(validateRestoreJobRequest)
- .handler(abortRestoreJobHandler);
-
- router.get(ApiEndpointsV1.RESTORE_JOB_PROGRESS_ROUTE)
- .handler(validateTableExistence)
- .handler(validateRestoreJobRequest)
- .handler(restoreJobProgressHandler);
+ //noinspection deprecation
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.DEPRECATED_KEYSPACE_SCHEMA_ROUTE)
+ .handler(keyspaceSchemaHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.KEYSPACE_SCHEMA_ROUTE)
+ .handler(keyspaceSchemaHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.RING_ROUTE)
+ .handler(ringHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.RING_ROUTE_PER_KEYSPACE)
+ .handler(keyspaceRingHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.CONNECTED_CLIENT_STATS_ROUTE)
+ .handler(connectedClientStatsHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.OPERATIONAL_JOB_ROUTE)
+ .handler(operationalJobHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.LIST_OPERATIONAL_JOBS_ROUTE)
+ .handler(listOperationalJobsHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.PUT)
+ .endpoint(ApiEndpointsV1.NODE_DECOMMISSION_ROUTE)
+ .handler(nodeDecommissionHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.PUT)
+ .endpoint(ApiEndpointsV1.SSTABLE_UPLOAD_ROUTE)
+ .handler(ssTableUploadHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.KEYSPACE_TOKEN_MAPPING_ROUTE)
+ .handler(tokenRangeHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.PUT)
+ .endpoint(ApiEndpointsV1.SSTABLE_IMPORT_ROUTE)
+ .handler(ssTableImportHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.DELETE)
+ .endpoint(ApiEndpointsV1.SSTABLE_CLEANUP_ROUTE)
+ .handler(ssTableCleanupHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.GOSSIP_INFO_ROUTE)
+ .handler(gossipInfoHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.POST)
+ .endpoint(ApiEndpointsV1.CREATE_RESTORE_JOB_ROUTE)
+ .setBodyHandler(true)
+ .handler(validateTableExistence)
+ .handler(validateRestoreJobRequest)
+ .handler(createRestoreJobHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.POST)
+ .endpoint(ApiEndpointsV1.RESTORE_JOB_SLICES_ROUTE)
+ .setBodyHandler(true)
+ .handler(diskSpaceProtection) // reject creating slice if short of disk space
+ .handler(validateTableExistence)
+ .handler(validateRestoreJobRequest)
+ .handler(createRestoreSliceHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.RESTORE_JOB_ROUTE)
+ .handler(validateTableExistence)
+ .handler(validateRestoreJobRequest)
+ .handler(restoreJobSummaryHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.PATCH)
+ .endpoint(ApiEndpointsV1.RESTORE_JOB_ROUTE)
+ .setBodyHandler(true)
+ .handler(validateTableExistence)
+ .handler(validateRestoreJobRequest)
+ .handler(updateRestoreJobHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.POST)
+ .endpoint(ApiEndpointsV1.ABORT_RESTORE_JOB_ROUTE)
+ .setBodyHandler(true)
+ .handler(validateTableExistence)
+ .handler(validateRestoreJobRequest)
+ .handler(abortRestoreJobHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.RESTORE_JOB_PROGRESS_ROUTE)
+ .handler(validateTableExistence)
+ .handler(validateRestoreJobRequest)
+ .handler(restoreJobProgressHandler)
+ .build();
// CDC APIs
- router.get(ApiEndpointsV1.LIST_CDC_SEGMENTS_ROUTE)
- .handler(listCdcDirHandler);
- router.get(ApiEndpointsV1.STREAM_CDC_SEGMENTS_ROUTE)
- .handler(streamCdcSegmentHandler);
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.LIST_CDC_SEGMENTS_ROUTE)
+ .handler(listCdcDirHandler)
+ .build();
+
+ protectedRouteBuilderFactory.get().router(router).method(HttpMethod.GET)
+ .endpoint(ApiEndpointsV1.STREAM_CDC_SEGMENTS_ROUTE)
+ .handler(streamCdcSegmentHandler)
+ .build();
return router;
}
@@ -479,7 +604,8 @@ public class MainModule extends AbstractModule
@Provides
@Singleton
- public CQLSessionProvider cqlSessionProvider(Vertx vertx, SidecarConfiguration sidecarConfiguration,
+ public CQLSessionProvider cqlSessionProvider(Vertx vertx,
+ SidecarConfiguration sidecarConfiguration,
DriverUtils driverUtils)
{
CQLSessionProviderImpl cqlSessionProvider = new CQLSessionProviderImpl(sidecarConfiguration,
@@ -642,6 +768,7 @@ public class MainModule extends AbstractModule
RestoreJobsSchema restoreJobsSchema,
RestoreSlicesSchema restoreSlicesSchema,
RestoreRangesSchema restoreRangesSchema,
+ SidecarRolePermissionsSchema sidecarRolePermissionsSchema,
SystemAuthSchema systemAuthSchema,
SidecarLeaseSchema sidecarLeaseSchema,
SidecarMetrics metrics,
@@ -651,6 +778,7 @@ public class MainModule extends AbstractModule
sidecarInternalKeyspace.registerTableSchema(restoreJobsSchema);
sidecarInternalKeyspace.registerTableSchema(restoreSlicesSchema);
sidecarInternalKeyspace.registerTableSchema(restoreRangesSchema);
+ sidecarInternalKeyspace.registerTableSchema(sidecarRolePermissionsSchema);
sidecarInternalKeyspace.registerTableSchema(systemAuthSchema);
sidecarInternalKeyspace.registerTableSchema(sidecarLeaseSchema);
SchemaMetrics schemaMetrics = metrics.server().schema();
diff --git a/server/src/main/java/org/apache/cassandra/sidecar/utils/AuthUtils.java b/server/src/main/java/org/apache/cassandra/sidecar/utils/AuthUtils.java
new file mode 100644
index 00000000..d7e337d6
--- /dev/null
+++ b/server/src/main/java/org/apache/cassandra/sidecar/utils/AuthUtils.java
@@ -0,0 +1,84 @@
+/*
+ * 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.utils;
+
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.Objects;
+
+import io.vertx.core.json.JsonObject;
+import io.vertx.ext.auth.User;
+import org.apache.cassandra.sidecar.acl.authorization.DomainAwarePermission;
+import org.apache.cassandra.sidecar.acl.authorization.Permission;
+import org.apache.cassandra.sidecar.acl.authorization.StandardPermission;
+
+import static org.apache.cassandra.sidecar.acl.authorization.DomainAwarePermission.WILDCARD_PART_DIVIDER_TOKEN;
+
+/**
+ * Class with utility methods for Authentication and Authorization.
+ */
+public class AuthUtils
+{
+ /**
+ * Extracts a list of identities a user holds from their principal.
+ *
+ * @param user User object in Vertx
+ * @return extracted identities of user
+ */
+ public static List<String> extractIdentities(User user)
+ {
+ JsonObject principal = user.principal();
+
+ if (principal == null)
+ {
+ return Collections.emptyList();
+ }
+
+ List<String> identities = new ArrayList<>();
+
+ String identity = principal.getString("identity");
+ if (identity != null)
+ {
+ identities.add(identity);
+ }
+
+ String identitiesString = user.principal().getString("identities");
+ if (identitiesString != null)
+ {
+ String[] parts = identitiesString.split(",");
+ identities.addAll(Arrays.asList(parts));
+ }
+ return Collections.unmodifiableList(identities);
+ }
+
+ /**
+ * Construct {@link Permission} given the permission name.
+ *
+ * @param name name of permission
+ * @return an instance of {@link Permission} given the name
+ */
+ public static Permission permissionFromName(String name)
+ {
+ Objects.requireNonNull(name, "name cannot be null");
+ boolean isDomainAware = name.contains(WILDCARD_PART_DIVIDER_TOKEN);
+ return isDomainAware ? new DomainAwarePermission(name) : new StandardPermission(name);
+ }
+}
diff --git a/server/src/test/integration/org/apache/cassandra/sidecar/acl/MutualTLSAuthenticationIntegrationTest.java b/server/src/test/integration/org/apache/cassandra/sidecar/acl/MutualTLSAuthenticationIntegrationTest.java
index d1636958..97d3afe8 100644
--- a/server/src/test/integration/org/apache/cassandra/sidecar/acl/MutualTLSAuthenticationIntegrationTest.java
+++ b/server/src/test/integration/org/apache/cassandra/sidecar/acl/MutualTLSAuthenticationIntegrationTest.java
@@ -63,8 +63,12 @@ class MutualTLSAuthenticationIntegrationTest extends IntegrationTestBase
if (cassandraTestContext.version.major == 5)
{
insertIdentityRole("spiffe://cassandra/sidecar/test", "cassandra-role");
+ grantSidecarPermission("cassandra-role", "cluster", "SCHEMA:READ");
}
+ // wait for cache refresh to pick by granted SCHEMA:READ permission
+ Thread.sleep(2000L);
+
String testRoute = "/api/v1/schema/keyspaces";
Path clientKeystorePath = clientKeystorePath("spiffe://cassandra/sidecar/test");
WebClient client = createClient(clientKeystorePath, truststorePath);
@@ -135,4 +139,11 @@ class MutualTLSAuthenticationIntegrationTest extends IntegrationTestBase
Session session = maybeGetSession();
session.execute("INSERT INTO system_auth.identity_to_role (identity, role) VALUES (\'" + identity + "\',\'" + role + "\');");
}
+
+ private void grantSidecarPermission(String role, String resource, String permission)
+ {
+ Session session = maybeGetSession();
+ session.execute(String.format("INSERT INTO sidecar_internal.role_permissions_v1 (role, resource, permissions) " +
+ "VALUES ('%s', '%s', {'%s'})", role, resource, permission));
+ }
}
diff --git a/server/src/test/integration/org/apache/cassandra/sidecar/acl/RoleBasedAuthorizationIntegrationTest.java b/server/src/test/integration/org/apache/cassandra/sidecar/acl/RoleBasedAuthorizationIntegrationTest.java
new file mode 100644
index 00000000..def06cdd
--- /dev/null
+++ b/server/src/test/integration/org/apache/cassandra/sidecar/acl/RoleBasedAuthorizationIntegrationTest.java
@@ -0,0 +1,418 @@
+/*
+ * 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;
+
+import java.nio.file.Path;
+import java.util.Comparator;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import org.junit.jupiter.api.extension.ExtendWith;
+
+import com.datastax.driver.core.Session;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.Future;
+import io.vertx.core.Promise;
+import io.vertx.core.buffer.Buffer;
+import io.vertx.core.http.HttpMethod;
+import io.vertx.ext.web.client.HttpResponse;
+import io.vertx.ext.web.client.WebClient;
+import io.vertx.junit5.VertxExtension;
+import io.vertx.junit5.VertxTestContext;
+import org.apache.cassandra.sidecar.common.response.ListSnapshotFilesResponse;
+import org.apache.cassandra.sidecar.testing.IntegrationTestBase;
+import org.apache.cassandra.testing.AuthMode;
+import org.apache.cassandra.testing.CassandraIntegrationTest;
+import org.apache.cassandra.testing.CassandraTestContext;
+
+import static org.apache.cassandra.sidecar.testing.IntegrationTestModule.ADMIN_IDENTITY;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assumptions.assumeThat;
+
+/**
+ * Test for role based access control in Sidecar
+ * Note: Do not add new test cases in this class. Add them into test method, example refer to testForAdmin
+ */
+@ExtendWith(VertxExtension.class)
+class RoleBasedAuthorizationIntegrationTest extends IntegrationTestBase
+{
+ private static final int MIN_VERSION_WITH_MTLS = 5;
+
+ private Path nonAdminClientKeystorePath;
+ private CountDownLatch testCompleteLatch;
+
+ @CassandraIntegrationTest(authMode = AuthMode.MUTUAL_TLS)
+ void testAuthorizationScenarios(VertxTestContext context, CassandraTestContext cassandraContext) throws Exception
+ {
+ prepareForTest(cassandraContext);
+
+ // wait for cache refreshes
+ Thread.sleep(3000);
+
+ testCompleteLatch = new CountDownLatch(16);
+
+ // permissions for test cases below are granted during prepareForTest to save cache refresh time. Please
+ // refer to grantRequiredPermissions to check permissions granted for a test to understand verifications done in
+ // test
+ testForAdmin(context);
+ testForSuperUser(context);
+ testForNonAdmin(context);
+ testGrantingForTable(context);
+ testGrantingForKeyspace(context);
+ testGrantingAllTablesExceptKeyspace(context);
+ testGrantingAtDataLevel(context);
+ testGrantingWithWildcardSubparts(context);
+ testEndpointRequiringMultipleActions(context);
+
+ assertThat(testCompleteLatch.await(4, TimeUnit.MINUTES)).isTrue();
+ context.completeNow();
+ }
+
+ void testForAdmin(VertxTestContext context)
+ {
+ String keyspaceSchemaRoute = String.format("/api/v1/keyspaces/%s/schema", "test_keyspace");
+ // uses client keystore with admin identity. Admins bypass authorization checks
+
+ verifyAccess(context, testCompleteLatch, HttpMethod.GET, keyspaceSchemaRoute, clientKeystorePath, false);
+ }
+
+ void testForSuperUser(VertxTestContext context) throws Exception
+ {
+ String keyspaceSchemaRoute = String.format("/api/v1/keyspaces/%s/schema", "test_keyspace");
+ // uses client keystore with superuser identity
+ Path clientKeystorePath = clientKeystorePath("spiffe://cassandra/sidecar/super_user_test_user");
+
+ verifyAccess(context, testCompleteLatch, HttpMethod.GET, keyspaceSchemaRoute, clientKeystorePath, false);
+ }
+
+ void testForNonAdmin(VertxTestContext context)
+ {
+ String keyspaceSchemaRoute = String.format("/api/v1/keyspaces/%s/schema", "non_admin_test_keyspace");
+
+ verifyAccess(context, testCompleteLatch, HttpMethod.GET, keyspaceSchemaRoute, nonAdminClientKeystorePath, false);
+ }
+
+ void testGrantingForTable(VertxTestContext context)
+ {
+ String createSnapshotRoute = String.format("/api/v1/keyspaces/%s/tables/%s/snapshots/my-snapshot",
+ "grant_table_test_keyspace", "test_table");
+
+ // SNAPSHOT:CREATE permission granted for data/grant_table_test_keyspace/test_table
+ verifyAccess(context, testCompleteLatch, HttpMethod.PUT, createSnapshotRoute, nonAdminClientKeystorePath, false);
+
+ // SNAPSHOT:DELETE permission not granted for data/grant_table_test_keyspace/test_table
+ verifyAccess(context, testCompleteLatch, HttpMethod.DELETE, createSnapshotRoute, nonAdminClientKeystorePath, true);
+ }
+
+ void testGrantingForKeyspace(VertxTestContext context)
+ {
+ String createSnapshotRoute = String.format("/api/v1/keyspaces/%s/tables/%s/snapshots/my-snapshot",
+ "grant_keyspace_test_keyspace", "test_table");
+
+ // SNAPSHOT:CREATE permission granted for data/grant_keyspace_test_keyspace/test_table with
+ // data/grant_tables_test_keyspace grant
+ verifyAccess(context, testCompleteLatch, HttpMethod.PUT, createSnapshotRoute, nonAdminClientKeystorePath, false);
+
+ // access not granted for different keyspace
+ String notAllowedSnapshotRoute = String.format("/api/v1/keyspaces/%s/tables/%s/snapshots/my-snapshot",
+ "not_allowed_keyspace", "test_table");
+ verifyAccess(context, testCompleteLatch, HttpMethod.PUT, notAllowedSnapshotRoute, nonAdminClientKeystorePath, true);
+
+ // SNAPSHOT:DELETE permission not granted for data/grant_keyspace_test_keyspace/test_table
+ verifyAccess(context, testCompleteLatch, HttpMethod.DELETE, createSnapshotRoute, nonAdminClientKeystorePath, true);
+ }
+
+ void testGrantingAllTablesExceptKeyspace(VertxTestContext context)
+ {
+ String createSnapshotRoute = String.format("/api/v1/keyspaces/%s/tables/%s/snapshots/my-snapshot",
+ "grant_tables_except_keyspace_test_keyspace", "test_table");
+
+ // SNAPSHOT:CREATE permission granted for data/grant_tables_except_keyspace_test_keyspace/test_table
+ // with data/grant_tables_except_keyspace_test_keyspace grant
+ verifyAccess(context, testCompleteLatch, HttpMethod.PUT, createSnapshotRoute, nonAdminClientKeystorePath, false);
+
+ // SCHEMA:READ is not granted since it expects permissions at keyspace level
+ String keyspaceSchemaRoute = String.format("/api/v1/keyspaces/%s/schema", "grant_tables_except_keyspace_test_keyspace");
+ verifyAccess(context, testCompleteLatch, HttpMethod.GET, keyspaceSchemaRoute, nonAdminClientKeystorePath, true);
+ }
+
+ void testGrantingAtDataLevel(VertxTestContext context) throws Exception
+ {
+ String createSnapshotRoute = String.format("/api/v1/keyspaces/%s/tables/%s/snapshots/my-snapshot",
+ "test_keyspace", "test_table");
+ Path clientKeystorePath = clientKeystorePath("spiffe://cassandra/sidecar/grant_data_test_user");
+
+ // SNAPSHOT:CREATE permission granted for data/test_keyspace/test_table with data resource grant
+ verifyAccess(context, testCompleteLatch, HttpMethod.PUT, createSnapshotRoute, clientKeystorePath, false);
+
+ // SNAPSHOT:DELETE permission not granted for data/test_keyspace/test_table not granted
+ verifyAccess(context, testCompleteLatch, HttpMethod.DELETE, createSnapshotRoute, clientKeystorePath, true);
+ }
+
+ void testGrantingWithWildcardSubparts(VertxTestContext context) throws Exception
+ {
+ String schemaRoute = "/api/v1/cassandra/schema";
+ String gossipRoute = "/api/v1/cassandra/gossip";
+ String ringRoute = "/api/v1/cassandra/ring";
+ Path clientKeystorePath = clientKeystorePath("spiffe://cassandra/sidecar/wildcard_with_subparts_test_user");
+
+ // SCHEMA:READ permission granted for cluster with GOSSIP,SCHEMA:READ
+ verifyAccess(context, testCompleteLatch, HttpMethod.GET, schemaRoute, clientKeystorePath, false);
+
+ // GOSSIP:READ permission granted for cluster with GOSSIP,SCHEMA:READ
+ verifyAccess(context, testCompleteLatch, HttpMethod.GET, gossipRoute, clientKeystorePath, false);
+
+ // RING:READ permission not granted with GOSSIP,SCHEMA:READ
+ verifyAccess(context, testCompleteLatch, HttpMethod.GET, ringRoute, clientKeystorePath, true);
+ }
+
+ void testEndpointRequiringMultipleActions(VertxTestContext context)
+ {
+ String createSnapshotRoute = String.format("/api/v1/keyspaces/%s/tables/%s/snapshots/my-snapshot",
+ "multiple_permissions_required_test_keyspace", "test_table");
+
+ String listSnapshotRoute
+ = String.format("/api/v1/keyspaces/%s/tables/%s/snapshots/%s",
+ "multiple_permissions_required_test_keyspace", "test_table", "my-snapshot");
+
+ // SNAPSHOT:CREATE permission granted for data/multiple_permissions_required_test_keyspace/test_table
+ WebClient client = createClient(nonAdminClientKeystorePath, truststorePath);
+
+ createReq(client, HttpMethod.PUT, createSnapshotRoute)
+ .compose(createResp -> {
+ // grant sidecar permission for streaming
+ updateSidecarPermission("non_admin_test_role",
+ "data/multiple_permissions_required_test_keyspace/test_table",
+ "SNAPSHOT:READ");
+
+ // wait for cache refresh
+ return waitForCacheRefresh(2000)
+ .compose(v -> createReq(client, HttpMethod.GET, listSnapshotRoute));
+ })
+ .compose(listSnapshotResp -> {
+ ListSnapshotFilesResponse snapshotFiles = listSnapshotResp.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());
+
+ // grant sidecar permission for streaming
+ updateSidecarPermission("non_admin_test_role",
+ "data/multiple_permissions_required_test_keyspace/test_table",
+ "SNAPSHOT:STREAM");
+
+ return waitForCacheRefresh(2000)
+ // STREAM SSTable request requires both Sidecar SNAPSHOT:STREAM permission and Cassandra's SELECT
+ // permission on a table it accesses data.
+ .compose(v -> createReq(client, HttpMethod.GET, filesToStream.get(0).componentDownloadUrl()))
+ .compose(deniedStreamResp -> {
+ // request denied without SELECT permission
+ assertThat(deniedStreamResp.statusCode()).isEqualTo(HttpResponseStatus.FORBIDDEN.code());
+
+ // grant SELECT permission with cassandra role
+ grantTablePermission("multiple_permissions_required_test_keyspace", "test_table", "non_admin_test_role");
+
+ return waitForCacheRefresh(2000);
+ }).compose(v -> createReq(client, HttpMethod.GET, filesToStream.get(0).componentDownloadUrl()));
+ })
+ .onSuccess(acceptedStreamResp -> {
+ // stream request goes through with both SNAPSHOT:STREAM and SELECT permissions
+ assertThat(acceptedStreamResp.statusCode()).isEqualTo(HttpResponseStatus.OK.code());
+ testCompleteLatch.countDown();
+ })
+ .onFailure(context::failNow);
+ }
+
+ private void prepareForTest(CassandraTestContext cassandraContext) throws Exception
+ {
+ // mTLS authentication was added in Cassandra starting 5.0 version
+ assumeThat(cassandraContext.version.major)
+ .withFailMessage("mTLS authentication is not supported in 4.0 Cassandra version")
+ .isGreaterThanOrEqualTo(MIN_VERSION_WITH_MTLS);
+
+ // required for authentication of sidecar requests to Cassandra. Only superusers can grant permissions
+ insertIdentityRole(cassandraContext, ADMIN_IDENTITY, "cassandra");
+
+ waitForSchemaReady(30, TimeUnit.SECONDS);
+ createRequiredKeyspaceTables();
+ createRequiredRoles(cassandraContext);
+ grantRequiredPermissions();
+ createRequiredKeystores();
+ }
+
+ private void insertIdentityRole(CassandraTestContext cassandraContext, String identity, String role)
+ {
+ String statement = String.format("INSERT INTO system_auth.identity_to_role (identity, role) VALUES ('%s','%s')",
+ identity, role);
+ cassandraContext.cluster().schemaChangeIgnoringStoppedInstances(statement);
+ }
+
+ private void createRequiredKeyspaceTables()
+ {
+ createKeyspace("test_keyspace");
+ createKeyspace("non_admin_test_keyspace");
+ createKeyspace("grant_table_test_keyspace");
+ createKeyspace("grant_keyspace_test_keyspace");
+ createKeyspace("grant_tables_except_keyspace_test_keyspace");
+ createKeyspace("multiple_permissions_required_test_keyspace");
+ createTable("test_keyspace", "test_table");
+ createTable("non_admin_test_keyspace", "test_table");
+ createTable("grant_table_test_keyspace", "test_table");
+ createTable("grant_keyspace_test_keyspace", "test_table");
+ createTable("grant_tables_except_keyspace_test_keyspace", "test_table");
+ createTable("multiple_permissions_required_test_keyspace", "test_table");
+ }
+
+ private void createRequiredRoles(CassandraTestContext cassandraContext)
+ {
+ createRole("super_user_test_role", true);
+ insertIdentityRole(cassandraContext, "spiffe://cassandra/sidecar/super_user_test_user", "super_user_test_role");
+
+ createRole("non_admin_test_role", false);
+ insertIdentityRole(cassandraContext, "spiffe://cassandra/sidecar/non_admin_test_user", "non_admin_test_role");
+
+ createRole("grant_data_test_role", false);
+ insertIdentityRole(cassandraContext, "spiffe://cassandra/sidecar/grant_data_test_user", "grant_data_test_role");
+
+ createRole("wildcard_across_targets_test_role", false);
+ insertIdentityRole(cassandraContext, "spiffe://cassandra/sidecar/wildcard_across_targets_test_user", "wildcard_across_targets_test_role");
+
+ createRole("wildcard_with_subparts_test_role", false);
+ insertIdentityRole(cassandraContext, "spiffe://cassandra/sidecar/wildcard_with_subparts_test_user", "wildcard_with_subparts_test_role");
+ }
+
+ private void grantRequiredPermissions()
+ {
+ // permission for testForNonAdmin
+ grantSidecarPermission("non_admin_test_role", "data/non_admin_test_keyspace", "SCHEMA:READ");
+
+ // permission for testGrantingForTable
+ grantSidecarPermission("non_admin_test_role", "data/grant_table_test_keyspace/test_table", "SNAPSHOT:CREATE");
+
+ // permission for testGrantingForKeyspace
+ grantSidecarPermission("non_admin_test_role", "data/grant_keyspace_test_keyspace", "SNAPSHOT:CREATE");
+
+ // permission for testGrantingAllTablesExceptKeyspace
+ grantSidecarPermission("non_admin_test_role", "data/grant_tables_except_keyspace_test_keyspace/*", "SNAPSHOT:CREATE");
+
+ // permission for testGrantingAtDataLevel
+ grantSidecarPermission("grant_data_test_role", "data", "SNAPSHOT:CREATE");
+
+ // permission for testGrantingWithWildcardSubparts
+ grantSidecarPermission("wildcard_with_subparts_test_role", "cluster", "GOSSIP,SCHEMA:READ");
+
+ // permission for testEndpointRequiringMultipleActions
+ grantSidecarPermission("non_admin_test_role",
+ "data/multiple_permissions_required_test_keyspace/test_table",
+ "SNAPSHOT:CREATE");
+ }
+
+ private void createRequiredKeystores() throws Exception
+ {
+ nonAdminClientKeystorePath = clientKeystorePath("spiffe://cassandra/sidecar/non_admin_test_user");
+ }
+
+ private void createRole(String role, boolean superUser)
+ {
+ Session session = maybeGetSession();
+ session.execute("CREATE ROLE " + role + " WITH PASSWORD = 'password' AND SUPERUSER = " + superUser + " AND LOGIN = true;");
+ }
+
+ private void createKeyspace(String keyspace)
+ {
+ Session session = maybeGetSession();
+ session.execute("CREATE KEYSPACE IF NOT EXISTS " + keyspace + " WITH REPLICATION = {'class':'SimpleStrategy', 'replication_factor':'3'}");
+ }
+
+ private void createTable(String keyspace, String table)
+ {
+ Session session = maybeGetSession();
+ session.execute(String.format("CREATE TABLE %s.%s (a int, b text, PRIMARY KEY (a));", keyspace, table));
+ session.execute("INSERT INTO " + keyspace + "." + table + " (a, b) VALUES (1, 'text');");
+ }
+
+ private void grantTablePermission(String keyspace, String table, String role)
+ {
+ Session session = maybeGetSession();
+ session.execute("GRANT ALL PERMISSIONS ON " + keyspace + "." + table + " TO " + role);
+ }
+
+ private void grantSidecarPermission(String role, String resource, String permission)
+ {
+ Session session = maybeGetSession();
+ session.execute(String.format("INSERT INTO sidecar_internal.role_permissions_v1 (role, resource, permissions) " +
+ "VALUES ('%s', '%s', {'%s'})", role, resource, permission));
+ }
+
+ private void updateSidecarPermission(String role, String resource, String permission)
+ {
+ Session session = maybeGetSession();
+ session.execute(String.format("UPDATE sidecar_internal.role_permissions_v1 SET permissions = permissions + {'%s'} " +
+ "where role = '%s' and resource = '%s'", permission, role, resource));
+ }
+
+ private void verifyAccess(VertxTestContext context, CountDownLatch countDownLatch, HttpMethod method,
+ String testRoute, Path clientKeystorePath, boolean expectForbidden)
+ {
+ WebClient client = createClient(clientKeystorePath, truststorePath);
+ client.request(method, server.actualPort(), "127.0.0.1", testRoute)
+ .send(response -> {
+ if (response.cause() != null)
+ {
+ context.failNow(response.cause());
+ return;
+ }
+
+ if (expectForbidden)
+ {
+ if (response.result().statusCode() != HttpResponseStatus.FORBIDDEN.code())
+ {
+ context.failNow(HttpResponseStatus.FORBIDDEN.code() + " expected but got " + response.result().statusCode());
+ return;
+ }
+ }
+ else
+ {
+ if (response.result().statusCode() != HttpResponseStatus.OK.code())
+ {
+ context.failNow(HttpResponseStatus.OK.code() + " expected but got " + response.result().statusCode());
+ return;
+ }
+ }
+ countDownLatch.countDown();
+ });
+ }
+
+ private Future<HttpResponse<Buffer>> createReq(WebClient client, HttpMethod method, String route)
+ {
+ return client.request(method, server.actualPort(), "127.0.0.1", route).send();
+ }
+
+ // Helper method to wait for cache refresh
+ private Future<Void> waitForCacheRefresh(long durationMillis)
+ {
+ Promise<Void> promise = Promise.promise();
+ vertx.setTimer(durationMillis, id -> promise.complete());
+ return promise.future();
+ }
+}
diff --git a/server/src/test/integration/org/apache/cassandra/sidecar/cluster/locator/CqlSessionProviderIntegrationTest.java b/server/src/test/integration/org/apache/cassandra/sidecar/cluster/locator/CqlSessionProviderIntegrationTest.java
index cef9e458..5c530c1e 100644
--- a/server/src/test/integration/org/apache/cassandra/sidecar/cluster/locator/CqlSessionProviderIntegrationTest.java
+++ b/server/src/test/integration/org/apache/cassandra/sidecar/cluster/locator/CqlSessionProviderIntegrationTest.java
@@ -18,24 +18,19 @@
package org.apache.cassandra.sidecar.cluster.locator;
-import java.util.Collections;
import java.util.concurrent.TimeUnit;
import org.junit.jupiter.api.extension.ExtendWith;
-import com.datastax.driver.core.Session;
import io.vertx.ext.web.client.WebClient;
import io.vertx.junit5.VertxExtension;
import io.vertx.junit5.VertxTestContext;
import org.apache.cassandra.sidecar.common.response.ConnectedClientStatsResponse;
import org.apache.cassandra.sidecar.common.response.data.ClientConnectionEntry;
-import org.apache.cassandra.sidecar.config.SslConfiguration;
-import org.apache.cassandra.sidecar.config.yaml.KeyStoreConfigurationImpl;
-import org.apache.cassandra.sidecar.config.yaml.SslConfigurationImpl;
import org.apache.cassandra.sidecar.testing.IntegrationTestBase;
+import org.apache.cassandra.testing.AuthMode;
import org.apache.cassandra.testing.CassandraIntegrationTest;
-import org.apache.cassandra.testing.ConfigurableCassandraTestContext;
-import software.amazon.awssdk.utils.ImmutableMap;
+import org.apache.cassandra.testing.CassandraTestContext;
import static org.apache.cassandra.sidecar.testing.IntegrationTestModule.ADMIN_IDENTITY;
import static org.assertj.core.api.Assertions.assertThat;
@@ -49,99 +44,43 @@ class CqlSessionProviderIntegrationTest extends IntegrationTestBase
{
private static final int MIN_VERSION_WITH_MTLS = 5;
- @CassandraIntegrationTest(buildCluster = false)
- void testWithUsernamePassword(VertxTestContext context, ConfigurableCassandraTestContext cassandraContext) throws Exception
+ @CassandraIntegrationTest(authMode = AuthMode.PASSWORD)
+ void testWithUsernamePassword(VertxTestContext context) throws Exception
{
- cassandraContext.configureAndStartCluster(builder -> {
- builder.appendConfig(config -> config.set("authenticator", "org.apache.cassandra.auth.PasswordAuthenticator"));
- });
- sidecarTestContext.refreshInstancesMetadata();
waitForSchemaReady(30, TimeUnit.SECONDS);
retrieveClientStats(context, "cassandra", false);
}
- @CassandraIntegrationTest(buildCluster = false)
- void testWithSSLOnly(VertxTestContext context, ConfigurableCassandraTestContext cassandraContext) throws Exception
+ @CassandraIntegrationTest(enableSsl = true)
+ void testWithSSLOnly(VertxTestContext context) throws Exception
{
- cassandraContext.configureAndStartCluster(builder -> {
- builder.appendConfig(config ->
- // dot-separated options are not supported in 4.0
- config.set("client_encryption_options", ImmutableMap.of("enabled", "true",
- "require_client_auth", "false",
- "keystore", serverKeystorePath.toAbsolutePath().toString(),
- "keystore_password", serverKeystorePassword)));
- });
sidecarTestContext.setUsernamePassword(null, null);
- sidecarTestContext.setSslConfiguration(sslConfigWithTruststore());
waitForSchemaReady(30, TimeUnit.SECONDS);
// we enable only SSL and do not set any authenticator, hence username is "anonymous"
retrieveClientStats(context, "anonymous", true);
}
- @CassandraIntegrationTest(buildCluster = false)
- void testWithSSLOnlyWithUsername(VertxTestContext context, ConfigurableCassandraTestContext cassandraContext) throws Exception
+ @CassandraIntegrationTest(enableSsl = true, authMode = AuthMode.PASSWORD)
+ void testWithSSLOnlyWithUsername(VertxTestContext context) throws Exception
{
- cassandraContext.configureAndStartCluster(builder -> {
- builder.appendConfig(config -> config.set("authenticator", "org.apache.cassandra.auth.PasswordAuthenticator"));
-
- builder.appendConfig(config ->
- // dot-separated options are not supported in 4.0
- config.set("client_encryption_options", ImmutableMap.of("enabled", "true",
- "require_client_auth", "false",
- "keystore", serverKeystorePath.toAbsolutePath().toString(),
- "keystore_password", serverKeystorePassword)));
- });
sidecarTestContext.setUsernamePassword("cassandra", "cassandra");
- sidecarTestContext.setSslConfiguration(sslConfigWithTruststore());
waitForSchemaReady(30, TimeUnit.SECONDS);
// we enable only SSL and do not set any authenticator, hence username is "anonymous"
retrieveClientStats(context, "cassandra", true);
}
- @CassandraIntegrationTest(buildCluster = false)
- void testWithMTLS(VertxTestContext context, ConfigurableCassandraTestContext cassandraContext) throws Exception
+ @CassandraIntegrationTest(authMode = AuthMode.MUTUAL_TLS)
+ void testWithMTLS(VertxTestContext context, CassandraTestContext cassandraTestContext) throws Exception
{
// mTLS authentication was added in Cassandra starting 5.0 version
- assumeThat(cassandraContext.version.major)
+ assumeThat(cassandraTestContext.version.major)
.withFailMessage("mTLS authentication is not supported in 4.0 Cassandra version")
.isGreaterThanOrEqualTo(MIN_VERSION_WITH_MTLS);
- cassandraContext.configureAndStartCluster(builder -> builder.appendConfig(config -> {
- config.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
- .set("authenticator.parameters", Collections.singletonMap("validator_class_name",
- "org.apache.cassandra.auth.SpiffeCertificateValidator"))
- .set("role_manager", "CassandraRoleManager")
- .set("authorizer", "CassandraAuthorizer")
- .set("client_encryption_options.enabled", "true")
- .set("client_encryption_options.optional", "true")
- .set("client_encryption_options.require_client_auth", "true")
- .set("client_encryption_options.require_endpoint_verification", "false")
- .set("client_encryption_options.keystore", serverKeystorePath.toAbsolutePath().toString())
- .set("client_encryption_options.keystore_password", serverKeystorePassword)
- .set("client_encryption_options.truststore", truststorePath.toAbsolutePath().toString())
- .set("client_encryption_options.truststore_password", truststorePassword);
- }));
+ insertIdentityRole(cassandraTestContext, ADMIN_IDENTITY, "cassandra");
waitForSchemaReady(30, TimeUnit.SECONDS);
- insertIdentityRole(ADMIN_IDENTITY, "cassandra");
- sidecarTestContext.setSslConfiguration(sslConfigWithKeystoreTruststore());
- retrieveClientStats(context, "cassandra", true);
- }
-
- private SslConfiguration sslConfigWithTruststore()
- {
- return SslConfigurationImpl.builder()
- .enabled(true)
- .truststore(new KeyStoreConfigurationImpl(truststorePath.toAbsolutePath().toString(), truststorePassword, "PKCS12"))
- .build();
- }
- private SslConfiguration sslConfigWithKeystoreTruststore()
- {
- return SslConfigurationImpl.builder()
- .enabled(true)
- .keystore(new KeyStoreConfigurationImpl(clientKeystorePath.toAbsolutePath().toString(), clientKeystorePassword, "PKCS12"))
- .truststore(new KeyStoreConfigurationImpl(truststorePath.toAbsolutePath().toString(), truststorePassword, "PKCS12"))
- .build();
+ retrieveClientStats(context, "cassandra", true);
}
private void retrieveClientStats(VertxTestContext context, String expectedUsername, boolean checkSsl) throws Exception
@@ -184,10 +123,10 @@ class CqlSessionProviderIntegrationTest extends IntegrationTestBase
}
}
- private void insertIdentityRole(String identity, String role)
+ private void insertIdentityRole(CassandraTestContext cassandraContext, String identity, String role)
{
- Session session = maybeGetSession();
- session.execute("INSERT INTO system_auth.identity_to_role (identity, role) VALUES (\'" + identity + "\',\'" + role + "\');");
+ String statement = String.format("INSERT INTO system_auth.identity_to_role (identity, role) VALUES ('%s','%s')",
+ identity, role);
+ cassandraContext.cluster().schemaChangeIgnoringStoppedInstances(statement);
}
}
-
diff --git a/server/src/test/integration/org/apache/cassandra/sidecar/testing/CassandraSidecarTestContext.java b/server/src/test/integration/org/apache/cassandra/sidecar/testing/CassandraSidecarTestContext.java
index 6ce876f9..5b2e7a67 100644
--- a/server/src/test/integration/org/apache/cassandra/sidecar/testing/CassandraSidecarTestContext.java
+++ b/server/src/test/integration/org/apache/cassandra/sidecar/testing/CassandraSidecarTestContext.java
@@ -178,12 +178,6 @@ public class CassandraSidecarTestContext implements AutoCloseable
refreshInstancesMetadata();
}
- public void setSslConfiguration(SslConfiguration sslConfiguration)
- {
- this.sslConfiguration = sslConfiguration;
- refreshInstancesMetadata();
- }
-
public InstancesMetadata instancesMetadata()
{
if (instancesMetadata == null)
diff --git a/server/src/test/integration/org/apache/cassandra/sidecar/testing/IntegrationTestBase.java b/server/src/test/integration/org/apache/cassandra/sidecar/testing/IntegrationTestBase.java
index 5934e504..d04723ae 100644
--- a/server/src/test/integration/org/apache/cassandra/sidecar/testing/IntegrationTestBase.java
+++ b/server/src/test/integration/org/apache/cassandra/sidecar/testing/IntegrationTestBase.java
@@ -67,10 +67,14 @@ import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
import org.apache.cassandra.sidecar.common.server.data.Name;
import org.apache.cassandra.sidecar.common.server.data.QualifiedTableName;
import org.apache.cassandra.sidecar.common.server.dns.DnsResolver;
+import org.apache.cassandra.sidecar.config.SslConfiguration;
+import org.apache.cassandra.sidecar.config.yaml.KeyStoreConfigurationImpl;
+import org.apache.cassandra.sidecar.config.yaml.SslConfigurationImpl;
import org.apache.cassandra.sidecar.server.MainModule;
import org.apache.cassandra.sidecar.server.Server;
import org.apache.cassandra.sidecar.server.SidecarServerEvents;
import org.apache.cassandra.testing.AbstractCassandraTestContext;
+import org.apache.cassandra.testing.AuthMode;
import static org.apache.cassandra.sidecar.server.SidecarServerEvents.ON_CASSANDRA_CQL_READY;
import static org.apache.cassandra.sidecar.testing.IntegrationTestModule.ADMIN_IDENTITY;
@@ -97,7 +101,6 @@ public abstract class IntegrationTestBase
protected File tempDir;
protected CertificateBundle ca;
protected Path serverKeystorePath;
- protected String serverKeystorePassword = "password";
protected Path clientKeystorePath;
protected String clientKeystorePassword = "password";
protected Path truststorePath;
@@ -112,9 +115,9 @@ public abstract class IntegrationTestBase
{
testExceptions.clear();
- ca = ca();
- truststorePath = truststorePath();
- serverKeystorePath = serverKeystorePath();
+ ca = cassandraTestContext.ca;
+ truststorePath = cassandraTestContext.truststorePath;
+ serverKeystorePath = cassandraTestContext.serverKeystorePath;
clientKeystorePath = clientKeystorePath(ADMIN_IDENTITY);
IntegrationTestModule integrationTestModule = new IntegrationTestModule();
@@ -125,13 +128,22 @@ public abstract class IntegrationTestBase
int clusterSize = cassandraTestContext.clusterSize();
injector = Guice.createInjector(Modules.override(new MainModule()).with(integrationTestModule));
vertx = injector.getInstance(Vertx.class);
- sidecarTestContext = CassandraSidecarTestContext.from(vertx, cassandraTestContext, DnsResolver.DEFAULT,
- getNumInstancesToManage(clusterSize), null);
+ SslConfiguration sslConfig = cassandraTestContext.annotation.authMode().equals(AuthMode.MUTUAL_TLS)
+ ? sslConfigWithClientKeystoreTruststore() : null;
+
+ // When only SSL is enabled and mTLS is not enabled, we should not set keystore in SslConfig. Set a keystore
+ // when mTLS is enabled
+ if (cassandraTestContext.annotation.enableSsl() &&
+ !cassandraTestContext.annotation.authMode().equals(AuthMode.MUTUAL_TLS))
+ {
+ sslConfig = sslConfigWithTruststore();
+ }
+ sidecarTestContext = CassandraSidecarTestContext.from(vertx, cassandraTestContext, DnsResolver.DEFAULT,
+ getNumInstancesToManage(clusterSize), sslConfig);
integrationTestModule.setCassandraTestContext(sidecarTestContext);
server = injector.getInstance(Server.class);
- client = createClient(clientKeystorePath, truststorePath);
VertxTestContext context = new VertxTestContext();
if (sidecarTestContext.isClusterBuilt())
@@ -431,29 +443,6 @@ public abstract class IntegrationTestBase
.forEach(instanceMetadata -> instanceMetadata.delegate().healthCheck());
}
- protected CertificateBundle ca() throws Exception
- {
- return CertificateBuilder.builder()
- .subject("CN=Apache cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
- .isCertificateAuthority(true)
- .buildSelfSigned();
- }
- protected Path truststorePath() throws Exception
- {
- return ca.toTempKeyStorePath(tempDir.toPath(), truststorePassword.toCharArray(), truststorePassword.toCharArray());
- }
-
- protected Path serverKeystorePath() throws Exception
- {
- CertificateBundle keystore
- = CertificateBuilder.builder()
- .subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
- .addSanDnsName("localhost")
- .addSanIpAddress("127.0.0.1")
- .buildIssuedBy(ca);
- return keystore.toTempKeyStorePath(tempDir.toPath(), serverKeystorePassword.toCharArray(), serverKeystorePassword.toCharArray());
- }
-
protected Path clientKeystorePath(String identity) throws Exception
{
return clientKeystorePath(identity, false);
@@ -475,6 +464,24 @@ public abstract class IntegrationTestBase
return clientKeystore.toTempKeyStorePath(tempDir.toPath(), clientKeystorePassword.toCharArray(), clientKeystorePassword.toCharArray());
}
+ private SslConfiguration sslConfigWithClientKeystoreTruststore()
+ {
+ return SslConfigurationImpl
+ .builder()
+ .enabled(true)
+ .keystore(new KeyStoreConfigurationImpl(clientKeystorePath.toAbsolutePath().toString(), clientKeystorePassword, "PKCS12"))
+ .truststore(new KeyStoreConfigurationImpl(truststorePath.toAbsolutePath().toString(), truststorePassword, "PKCS12"))
+ .build();
+ }
+
+ private SslConfiguration sslConfigWithTruststore()
+ {
+ return SslConfigurationImpl.builder()
+ .enabled(true)
+ .truststore(new KeyStoreConfigurationImpl(truststorePath.toAbsolutePath().toString(), truststorePassword, "PKCS12"))
+ .build();
+ }
+
protected WebClient createClient(Path clientKeystorePath, Path truststorePath)
{
WebClientOptions options = new WebClientOptions();
diff --git a/server/src/test/integration/org/apache/cassandra/sidecar/testing/IntegrationTestModule.java b/server/src/test/integration/org/apache/cassandra/sidecar/testing/IntegrationTestModule.java
index 81667714..c07e8700 100644
--- a/server/src/test/integration/org/apache/cassandra/sidecar/testing/IntegrationTestModule.java
+++ b/server/src/test/integration/org/apache/cassandra/sidecar/testing/IntegrationTestModule.java
@@ -170,10 +170,18 @@ public class IntegrationTestModule extends AbstractModule
ParameterizedClassConfiguration mTLSConfig
= new ParameterizedClassConfigurationImpl("org.apache.cassandra.sidecar.acl.authentication.MutualTlsAuthenticationHandlerFactory",
params);
+ ParameterizedClassConfiguration rbacConfig
+ = new ParameterizedClassConfigurationImpl("org.apache.cassandra.sidecar.acl.authorization.RoleBasedAuthorizationProvider",
+ Collections.emptyMap());
return new AccessControlConfigurationImpl(true,
Collections.singletonList(mTLSConfig),
+ rbacConfig,
Collections.singleton(ADMIN_IDENTITY),
- new CacheConfigurationImpl());
+ new CacheConfigurationImpl(MillisecondBoundConfiguration.parse("1s"),
+ 100,
+ true,
+ 5,
+ MillisecondBoundConfiguration.parse("1s")));
}
class WrapperInstancesMetadata implements InstancesMetadata
diff --git a/server/src/test/integration/org/apache/cassandra/testing/AbstractCassandraTestContext.java b/server/src/test/integration/org/apache/cassandra/testing/AbstractCassandraTestContext.java
index 259ea1da..2098186f 100644
--- a/server/src/test/integration/org/apache/cassandra/testing/AbstractCassandraTestContext.java
+++ b/server/src/test/integration/org/apache/cassandra/testing/AbstractCassandraTestContext.java
@@ -18,6 +18,7 @@
package org.apache.cassandra.testing;
+import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
@@ -25,6 +26,7 @@ import java.util.Objects;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
+import io.vertx.ext.auth.mtls.utils.CertificateBundle;
import org.apache.cassandra.distributed.UpgradeableCluster;
import org.apache.cassandra.distributed.shared.ShutdownException;
@@ -39,22 +41,36 @@ public abstract class AbstractCassandraTestContext implements AutoCloseable
private final Map<String, String> initialProperties;
protected UpgradeableCluster cluster;
+ // certificates created when cluster is started with auth
+ public final CertificateBundle ca;
+ public final Path serverKeystorePath;
+ public final Path truststorePath;
+
public CassandraIntegrationTest annotation;
public AbstractCassandraTestContext(SimpleCassandraVersion version,
UpgradeableCluster cluster,
+ CertificateBundle ca,
+ Path serverKeystorePath,
+ Path truststorePath,
CassandraIntegrationTest annotation)
{
this.version = version;
this.cluster = cluster;
+ this.ca = ca;
+ this.serverKeystorePath = serverKeystorePath;
+ this.truststorePath = truststorePath;
this.annotation = annotation;
this.initialProperties = systemStringProperties();
}
public AbstractCassandraTestContext(SimpleCassandraVersion version,
+ CertificateBundle ca,
+ Path serverKeystorePath,
+ Path truststorePath,
CassandraIntegrationTest annotation)
{
- this(version, null, annotation);
+ this(version, null, ca, serverKeystorePath, truststorePath, annotation);
}
public UpgradeableCluster cluster()
diff --git a/server/src/test/integration/org/apache/cassandra/testing/CassandraTestContext.java b/server/src/test/integration/org/apache/cassandra/testing/AuthMode.java
similarity index 53%
copy from server/src/test/integration/org/apache/cassandra/testing/CassandraTestContext.java
copy to server/src/test/integration/org/apache/cassandra/testing/AuthMode.java
index 09afe242..b12aafc4 100644
--- a/server/src/test/integration/org/apache/cassandra/testing/CassandraTestContext.java
+++ b/server/src/test/integration/org/apache/cassandra/testing/AuthMode.java
@@ -18,29 +18,23 @@
package org.apache.cassandra.testing;
-import org.apache.cassandra.distributed.UpgradeableCluster;
-
/**
- * Passed to integration tests.
- * See {@link CassandraIntegrationTest} for the required annotation
- * See {@link CassandraTestTemplate} for the Test Template
+ * Auth settings for Cassandra cluster
*/
-public class CassandraTestContext extends AbstractCassandraTestContext
+public enum AuthMode
{
+ /**
+ * Cassandra is configured with no authentication
+ */
+ NONE,
- public CassandraTestContext(SimpleCassandraVersion version,
- UpgradeableCluster cluster,
- CassandraIntegrationTest annotation)
- {
- super(version, cluster, annotation);
- }
+ /**
+ * Cassandra is configured with the PasswordAuthenticator
+ */
+ PASSWORD,
- @Override
- public String toString()
- {
- return "CassandraTestContext{"
- + "version=" + version
- + ", cluster=" + cluster
- + '}';
- }
+ /**
+ * Cassandra is configured with the MutualTLSWithPasswordFallbackAuthenticator
+ */
+ MUTUAL_TLS
}
diff --git a/server/src/test/integration/org/apache/cassandra/testing/CassandraIntegrationTest.java b/server/src/test/integration/org/apache/cassandra/testing/CassandraIntegrationTest.java
index 29fa433d..209eae74 100644
--- a/server/src/test/integration/org/apache/cassandra/testing/CassandraIntegrationTest.java
+++ b/server/src/test/integration/org/apache/cassandra/testing/CassandraIntegrationTest.java
@@ -124,4 +124,19 @@ public @interface CassandraIntegrationTest
* false if it should be run on the first version.
*/
boolean versionDependent() default true;
+
+ /**
+ * AuthMode set for Cassandra cluster. Cassandra is started with required authenticator depending on the mode.
+ * @return AuthMode selected for the cluster. Possible options are {@code AuthMode.NONE}, {@code AuthMode.PASSWORD}
+ * {@code AuthMode.MUTUAL_TLS}
+ */
+ AuthMode authMode() default AuthMode.NONE;
+
+ /**
+ * Enables SSL for Cassandra cluster when set to true
+ *
+ * Note: enabledSsl is not required when AuthMode is set to {@code AuthMode.MUTUAL_TLS}
+ * @return whether SSL is enabled for Cassandra cluster
+ */
+ boolean enableSsl() default false;
}
diff --git a/server/src/test/integration/org/apache/cassandra/testing/CassandraTestContext.java b/server/src/test/integration/org/apache/cassandra/testing/CassandraTestContext.java
index 09afe242..b8832e23 100644
--- a/server/src/test/integration/org/apache/cassandra/testing/CassandraTestContext.java
+++ b/server/src/test/integration/org/apache/cassandra/testing/CassandraTestContext.java
@@ -18,6 +18,9 @@
package org.apache.cassandra.testing;
+import java.nio.file.Path;
+
+import io.vertx.ext.auth.mtls.utils.CertificateBundle;
import org.apache.cassandra.distributed.UpgradeableCluster;
/**
@@ -30,9 +33,12 @@ public class CassandraTestContext extends AbstractCassandraTestContext
public CassandraTestContext(SimpleCassandraVersion version,
UpgradeableCluster cluster,
+ CertificateBundle ca,
+ Path serverKeystorePath,
+ Path truststorePath,
CassandraIntegrationTest annotation)
{
- super(version, cluster, annotation);
+ super(version, cluster, ca, serverKeystorePath, truststorePath, annotation);
}
@Override
diff --git a/server/src/test/integration/org/apache/cassandra/testing/CassandraTestTemplate.java b/server/src/test/integration/org/apache/cassandra/testing/CassandraTestTemplate.java
index 6afc1384..29ed5813 100644
--- a/server/src/test/integration/org/apache/cassandra/testing/CassandraTestTemplate.java
+++ b/server/src/test/integration/org/apache/cassandra/testing/CassandraTestTemplate.java
@@ -20,8 +20,11 @@ package org.apache.cassandra.testing;
import java.lang.reflect.AnnotatedElement;
import java.net.BindException;
+import java.nio.file.Files;
+import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
+import java.util.Collections;
import java.util.List;
import java.util.Optional;
import java.util.function.Predicate;
@@ -40,6 +43,8 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.vdurmont.semver4j.Semver;
+import io.vertx.ext.auth.mtls.utils.CertificateBuilder;
+import io.vertx.ext.auth.mtls.utils.CertificateBundle;
import org.apache.cassandra.distributed.UpgradeableCluster;
import org.apache.cassandra.distributed.api.Feature;
import org.apache.cassandra.distributed.api.TokenSupplier;
@@ -47,6 +52,7 @@ import org.apache.cassandra.distributed.impl.AbstractCluster;
import org.apache.cassandra.distributed.shared.Versions;
import org.apache.cassandra.sidecar.common.utils.Preconditions;
import org.apache.cassandra.utils.Throwables;
+import software.amazon.awssdk.utils.ImmutableMap;
/**
@@ -62,6 +68,9 @@ import org.apache.cassandra.utils.Throwables;
public class CassandraTestTemplate implements TestTemplateInvocationContextProvider
{
private static final Logger LOGGER = LoggerFactory.getLogger(CassandraTestTemplate.class);
+ private static final int MIN_VERSION_WITH_MTLS = 5;
+ private final String truststorePassword = "password";
+ private final String serverKeystorePassword = "password";
private AbstractCassandraTestContext cassandraTestContext;
@@ -171,6 +180,56 @@ public class CassandraTestTemplate implements TestTemplateInvocationContextProvi
.withSharedClasses(extra.or(AbstractCluster.SHARED_PREDICATE))
.withDataDirCount(annotation.numDataDirsPerInstance())
.withConfig(config -> annotationToFeatureList(annotation).forEach(config::with));
+
+ Path tempDirPath = Files.createTempDirectory("certs");
+ CertificateBundle ca = ca();
+ Path serverKeystorePath = serverKeystorePath(ca, tempDirPath);
+ Path truststorePath = truststorePath(ca, tempDirPath);
+
+ switch(annotation.authMode())
+ {
+ case PASSWORD:
+ {
+ clusterBuilder.appendConfig(config -> config.set("authenticator", "org.apache.cassandra.auth.PasswordAuthenticator"));
+ break;
+ }
+ case MUTUAL_TLS:
+ {
+ // mTLS authentication was added in Cassandra starting 5.0 version
+ if (clusterBuilder.getVersion().version.getMajor() >= MIN_VERSION_WITH_MTLS)
+ {
+ clusterBuilder.appendConfig(config -> {
+ config.set("authenticator.class_name", "org.apache.cassandra.auth.MutualTlsWithPasswordFallbackAuthenticator")
+ .set("authenticator.parameters", Collections.singletonMap("validator_class_name",
+ "org.apache.cassandra.auth.SpiffeCertificateValidator"))
+ .set("role_manager", "CassandraRoleManager")
+ .set("authorizer", "CassandraAuthorizer")
+ .set("client_encryption_options.enabled", "true")
+ .set("client_encryption_options.optional", "true")
+ .set("client_encryption_options.require_client_auth", "true")
+ .set("client_encryption_options.require_endpoint_verification", "false")
+ .set("client_encryption_options.keystore", serverKeystorePath.toAbsolutePath().toString())
+ .set("client_encryption_options.keystore_password", serverKeystorePassword)
+ .set("client_encryption_options.truststore", truststorePath.toAbsolutePath().toString())
+ .set("client_encryption_options.truststore_password", truststorePassword);
+ });
+ }
+ break;
+ }
+ default:
+ }
+
+ if (annotation.enableSsl() && !annotation.authMode().equals(AuthMode.MUTUAL_TLS))
+ {
+ clusterBuilder.appendConfig(config -> {
+ // dot-separated options are not supported in 4.0
+ config.set("client_encryption_options", ImmutableMap.of("enabled", "true",
+ "require_client_auth", "false",
+ "keystore", serverKeystorePath.toAbsolutePath().toString(),
+ "keystore_password", serverKeystorePassword));
+ });
+ }
+
TokenSupplier tokenSupplier = TokenSupplier.evenlyDistributedTokens(finalNodeCount,
clusterBuilder.getTokenCount());
clusterBuilder.withTokenSupplier(tokenSupplier);
@@ -185,12 +244,13 @@ public class CassandraTestTemplate implements TestTemplateInvocationContextProvi
{
cluster = clusterBuilder.createWithoutStarting();
}
- cassandraTestContext = new CassandraTestContext(versionParsed, cluster, annotation);
+ cassandraTestContext = new CassandraTestContext(versionParsed, cluster, ca, serverKeystorePath,
+ truststorePath, annotation);
}
else
{
- cassandraTestContext = new ConfigurableCassandraTestContext(versionParsed,
- clusterBuilder,
+ cassandraTestContext = new ConfigurableCassandraTestContext(versionParsed, clusterBuilder, ca,
+ serverKeystorePath, truststorePath,
annotation);
}
LOGGER.info("Testing {} against in-jvm dtest cluster", version);
@@ -309,6 +369,30 @@ public class CassandraTestTemplate implements TestTemplateInvocationContextProvi
}
}
+ private CertificateBundle ca() throws Exception
+ {
+ return CertificateBuilder.builder()
+ .subject("CN=Apache cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown")
+ .isCertificateAuthority(true)
+ .buildSelfSigned();
+ }
+
+ private Path truststorePath(CertificateBundle ca, Path path) throws Exception
+ {
+ return ca.toTempKeyStorePath(path, truststorePassword.toCharArray(), truststorePassword.toCharArray());
+ }
+
+ private Path serverKeystorePath(CertificateBundle ca, Path path) throws Exception
+ {
+ CertificateBundle keystore
+ = CertificateBuilder.builder()
+ .subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown")
+ .addSanDnsName("localhost")
+ .addSanIpAddress("127.0.0.1")
+ .buildIssuedBy(ca);
+ return keystore.toTempKeyStorePath(path, serverKeystorePassword.toCharArray(), serverKeystorePassword.toCharArray());
+ }
+
public static UpgradeableCluster retriableStartCluster(UpgradeableCluster.Builder builder, int maxAttempts)
{
Throwable lastCause = null;
diff --git a/server/src/test/integration/org/apache/cassandra/testing/ConfigurableCassandraTestContext.java b/server/src/test/integration/org/apache/cassandra/testing/ConfigurableCassandraTestContext.java
index a82f06d7..a7cd84ba 100644
--- a/server/src/test/integration/org/apache/cassandra/testing/ConfigurableCassandraTestContext.java
+++ b/server/src/test/integration/org/apache/cassandra/testing/ConfigurableCassandraTestContext.java
@@ -18,8 +18,10 @@
package org.apache.cassandra.testing;
+import java.nio.file.Path;
import java.util.function.Consumer;
+import io.vertx.ext.auth.mtls.utils.CertificateBundle;
import org.apache.cassandra.distributed.UpgradeableCluster;
/**
@@ -32,9 +34,12 @@ public class ConfigurableCassandraTestContext extends AbstractCassandraTestConte
public ConfigurableCassandraTestContext(SimpleCassandraVersion version,
UpgradeableCluster.Builder builder,
+ CertificateBundle ca,
+ Path serverKeystorePath,
+ Path truststorePath,
CassandraIntegrationTest annotation)
{
- super(version, annotation);
+ super(version, ca, serverKeystorePath, truststorePath, annotation);
this.builder = builder;
}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/acl/RoleAuthorizationsCacheTest.java b/server/src/test/java/org/apache/cassandra/sidecar/acl/RoleAuthorizationsCacheTest.java
new file mode 100644
index 00000000..57f6d20e
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/acl/RoleAuthorizationsCacheTest.java
@@ -0,0 +1,259 @@
+/*
+ * 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;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import io.vertx.core.Vertx;
+import io.vertx.core.json.JsonObject;
+import io.vertx.ext.auth.authorization.Authorization;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.CassandraPermissions;
+import org.apache.cassandra.sidecar.acl.authorization.RoleAuthorizationsCache;
+import org.apache.cassandra.sidecar.common.server.utils.MillisecondBoundConfiguration;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.apache.cassandra.sidecar.config.AccessControlConfiguration;
+import org.apache.cassandra.sidecar.config.CacheConfiguration;
+import org.apache.cassandra.sidecar.config.SchemaKeyspaceConfiguration;
+import org.apache.cassandra.sidecar.config.ServiceConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.SidecarPermissionsDatabaseAccessor;
+import org.apache.cassandra.sidecar.db.SystemAuthDatabaseAccessor;
+import org.apache.cassandra.sidecar.db.schema.SidecarSchema;
+
+import static org.apache.cassandra.sidecar.ExecutorPoolsHelper.createdSharedTestPool;
+import static org.apache.cassandra.sidecar.server.SidecarServerEvents.ON_SIDECAR_SCHEMA_INITIALIZED;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Test for {@link RoleAuthorizationsCache}
+ */
+class RoleAuthorizationsCacheTest
+{
+ Vertx vertx;
+ SidecarSchema mockSidecarSchema;
+ ExecutorPools executorPools;
+
+ @BeforeEach
+ void setup()
+ {
+ vertx = Vertx.vertx();
+ mockSidecarSchema = mock(SidecarSchema.class);
+ when(mockSidecarSchema.isInitialized()).thenReturn(true);
+ executorPools = createdSharedTestPool(vertx);
+ }
+
+ @Test
+ void testCacheSizeAlwaysOne() throws InterruptedException
+ {
+ Map<String, Set<Authorization>> cassandraAuthorizations = new HashMap<>();
+ cassandraAuthorizations.put("test_role1", new HashSet<>(Collections.singletonList(CassandraPermissions.SELECT.toAuthorization())));
+ SystemAuthDatabaseAccessor mockDbAccessor = mock(SystemAuthDatabaseAccessor.class);
+ when(mockDbAccessor.findAllRolesAndPermissions()).thenReturn(cassandraAuthorizations);
+ Map<String, Set<Authorization>> sidecarAuthorizations = new HashMap<>();
+ sidecarAuthorizations.put("test_role1", new HashSet<>(Collections.singletonList(BasicPermissions.CREATE_SNAPSHOT.toAuthorization())));
+ SidecarPermissionsDatabaseAccessor mockSidecarPermissionsAccessor = mock(SidecarPermissionsDatabaseAccessor.class);
+ when(mockSidecarPermissionsAccessor.rolesToAuthorizations()).thenReturn(sidecarAuthorizations);
+ SidecarConfiguration mockConfig = mockConfig();
+ RoleAuthorizationsCache cache = new RoleAuthorizationsCache(vertx,
+ executorPools,
+ mockConfig,
+ mockSidecarSchema,
+ mockDbAccessor,
+ mockSidecarPermissionsAccessor);
+ assertThat(cache.getAll().size()).isZero();
+ assertThat(cache.getAuthorizations("test_role1").size()).isEqualTo(2);
+ assertThat(cache.getAll().size()).isOne();
+
+ sidecarAuthorizations.put("test_role2", new HashSet<>(Collections.singletonList(BasicPermissions.STREAM_SNAPSHOT.toAuthorization())));
+ when(mockSidecarPermissionsAccessor.rolesToAuthorizations()).thenReturn(sidecarAuthorizations);
+
+ // wait for cache entries to be refreshed
+ Thread.sleep(3000);
+
+ // New entries fetched during refreshes
+ assertThat(cache.getAuthorizations("test_role2").size()).isOne();
+ assertThat(cache.getAll().size()).isOne();
+ }
+
+ @Test
+ void testNotFoundUser()
+ {
+ SystemAuthDatabaseAccessor mockDbAccessor = mock(SystemAuthDatabaseAccessor.class);
+ Map<String, Set<Authorization>> cassandraAuthorizations = new HashMap<>();
+ cassandraAuthorizations.put("test_role1", new HashSet<>(Collections.singletonList(CassandraPermissions.SELECT.toAuthorization())));
+ when(mockDbAccessor.findAllRolesAndPermissions()).thenReturn(cassandraAuthorizations);
+ Map<String, Set<Authorization>> sidecarAuthorizations = new HashMap<>();
+ sidecarAuthorizations.put("test_role1", new HashSet<>(Collections.singletonList(BasicPermissions.CREATE_SNAPSHOT.toAuthorization())));
+ SidecarPermissionsDatabaseAccessor mockSidecarPermissionsAccessor = mock(SidecarPermissionsDatabaseAccessor.class);
+ when(mockSidecarPermissionsAccessor.rolesToAuthorizations()).thenReturn(sidecarAuthorizations);
+ SidecarConfiguration mockConfig = mockConfig();
+ RoleAuthorizationsCache cache = new RoleAuthorizationsCache(vertx,
+ executorPools,
+ mockConfig,
+ mockSidecarSchema,
+ mockDbAccessor,
+ mockSidecarPermissionsAccessor);
+ assertThat(cache.getAll().size()).isZero();
+
+ cache.warmUp(5);
+
+ // New entries fetched during refreshes
+ assertThat(cache.getAll().size()).isOne();
+ assertThat(cache.getAuthorizations("test_role2")).isNull();
+ }
+
+ @Test
+ void testBulkload() throws InterruptedException
+ {
+ Map<String, Set<Authorization>> sidecarAuthorizations = new HashMap<>();
+ sidecarAuthorizations.put("test_role1", new HashSet<>(Collections.singletonList(BasicPermissions.CREATE_SNAPSHOT.toAuthorization())));
+ sidecarAuthorizations.put("test_role2", new HashSet<>(Collections.singletonList(BasicPermissions.STREAM_SNAPSHOT.toAuthorization())));
+ SystemAuthDatabaseAccessor mockDbAccessor = mock(SystemAuthDatabaseAccessor.class);
+ when(mockDbAccessor.findAllRolesAndPermissions()).thenReturn(sidecarAuthorizations);
+ SidecarPermissionsDatabaseAccessor mockSidecarPermissionsAccessor = mock(SidecarPermissionsDatabaseAccessor.class);
+ SidecarConfiguration mockConfig = mockConfig();
+ RoleAuthorizationsCache cache = new RoleAuthorizationsCache(vertx,
+ executorPools,
+ mockConfig,
+ mockSidecarSchema,
+ mockDbAccessor,
+ mockSidecarPermissionsAccessor);
+ assertThat(cache.getAll().size()).isZero();
+
+ // warming cache
+ vertx.eventBus().publish(ON_SIDECAR_SCHEMA_INITIALIZED.address(), new JsonObject());
+
+ // wait for cache warming. system_auth.role_permissions table bulk loaded against a single key
+ Thread.sleep(3000);
+ assertThat(cache.getAll().size()).isOne();
+ assertThat(cache.get("unique_cache_entry_key").get("test_role1").size()).isOne();
+ assertThat(cache.get("unique_cache_entry_key").get("test_role2").size()).isOne();
+ }
+
+ @Test
+ void testCacheDisabled()
+ {
+ Map<String, Set<Authorization>> sidecarAuthorizations = new HashMap<>();
+ sidecarAuthorizations.put("test_role1", new HashSet<>(Collections.singletonList(BasicPermissions.CREATE_SNAPSHOT.toAuthorization())));
+ sidecarAuthorizations.put("test_role2", new HashSet<>(Collections.singletonList(BasicPermissions.STREAM_SNAPSHOT.toAuthorization())));
+ SystemAuthDatabaseAccessor mockDbAccessor = mock(SystemAuthDatabaseAccessor.class);
+ when(mockDbAccessor.findAllRolesAndPermissions()).thenReturn(sidecarAuthorizations);
+ SidecarPermissionsDatabaseAccessor mockSidecarPermissionsAccessor = mock(SidecarPermissionsDatabaseAccessor.class);
+ SidecarConfiguration mockConfig = mockConfig();
+ CacheConfiguration mockCacheConfig = mock(CacheConfiguration.class);
+ when(mockCacheConfig.enabled()).thenReturn(true);
+ when(mockCacheConfig.expireAfterAccess()).thenReturn(MillisecondBoundConfiguration.parse("1s"));
+ when(mockCacheConfig.maximumSize()).thenReturn(100L);
+ when(mockConfig.accessControlConfiguration().permissionCacheConfiguration()).thenReturn(mockCacheConfig);
+ RoleAuthorizationsCache cache = new RoleAuthorizationsCache(vertx,
+ executorPools,
+ mockConfig,
+ mockSidecarSchema,
+ mockDbAccessor,
+ mockSidecarPermissionsAccessor);
+ assertThat(cache.getAuthorizations("test_role1").size()).isOne();
+ assertThat(cache.getAuthorizations("test_role2").size()).isOne();
+ }
+
+ @Test
+ void testEmptyEntriesFromSystemAuthDatabaseAccessor() throws InterruptedException
+ {
+ SystemAuthDatabaseAccessor mockDbAccessor = mock(SystemAuthDatabaseAccessor.class);
+ when(mockDbAccessor.findAllRolesAndPermissions()).thenReturn(Collections.emptyMap());
+ SidecarPermissionsDatabaseAccessor mockSidecarPermissionsAccessor = mock(SidecarPermissionsDatabaseAccessor.class);
+ SidecarConfiguration mockConfig = mockConfig();
+ RoleAuthorizationsCache cache = new RoleAuthorizationsCache(vertx,
+ executorPools,
+ mockConfig,
+ mockSidecarSchema,
+ mockDbAccessor,
+ mockSidecarPermissionsAccessor);
+ assertThat(cache.getAll().size()).isZero();
+
+ // warming cache
+ vertx.eventBus().publish(ON_SIDECAR_SCHEMA_INITIALIZED.address(), new JsonObject());
+
+ // wait for cache warming. system_auth.role_permissions table bulk loaded against a single key
+ Thread.sleep(3000);
+ assertThat(cache.getAll().size()).isOne();
+ assertThat(cache.get("unique_cache_entry_key").size()).isZero();
+ }
+
+ @Test
+ void testSidecarPermissionsNotAddedWhenSchemaDisabled()
+ {
+ Map<String, Set<Authorization>> cassandraAuthorizations = new HashMap<>();
+ cassandraAuthorizations.put("test_role1", new HashSet<>(Collections.singletonList(CassandraPermissions.SELECT.toAuthorization())));
+ cassandraAuthorizations.put("test_role2", new HashSet<>(Collections.singletonList(CassandraPermissions.CREATE.toAuthorization())));
+ SystemAuthDatabaseAccessor mockDbAccessor = mock(SystemAuthDatabaseAccessor.class);
+ when(mockDbAccessor.findAllRolesAndPermissions()).thenReturn(cassandraAuthorizations);
+ Map<String, Set<Authorization>> sidecarAuthorizations = new HashMap<>();
+ sidecarAuthorizations.put("test_role3", new HashSet<>(Collections.singletonList(BasicPermissions.CREATE_SNAPSHOT.toAuthorization())));
+ SidecarPermissionsDatabaseAccessor mockSidecarPermissionsAccessor = mock(SidecarPermissionsDatabaseAccessor.class);
+ when(mockSidecarPermissionsAccessor.rolesToAuthorizations()).thenReturn(sidecarAuthorizations);
+ SidecarConfiguration mockConfig = mockConfig();
+ SidecarSchema mockSidecarSchema = mock(SidecarSchema.class);
+ when(mockSidecarSchema.isInitialized()).thenReturn(false);
+ RoleAuthorizationsCache cache = new RoleAuthorizationsCache(vertx,
+ executorPools,
+ mockConfig,
+ mockSidecarSchema,
+ mockDbAccessor,
+ mockSidecarPermissionsAccessor);
+ assertThat(cache.getAll().size()).isZero();
+
+ // force warmup of cache
+ cache.warmUp(5);
+
+ assertThat(cache.getAll().size()).isOne();
+ assertThat(cache.get("unique_cache_entry_key").get("test_role1").size()).isOne();
+ assertThat(cache.get("unique_cache_entry_key").get("test_role2").size()).isOne();
+ assertThat(cache.get("unique_cache_entry_key").get("test_role3")).isNull();
+ }
+
+ private SidecarConfiguration mockConfig()
+ {
+ SidecarConfiguration mockConfig = mock(SidecarConfiguration.class);
+ ServiceConfiguration mockServiceConfig = mock(ServiceConfiguration.class);
+ SchemaKeyspaceConfiguration mockSchemaConfig = mock(SchemaKeyspaceConfiguration.class);
+ when(mockSchemaConfig.isEnabled()).thenReturn(true);
+ when(mockServiceConfig.schemaKeyspaceConfiguration()).thenReturn(mockSchemaConfig);
+ when(mockConfig.serviceConfiguration()).thenReturn(mockServiceConfig);
+ AccessControlConfiguration mockAccessControlConfig = mock(AccessControlConfiguration.class);
+ when(mockConfig.accessControlConfiguration()).thenReturn(mockAccessControlConfig);
+ CacheConfiguration mockCacheConfig = mock(CacheConfiguration.class);
+ when(mockCacheConfig.enabled()).thenReturn(true);
+ when(mockCacheConfig.expireAfterAccess()).thenReturn(MillisecondBoundConfiguration.parse("1s"));
+ when(mockCacheConfig.maximumSize()).thenReturn(10L);
+ when(mockCacheConfig.warmupRetries()).thenReturn(5);
+ when(mockCacheConfig.expireAfterAccess()).thenReturn(MillisecondBoundConfiguration.parse("1s"));
+ when(mockAccessControlConfig.permissionCacheConfiguration()).thenReturn(mockCacheConfig);
+ return mockConfig;
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/acl/authentication/MutualTLSAuthenticationHandlerTest.java b/server/src/test/java/org/apache/cassandra/sidecar/acl/authentication/MutualTLSAuthenticationHandlerTest.java
index fd6bc2ea..10e215af 100644
--- a/server/src/test/java/org/apache/cassandra/sidecar/acl/authentication/MutualTLSAuthenticationHandlerTest.java
+++ b/server/src/test/java/org/apache/cassandra/sidecar/acl/authentication/MutualTLSAuthenticationHandlerTest.java
@@ -308,8 +308,13 @@ class MutualTLSAuthenticationHandlerTest
.build();
+ String className = "org.apache.cassandra.sidecar.acl.authorization.AllowAllAuthorizationProvider";
AccessControlConfiguration accessControlConfiguration
- = new AccessControlConfigurationImpl(true, authenticatorsConfiguration(), Collections.singleton(ADMIN_IDENTITY), new CacheConfigurationImpl());
+ = new AccessControlConfigurationImpl(true,
+ authenticatorsConfiguration(),
+ new ParameterizedClassConfigurationImpl(className, Collections.emptyMap()),
+ Collections.singleton(ADMIN_IDENTITY),
+ new CacheConfigurationImpl());
return super.abstractConfig(sslConfiguration, accessControlConfiguration);
}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/AdminIdentityResolverTest.java b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/AdminIdentityResolverTest.java
new file mode 100644
index 00000000..211cc510
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/AdminIdentityResolverTest.java
@@ -0,0 +1,86 @@
+/*
+ * 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.Collections;
+
+import org.junit.jupiter.api.Test;
+
+import org.apache.cassandra.sidecar.acl.IdentityToRoleCache;
+import org.apache.cassandra.sidecar.config.AccessControlConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Test for {@link AdminIdentityResolver}
+ */
+class AdminIdentityResolverTest
+{
+ @Test
+ void testAdminIdentityFromConfig()
+ {
+ IdentityToRoleCache mockIdentityToRoleCache = mock(IdentityToRoleCache.class);
+ SuperUserCache mockSuperUserCache = mock(SuperUserCache.class);
+ SidecarConfiguration mockConfig = mock(SidecarConfiguration.class);
+ AccessControlConfiguration mockAclConfig = mock(AccessControlConfiguration.class);
+ when(mockAclConfig.adminIdentities()).thenReturn(Collections.singleton("spiffe://cassandra/sidecar/admin"));
+ when(mockConfig.accessControlConfiguration()).thenReturn(mockAclConfig);
+ AdminIdentityResolver adminIdentityResolver = new AdminIdentityResolver(mockIdentityToRoleCache,
+ mockSuperUserCache,
+ mockConfig);
+ assertThat(adminIdentityResolver.isAdmin("spiffe://cassandra/sidecar/admin")).isTrue();
+ assertThat(adminIdentityResolver.isAdmin("spiffe://cassandra/sidecar/test_user")).isFalse();
+ }
+
+ @Test
+ void testSuperUser()
+ {
+ IdentityToRoleCache mockIdentityToRoleCache = mock(IdentityToRoleCache.class);
+ when(mockIdentityToRoleCache.get("spiffe://cassandra/sidecar/test_user")).thenReturn("test_role");
+ SuperUserCache mockSuperUserCache = mock(SuperUserCache.class);
+ when(mockSuperUserCache.isSuperUser("test_role")).thenReturn(true);
+ SidecarConfiguration mockConfig = mock(SidecarConfiguration.class);
+ AccessControlConfiguration mockAclConfig = mock(AccessControlConfiguration.class);
+ when(mockAclConfig.adminIdentities()).thenReturn(Collections.emptySet());
+ when(mockConfig.accessControlConfiguration()).thenReturn(mockAclConfig);
+ AdminIdentityResolver adminIdentityResolver = new AdminIdentityResolver(mockIdentityToRoleCache,
+ mockSuperUserCache,
+ mockConfig);
+ assertThat(adminIdentityResolver.isAdmin("spiffe://cassandra/sidecar/test_user")).isTrue();
+ assertThat(adminIdentityResolver.isAdmin("spiffe://cassandra/sidecar/admin")).isFalse();
+ }
+
+ @Test
+ void testNonAdminIdentity()
+ {
+ IdentityToRoleCache mockIdentityToRoleCache = mock(IdentityToRoleCache.class);
+ SuperUserCache mockSuperUserCache = mock(SuperUserCache.class);
+ SidecarConfiguration mockConfig = mock(SidecarConfiguration.class);
+ AccessControlConfiguration mockAclConfig = mock(AccessControlConfiguration.class);
+ when(mockAclConfig.adminIdentities()).thenReturn(Collections.emptySet());
+ when(mockConfig.accessControlConfiguration()).thenReturn(mockAclConfig);
+ AdminIdentityResolver adminIdentityResolver = new AdminIdentityResolver(mockIdentityToRoleCache,
+ mockSuperUserCache,
+ mockConfig);
+ assertThat(adminIdentityResolver.isAdmin("spiffe://cassandra/sidecar/test_user")).isFalse();
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/AllowAllAuthorizationTest.java b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/AllowAllAuthorizationTest.java
new file mode 100644
index 00000000..3af86a4e
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/AllowAllAuthorizationTest.java
@@ -0,0 +1,74 @@
+/*
+ * 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.Set;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+
+import io.vertx.ext.auth.User;
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.auth.authorization.impl.PermissionBasedAuthorizationImpl;
+import io.vertx.junit5.VertxExtension;
+import io.vertx.junit5.VertxTestContext;
+
+import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
+
+/**
+ * Test for AllowAll authorization setting
+ */
+@ExtendWith(VertxExtension.class)
+class AllowAllAuthorizationTest
+{
+ AllowAllAuthorizationProvider provider;
+
+ @BeforeEach
+ void setup()
+ {
+ provider = new AllowAllAuthorizationProvider();
+ }
+
+ @Test
+ void testAllowAllAuthorizationMatching()
+ {
+ Authorization authorization = new PermissionBasedAuthorizationImpl("test_permission");
+ User user = User.fromName("test_user");
+ assertThat(authorization.match(user)).isFalse();
+ user.authorizations().add(provider.getId(), provider.authorization);
+ assertThat(authorization.match(user)).isTrue();
+ assertThat(provider.authorization.verify(authorization)).isTrue();
+ }
+
+ @Test
+ void testAuthorizationsWithAllowAllProvider(VertxTestContext testContext)
+ {
+ User user = User.fromName("test_user");
+ provider.getAuthorizations(user)
+ .onComplete(v -> {
+ Authorization authorization = new PermissionBasedAuthorizationImpl("test_permission");
+ Set<Authorization> found = user.authorizations().get(provider.getId());
+ assertThat(found.size()).isOne();
+ assertThat(found.contains(provider.authorization)).isTrue();
+ assertThat(found.iterator().next().verify(authorization)).isTrue();
+ testContext.completeNow();
+ });
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationHandlerTest.java b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationHandlerTest.java
new file mode 100644
index 00000000..02256b2a
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/AuthorizationHandlerTest.java
@@ -0,0 +1,51 @@
+/*
+ * 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 org.junit.jupiter.api.Test;
+
+import io.vertx.ext.auth.User;
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.web.RoutingContext;
+import io.vertx.ext.web.handler.HttpException;
+
+import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Test for {@link AuthorizationWithAdminBypassHandler}
+ */
+class AuthorizationHandlerTest
+{
+ @Test
+ void testMissingIdentity()
+ {
+ AdminIdentityResolver mockAdminIdentityResolver = mock(AdminIdentityResolver.class);
+ Authorization mockAuthorization = mock(Authorization.class);
+ AuthorizationParameterValidateHandler mockValidateHandler = mock(AuthorizationParameterValidateHandler.class);
+ AuthorizationWithAdminBypassHandler authorizationHandler
+ = new AuthorizationWithAdminBypassHandler(mockValidateHandler, mockAdminIdentityResolver, mockAuthorization);
+ RoutingContext mockCtx = mock(RoutingContext.class);
+ User user = User.fromName("test_user");
+ when(mockCtx.user()).thenReturn(user);
+ assertThatThrownBy(() -> authorizationHandler.handle(mockCtx))
+ .isInstanceOf(HttpException.class);
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/PermissionTest.java b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/PermissionTest.java
new file mode 100644
index 00000000..aa5d3e8e
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/PermissionTest.java
@@ -0,0 +1,103 @@
+/*
+ * 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 org.junit.jupiter.api.Test;
+
+import io.vertx.ext.auth.authorization.PermissionBasedAuthorization;
+import io.vertx.ext.auth.authorization.WildcardPermissionBasedAuthorization;
+
+import static org.apache.cassandra.sidecar.utils.AuthUtils.permissionFromName;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/**
+ * Test for {@link Permission}
+ */
+class PermissionTest
+{
+ @Test
+ void testValidActions()
+ {
+ assertThat(permissionFromName("CREATE_SNAPSHOT")).isInstanceOf(StandardPermission.class);
+ assertThat(permissionFromName("OPERATE")).isInstanceOf(StandardPermission.class);
+ assertThat(permissionFromName("CREATESNAPSHOT")).isInstanceOf(StandardPermission.class);
+ assertThat(permissionFromName("SNAPSHOT:CREATE")).isInstanceOf(DomainAwarePermission.class);
+ assertThat(permissionFromName("SNAPSHOT:CREATE,READ")).isInstanceOf(DomainAwarePermission.class);
+ assertThat(permissionFromName("SNAPSHOT:CREATE:NEW")).isInstanceOf(DomainAwarePermission.class);
+ }
+
+ @Test
+ void testInvalidActions()
+ {
+ assertThatThrownBy(() -> permissionFromName("")).isInstanceOf(IllegalArgumentException.class);
+ assertThatThrownBy(() -> permissionFromName(null)).isInstanceOf(NullPointerException.class);
+ }
+
+ @Test
+ void testToAuthorizationWithResource()
+ {
+ String expectedResource = VariableAwareResource.DATA_WITH_KEYSPACE_TABLE.resource();
+ PermissionBasedAuthorization authorization
+ = (PermissionBasedAuthorization) permissionFromName("CREATESNAPSHOT").toAuthorization(expectedResource);
+ assertThat(authorization.getResource()).isEqualTo(expectedResource);
+ WildcardPermissionBasedAuthorization wildcardAuthorization
+ = (WildcardPermissionBasedAuthorization) permissionFromName("SNAPSHOT:CREATE").toAuthorization(expectedResource);
+ assertThat(wildcardAuthorization.getResource()).isEqualTo(expectedResource);
+ }
+
+ @Test
+ void testToAuthorizationWithEmptyResource()
+ {
+ PermissionBasedAuthorization authorization
+ = (PermissionBasedAuthorization) permissionFromName("CREATESNAPSHOT").toAuthorization("");
+ assertThat(authorization.getResource()).isNull();
+ WildcardPermissionBasedAuthorization wildcardAuthorization
+ = (WildcardPermissionBasedAuthorization) permissionFromName("SNAPSHOT:CREATE").toAuthorization("");
+ assertThat(wildcardAuthorization.getResource()).isNull();
+ }
+
+ @Test
+ void testInvalidWildcardActions()
+ {
+ assertThatThrownBy(() -> new DomainAwarePermission("*"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("DomainAwarePermission can not have * to avoid unpredictable behavior");
+
+ assertThatThrownBy(() -> new DomainAwarePermission(":"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("DomainAwarePermission parts can not be empty");
+
+ assertThatThrownBy(() -> new DomainAwarePermission("::"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("DomainAwarePermission parts can not be empty");
+
+ assertThatThrownBy(() -> new DomainAwarePermission("a::d"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("DomainAwarePermission parts can not be empty");
+
+ assertThatThrownBy(() -> new DomainAwarePermission("a"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("DomainAwarePermission must have : to divide domain and action");
+
+ assertThatThrownBy(() -> new DomainAwarePermission("a,b,c"))
+ .isInstanceOf(IllegalArgumentException.class)
+ .hasMessage("DomainAwarePermission must have : to divide domain and action");
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationProviderTest.java b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationProviderTest.java
new file mode 100644
index 00000000..807fad26
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/RoleBasedAuthorizationProviderTest.java
@@ -0,0 +1,110 @@
+/*
+ * 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.Arrays;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+
+import io.vertx.ext.auth.User;
+import io.vertx.ext.auth.mtls.impl.MutualTlsUser;
+import io.vertx.junit5.VertxExtension;
+import io.vertx.junit5.VertxTestContext;
+import org.apache.cassandra.sidecar.acl.IdentityToRoleCache;
+
+import static com.datastax.driver.core.Assertions.assertThat;
+import static org.apache.cassandra.sidecar.utils.AuthUtils.permissionFromName;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Test for {@link RoleBasedAuthorizationProvider}
+ */
+@ExtendWith(VertxExtension.class)
+class RoleBasedAuthorizationProviderTest
+{
+ RoleAuthorizationsCache mockRolePermissionsCache;
+
+ @BeforeEach
+ void setup()
+ {
+ mockRolePermissionsCache = mock(RoleAuthorizationsCache.class);
+ }
+
+ @Test
+ void testMissingIdentity(VertxTestContext testContext)
+ {
+ IdentityToRoleCache mockIdentityToRoleCache = mock(IdentityToRoleCache.class);
+ RoleBasedAuthorizationProvider authorizationProvider = new RoleBasedAuthorizationProvider(mockIdentityToRoleCache,
+ mockRolePermissionsCache);
+ User user = User.fromName("test_user");
+ authorizationProvider.getAuthorizations(user)
+ .onSuccess(v -> testContext.failNow("With missing identity authorization provider is expected to return a failed future"))
+ .onFailure(cause -> testContext.completeNow());
+ }
+
+ @Test
+ void testCassandraRoleNotFound() throws Exception
+ {
+ IdentityToRoleCache mockIdentityToRoleCache = mock(IdentityToRoleCache.class);
+ RoleAuthorizationsCache mockRolePermissionsCache = mock(RoleAuthorizationsCache.class);
+ RoleBasedAuthorizationProvider authorizationProvider = new RoleBasedAuthorizationProvider(mockIdentityToRoleCache,
+ mockRolePermissionsCache);
+ User user = MutualTlsUser.fromIdentities(Collections.singletonList("spiffe://cassandra/sidecar/test_user"));
+
+ CountDownLatch waitForEmptyAuthorizations = new CountDownLatch(1);
+ authorizationProvider.getAuthorizations(user).onComplete(v -> waitForEmptyAuthorizations.countDown());
+ assertThat(waitForEmptyAuthorizations.await(30, TimeUnit.SECONDS)).isTrue();
+
+ assertThat(user.authorizations().get("RoleBasedAccessControl")).isEmpty();
+
+ when(mockIdentityToRoleCache.get("spiffe://cassandra/sidecar/test_user")).thenReturn("test_role");
+ when(mockRolePermissionsCache.getAuthorizations("test_role")).thenReturn(Collections.singleton(permissionFromName("RANDOM").toAuthorization()));
+
+ CountDownLatch waitForAuthorizations = new CountDownLatch(1);
+ authorizationProvider.getAuthorizations(user).onComplete(v -> waitForAuthorizations.countDown());
+ assertThat(waitForAuthorizations.await(30, TimeUnit.SECONDS)).isTrue();
+
+ assertThat(user.authorizations().get("RoleBasedAccessControl")).isNotEmpty();
+ }
+
+ @Test
+ void testAuthorizationsFetched(VertxTestContext testContext)
+ {
+ IdentityToRoleCache mockIdentityToRoleCache = mock(IdentityToRoleCache.class);
+ when(mockIdentityToRoleCache.get("spiffe://cassandra/sidecar/test_user")).thenReturn("test_role");
+ RoleAuthorizationsCache mockRolePermissionsCache = mock(RoleAuthorizationsCache.class);
+ when(mockRolePermissionsCache.getAuthorizations("test_role"))
+ .thenReturn(new HashSet<>(Arrays.asList(CassandraPermissions.CREATE.toAuthorization(), BasicPermissions.CREATE_SNAPSHOT.toAuthorization())));
+ RoleBasedAuthorizationProvider authorizationProvider = new RoleBasedAuthorizationProvider(mockIdentityToRoleCache,
+ mockRolePermissionsCache);
+ User user = MutualTlsUser.fromIdentities(Collections.singletonList("spiffe://cassandra/sidecar/test_user"));
+ authorizationProvider.getAuthorizations(user)
+ .onComplete(testContext.succeeding(v -> {
+ assertThat(user.authorizations().get(authorizationProvider.getId())).hasSize(2);
+ testContext.completeNow();
+ }));
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/SuperUserCacheTest.java b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/SuperUserCacheTest.java
new file mode 100644
index 00000000..3f8eae8c
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/acl/authorization/SuperUserCacheTest.java
@@ -0,0 +1,128 @@
+/*
+ * 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.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
+import com.google.common.collect.ImmutableMap;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+
+import io.vertx.core.Vertx;
+import io.vertx.core.json.JsonObject;
+import org.apache.cassandra.sidecar.common.server.utils.MillisecondBoundConfiguration;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.apache.cassandra.sidecar.config.AccessControlConfiguration;
+import org.apache.cassandra.sidecar.config.CacheConfiguration;
+import org.apache.cassandra.sidecar.config.SidecarConfiguration;
+import org.apache.cassandra.sidecar.db.SystemAuthDatabaseAccessor;
+
+import static org.apache.cassandra.sidecar.AssertionUtils.loopAssert;
+import static org.apache.cassandra.sidecar.ExecutorPoolsHelper.createdSharedTestPool;
+import static org.apache.cassandra.sidecar.server.SidecarServerEvents.ON_SIDECAR_SCHEMA_INITIALIZED;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Test for {@link SuperUserCache}
+ */
+class SuperUserCacheTest
+{
+ Vertx vertx;
+ ExecutorPools executorPools;
+
+ @BeforeEach
+ void setup()
+ {
+ vertx = Vertx.vertx();
+ executorPools = createdSharedTestPool(vertx);
+ }
+
+ @Test
+ void testBulkLoad()
+ {
+ SystemAuthDatabaseAccessor mockDbAccessor = mock(SystemAuthDatabaseAccessor.class);
+ when(mockDbAccessor.findAllRolesToSuperuserStatus()).thenReturn(ImmutableMap.of("test_role1", true,
+ "test_role2", false));
+ SidecarConfiguration mockConfig = mockConfig();
+ SuperUserCache cache = new SuperUserCache(vertx, executorPools, mockConfig, mockDbAccessor);
+ assertThat(cache.getAll().size()).isZero();
+
+ // warming cache
+ vertx.eventBus().publish(ON_SIDECAR_SCHEMA_INITIALIZED.address(), new JsonObject());
+
+ // wait for cache warming. system_auth.role_permissions table bulk loaded against a single key
+ loopAssert(3, 100, () -> {
+ assertThat(cache.getAll()).hasSize(2);
+ assertThat(cache.isSuperUser("test_role1")).isTrue();
+ assertThat(cache.isSuperUser("test_role2")).isFalse();
+ });
+ }
+
+ @Test
+ void testCacheDisabled()
+ {
+ Map<String, Boolean> superUserMap = new HashMap<>();
+ superUserMap.put("test_role1", true);
+ superUserMap.put("test_role2", false);
+ SystemAuthDatabaseAccessor mockDbAccessor = mock(SystemAuthDatabaseAccessor.class);
+ when(mockDbAccessor.isSuperUser("test_role")).thenReturn(true);
+ when(mockDbAccessor.findAllRolesToSuperuserStatus()).thenReturn(superUserMap);
+ SidecarConfiguration mockConfig = mockConfig();
+ when(mockConfig.accessControlConfiguration().permissionCacheConfiguration().enabled()).thenReturn(false);
+ SuperUserCache superUserCache = new SuperUserCache(vertx, executorPools, mockConfig, mockDbAccessor);
+ assertThat(superUserCache.get("test_role")).isTrue();
+ assertThat(superUserCache.isSuperUser("test_role")).isTrue();
+ assertThat(superUserCache.getAll().size()).isEqualTo(2);
+ }
+
+ @Test
+ void testEmptyEntriesFetched()
+ {
+ SystemAuthDatabaseAccessor mockDbAccessor = mock(SystemAuthDatabaseAccessor.class);
+ when(mockDbAccessor.findAllRolesToSuperuserStatus()).thenReturn(Collections.emptyMap());
+ SidecarConfiguration mockConfig = mockConfig();
+ SuperUserCache cache = new SuperUserCache(vertx, executorPools, mockConfig, mockDbAccessor);
+ assertThat(cache.getAll().size()).isZero();
+
+ // warming cache
+ vertx.eventBus().publish(ON_SIDECAR_SCHEMA_INITIALIZED.address(), new JsonObject());
+
+ // wait for cache warming. system_auth.role_permissions table bulk loaded against a single key
+ loopAssert(3, 100, () -> assertThat(cache.getAll().size()).isZero());
+ }
+
+ private SidecarConfiguration mockConfig()
+ {
+ SidecarConfiguration mockConfig = mock(SidecarConfiguration.class);
+ AccessControlConfiguration mockAccessControlConfig = mock(AccessControlConfiguration.class);
+ when(mockConfig.accessControlConfiguration()).thenReturn(mockAccessControlConfig);
+ CacheConfiguration mockCacheConfig = mock(CacheConfiguration.class);
+ when(mockCacheConfig.enabled()).thenReturn(true);
+ when(mockCacheConfig.expireAfterAccess()).thenReturn(MillisecondBoundConfiguration.parse("3s"));
+ when(mockCacheConfig.maximumSize()).thenReturn(10L);
+ when(mockCacheConfig.warmupRetries()).thenReturn(5);
+ when(mockCacheConfig.warmupRetryInterval()).thenReturn(MillisecondBoundConfiguration.parse("1s"));
+ when(mockAccessControlConfig.permissionCacheConfiguration()).thenReturn(mockCacheConfig);
+ return mockConfig;
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/config/SidecarConfigurationTest.java b/server/src/test/java/org/apache/cassandra/sidecar/config/SidecarConfigurationTest.java
index d386fbf3..861c91e0 100644
--- a/server/src/test/java/org/apache/cassandra/sidecar/config/SidecarConfigurationTest.java
+++ b/server/src/test/java/org/apache/cassandra/sidecar/config/SidecarConfigurationTest.java
@@ -337,6 +337,9 @@ class SidecarConfigurationTest
.contains(entry("certificate_validator", "io.vertx.ext.auth.mtls.impl.AllowAllCertificateValidator"),
entry("certificate_identity_extractor", "org.apache.cassandra.sidecar.acl.authentication.CassandraIdentityExtractor"));
+ ParameterizedClassConfiguration authorizer = accessControlConfiguration.authorizerConfiguration();
+ assertThat(authorizer.className()).isEqualTo("org.apache.cassandra.sidecar.acl.authorization.RoleBasedAuthorizationProvider");
+
assertThat(accessControlConfiguration.adminIdentities().size()).isEqualTo(2);
assertThat(accessControlConfiguration.adminIdentities()).contains("spiffe://authorized/admin/identity1");
assertThat(accessControlConfiguration.adminIdentities()).contains("spiffe://authorized/admin/identity2");
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/db/BasicPermissionsDatabaseAccessorTest.java b/server/src/test/java/org/apache/cassandra/sidecar/db/BasicPermissionsDatabaseAccessorTest.java
new file mode 100644
index 00000000..2293db5a
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/db/BasicPermissionsDatabaseAccessorTest.java
@@ -0,0 +1,80 @@
+/*
+ * 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.db;
+
+import java.util.Collections;
+
+import org.junit.jupiter.api.Test;
+
+import com.datastax.driver.core.BoundStatement;
+import com.datastax.driver.core.PreparedStatement;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.Statement;
+import org.apache.cassandra.sidecar.common.server.CQLSessionProvider;
+import org.apache.cassandra.sidecar.db.schema.SidecarRolePermissionsSchema;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Test for {@link SidecarPermissionsDatabaseAccessor}
+ */
+class BasicPermissionsDatabaseAccessorTest
+{
+ @Test
+ void testReadingInvalidActions()
+ {
+ SidecarRolePermissionsSchema mockSchema = mock(SidecarRolePermissionsSchema.class);
+ PreparedStatement mockStmt = mock(PreparedStatement.class);
+ BoundStatement mockBoundStmt = mock(BoundStatement.class);
+ when(mockStmt.bind()).thenReturn(mockBoundStmt);
+ when(mockSchema.allRolesPermissions()).thenReturn(mockStmt);
+
+ CQLSessionProvider mockSessionProvider = mock(CQLSessionProvider.class);
+ TestSidecarPermissionsDatabaseAccessor sidecarPermissionsDatabaseAccessor
+ = new TestSidecarPermissionsDatabaseAccessor(mockSchema, mockSessionProvider);
+
+ assertThat(sidecarPermissionsDatabaseAccessor.rolesToAuthorizations()).isEmpty();
+ }
+
+ static class TestSidecarPermissionsDatabaseAccessor extends SidecarPermissionsDatabaseAccessor
+ {
+
+ protected TestSidecarPermissionsDatabaseAccessor(SidecarRolePermissionsSchema tableSchema,
+ CQLSessionProvider sessionProvider)
+ {
+ super(tableSchema, sessionProvider);
+ }
+
+ @Override
+ protected ResultSet execute(Statement statement)
+ {
+ ResultSet mockResultSet = mock(ResultSet.class);
+ Row mockRow = mock(Row.class);
+ when(mockRow.getString("role")).thenReturn("test_role");
+ when(mockRow.getString("resource")).thenReturn("test_resource");
+ // invalid wildcard permission set
+ when(mockRow.getSet("permissions", String.class)).thenReturn(Collections.singleton(":"));
+ when(mockResultSet.iterator()).thenReturn(Collections.singletonList(mockRow).iterator());
+ return mockResultSet;
+ }
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/db/SidecarSchemaTest.java b/server/src/test/java/org/apache/cassandra/sidecar/db/SidecarSchemaTest.java
index f44d4f17..26c19750 100644
--- a/server/src/test/java/org/apache/cassandra/sidecar/db/SidecarSchemaTest.java
+++ b/server/src/test/java/org/apache/cassandra/sidecar/db/SidecarSchemaTest.java
@@ -129,7 +129,7 @@ public class SidecarSchemaTest
Uninterruptibles.sleepUninterruptibly(500, TimeUnit.MILLISECONDS);
}
- assertThat(interceptedExecStmts.size()).isEqualTo(5);
+ assertThat(interceptedExecStmts.size()).isEqualTo(6);
assertThat(interceptedExecStmts.get(0)).as("Create keyspace should be executed the first")
.contains("CREATE KEYSPACE IF NOT EXISTS sidecar_internal");
assertThat(interceptedExecStmts).as("Create table should be executed for job table")
@@ -138,6 +138,8 @@ public class SidecarSchemaTest
.anyMatch(stmt -> stmt.contains("CREATE TABLE IF NOT EXISTS sidecar_internal.restore_slice_v3"));
assertThat(interceptedExecStmts).as("Create table should be executed for range table")
.anyMatch(stmt -> stmt.contains("CREATE TABLE IF NOT EXISTS sidecar_internal.restore_range_v1"));
+ assertThat(interceptedExecStmts).as("Create table should be executed for role_permissions_v1 table")
+ .anyMatch(stmt -> stmt.contains("CREATE TABLE IF NOT EXISTS sidecar_internal.role_permissions_v1"));
List<String> expectedPrepStatements = Arrays.asList(
"INSERT INTO sidecar_internal.restore_job_v4 ( created_at, job_id, keyspace_name, table_name, " +
@@ -181,7 +183,15 @@ public class SidecarSchemaTest
"VALUES ('cluster_lease_holder',?) IF NOT EXISTS USING TTL 120",
"UPDATE sidecar_internal.sidecar_lease_v1 USING TTL 120 SET owner = ? " +
- "WHERE name = 'cluster_lease_holder' IF owner = ?"
+ "WHERE name = 'cluster_lease_holder' IF owner = ?",
+
+ "SELECT * FROM sidecar_internal.role_permissions_v1",
+
+ "SELECT is_superuser FROM system_auth.roles WHERE role = ?",
+
+ "SELECT * FROM system_auth.roles",
+
+ "SELECT * FROM system_auth.role_permissions"
);
assertThat(interceptedPrepStmts).as("Intercepted statements match expected statements")
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/db/SystemAuthDatabaseAccessorTest.java b/server/src/test/java/org/apache/cassandra/sidecar/db/SystemAuthDatabaseAccessorTest.java
index 7f1efc90..017662e7 100644
--- a/server/src/test/java/org/apache/cassandra/sidecar/db/SystemAuthDatabaseAccessorTest.java
+++ b/server/src/test/java/org/apache/cassandra/sidecar/db/SystemAuthDatabaseAccessorTest.java
@@ -41,9 +41,9 @@ class SystemAuthDatabaseAccessorTest
mockCqlSessionProvider);
assertThatThrownBy(() -> systemAuthDatabaseAccessor.findRoleFromIdentity("spiffe://cassandra/sidecar/test"))
.isInstanceOf(SchemaUnavailableException.class)
- .hasMessage("SystemAuthSchema was not prepared, values cannot be retrieved from table");
+ .hasMessage("Table system_auth.identity_to_role does not exist");
assertThatThrownBy(systemAuthDatabaseAccessor::findAllIdentityToRoles)
.isInstanceOf(SchemaUnavailableException.class)
- .hasMessage("SystemAuthSchema was not prepared, values cannot be retrieved from table");
+ .hasMessage("Table system_auth.identity_to_role does not exist");
}
}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/db/SystemAuthSchemaTest.java b/server/src/test/java/org/apache/cassandra/sidecar/db/SystemAuthSchemaTest.java
index 851644a6..912a513d 100644
--- a/server/src/test/java/org/apache/cassandra/sidecar/db/SystemAuthSchemaTest.java
+++ b/server/src/test/java/org/apache/cassandra/sidecar/db/SystemAuthSchemaTest.java
@@ -25,8 +25,9 @@ import com.datastax.driver.core.KeyspaceMetadata;
import com.datastax.driver.core.Metadata;
import com.datastax.driver.core.Session;
import org.apache.cassandra.sidecar.db.schema.SystemAuthSchema;
+import org.apache.cassandra.sidecar.exceptions.SchemaUnavailableException;
-import static com.datastax.driver.core.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@@ -48,8 +49,11 @@ class SystemAuthSchemaTest
when(mockSession.getCluster()).thenReturn(mockCluster);
SystemAuthSchema systemAuthSchema = new SystemAuthSchema();
- systemAuthSchema.initialize(mockSession, ignored -> true);
- assertThat(systemAuthSchema.selectRoleFromIdentity()).isNull();
- assertThat(systemAuthSchema.getAllRolesAndIdentities()).isNull();
+ assertThatThrownBy(systemAuthSchema::roleFromIdentity)
+ .isExactlyInstanceOf(SchemaUnavailableException.class)
+ .hasMessage("Table system_auth.identity_to_role does not exist");
+ assertThatThrownBy(systemAuthSchema::allRolesAndIdentities)
+ .isExactlyInstanceOf(SchemaUnavailableException.class)
+ .hasMessage("Table system_auth.identity_to_role does not exist");
}
}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/routes/AccessProtectedRouteBuilderTest.java b/server/src/test/java/org/apache/cassandra/sidecar/routes/AccessProtectedRouteBuilderTest.java
new file mode 100644
index 00000000..44f1b22f
--- /dev/null
+++ b/server/src/test/java/org/apache/cassandra/sidecar/routes/AccessProtectedRouteBuilderTest.java
@@ -0,0 +1,89 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.sidecar.routes;
+
+import org.junit.jupiter.api.Test;
+
+import io.vertx.core.http.HttpMethod;
+import io.vertx.ext.auth.authorization.AuthorizationProvider;
+import io.vertx.ext.web.Router;
+import org.apache.cassandra.sidecar.acl.authorization.AdminIdentityResolver;
+import org.apache.cassandra.sidecar.acl.authorization.AuthorizationParameterValidateHandler;
+import org.apache.cassandra.sidecar.common.ApiEndpointsV1;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.apache.cassandra.sidecar.config.AccessControlConfiguration;
+import org.apache.cassandra.sidecar.exceptions.ConfigurationException;
+import org.apache.cassandra.sidecar.utils.CassandraInputValidator;
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+/**
+ * Test for {@link AccessProtectedRouteBuilder}
+ */
+class AccessProtectedRouteBuilderTest
+{
+ @Test
+ void testRequiredParameters()
+ {
+ AccessControlConfiguration mockConfig = mock(AccessControlConfiguration.class);
+ AuthorizationProvider mockAuthorizationProvider = mock(AuthorizationProvider.class);
+ AdminIdentityResolver mockAdminIdentityResolver = mock(AdminIdentityResolver.class);
+ AuthorizationParameterValidateHandler mockHandler = mock(AuthorizationParameterValidateHandler.class);
+ AccessProtectedRouteBuilder accessProtectedRouteBuilder = new AccessProtectedRouteBuilder(mockConfig,
+ mockAuthorizationProvider,
+ mockAdminIdentityResolver,
+ mockHandler);
+ Router mockRouter = mock(Router.class);
+ accessProtectedRouteBuilder.router(mockRouter);
+ accessProtectedRouteBuilder.method(HttpMethod.GET);
+ accessProtectedRouteBuilder.endpoint("/api/v1/__health");
+ assertThatThrownBy(accessProtectedRouteBuilder::build).isInstanceOf(IllegalArgumentException.class);
+ }
+
+ @Test
+ void testRouteWithoutAccessProtected()
+ {
+ AccessControlConfiguration mockConfig = mock(AccessControlConfiguration.class);
+ when(mockConfig.enabled()).thenReturn(true);
+ AuthorizationProvider mockAuthorizationProvider = mock(AuthorizationProvider.class);
+ AdminIdentityResolver mockAdminIdentityResolver = mock(AdminIdentityResolver.class);
+ AuthorizationParameterValidateHandler mockHandler = mock(AuthorizationParameterValidateHandler.class);
+ AccessProtectedRouteBuilder accessProtectedRouteBuilder
+ = new AccessProtectedRouteBuilder(mockConfig, mockAuthorizationProvider, mockAdminIdentityResolver,
+ mockHandler);
+ Router mockRouter = mock(Router.class);
+ InstanceMetadataFetcher mockMetadataFetcher = mock(InstanceMetadataFetcher.class);
+ ExecutorPools mockExecutorPools = mock(ExecutorPools.class);
+ CassandraInputValidator mockValidator = mock(CassandraInputValidator.class);
+ CassandraHealthHandler cassandraHealthHandler
+ = new CassandraHealthHandler(mockMetadataFetcher, mockExecutorPools, mockValidator);
+ assertThatThrownBy(() -> {
+ accessProtectedRouteBuilder.endpoint(ApiEndpointsV1.HEALTH_ROUTE)
+ .method(HttpMethod.GET)
+ .router(mockRouter)
+ .handler(cassandraHealthHandler)
+ .build();
+ })
+ .isInstanceOf(ConfigurationException.class)
+ .hasMessage("Authorized route must have authorizations declared");
+ }
+}
diff --git a/server/src/test/java/org/apache/cassandra/sidecar/server/ServerTest.java b/server/src/test/java/org/apache/cassandra/sidecar/server/ServerTest.java
index be0a51b9..50f65a51 100644
--- a/server/src/test/java/org/apache/cassandra/sidecar/server/ServerTest.java
+++ b/server/src/test/java/org/apache/cassandra/sidecar/server/ServerTest.java
@@ -308,6 +308,16 @@ class ServerTest
"UnrecognizedAuthenticationHandler has not been registered");
}
+ @Test
+ @DisplayName("Invalid access control config, unrecognized authorization provider set")
+ void unrecognizedAuthorizationProviderSet()
+ {
+ assertThatThrownBy(() -> configureServer("config/sidecar_unrecognized_authorizer.yaml"))
+ .hasCauseInstanceOf(ConfigurationException.class)
+ .hasMessageContaining("Unrecognized authorization provider org.apache.cassandra.sidecar.acl." +
+ "authorization.UnrecognizedAuthorizationProvider set");
+ }
+
Future<String> validateHealthEndpoint(String deploymentId)
{
LOGGER.info("Checking server health 127.0.0.1:{}/api/v1/__health", server.actualPort());
diff --git a/server/src/test/resources/config/sidecar_multiple_instances.yaml b/server/src/test/resources/config/sidecar_multiple_instances.yaml
index be7a71da..f169bfdc 100644
--- a/server/src/test/resources/config/sidecar_multiple_instances.yaml
+++ b/server/src/test/resources/config/sidecar_multiple_instances.yaml
@@ -139,6 +139,8 @@ access_control:
parameters:
certificate_validator: io.vertx.ext.auth.mtls.impl.AllowAllCertificateValidator
certificate_identity_extractor: org.apache.cassandra.sidecar.acl.authentication.CassandraIdentityExtractor
+ authorizer:
+ - class_name: org.apache.cassandra.sidecar.acl.authorization.RoleBasedAuthorizationProvider
admin_identities:
- spiffe://authorized/admin/identity1
- spiffe://authorized/admin/identity2
diff --git a/server/src/test/resources/config/sidecar_unrecognized_authorizer.yaml b/server/src/test/resources/config/sidecar_unrecognized_authorizer.yaml
new file mode 100644
index 00000000..0e10308e
--- /dev/null
+++ b/server/src/test/resources/config/sidecar_unrecognized_authorizer.yaml
@@ -0,0 +1,122 @@
+#
+# Cassandra SideCar configuration file
+#
+cassandra:
+ host: localhost
+ port: 9042
+ data_dirs:
+ - /ccm/test/node1/data0
+ - /ccm/test/node1/data1
+ staging_dir: /ccm/test/node1/sstable-staging
+ jmx_host: 127.0.0.1
+ jmx_port: 7199
+ jmx_role: controlRole
+ jmx_role_password: controlPassword
+ jmx_ssl_enabled: true
+
+sidecar:
+ host: 0.0.0.0
+ port: 9043
+ request_idle_timeout_millis: 300000 # this field expects integer value
+ request_timeout_millis: 300000
+ tcp_keep_alive: false
+ accept_backlog: 1024
+ server_verticle_instances: 2
+ throttle:
+ stream_requests_per_sec: 5000
+ timeout_sec: 10
+ traffic_shaping:
+ inbound_global_bandwidth_bps: 500
+ outbound_global_bandwidth_bps: 1500
+ peak_outbound_global_bandwidth_bps: 2000
+ max_delay_to_wait_millis: 2500
+ check_interval_for_stats_millis: 3000
+ sstable_upload:
+ concurrent_upload_limit: 80
+ min_free_space_percent: 10
+ # file_permissions: "rw-r--r--" # when not specified, the default file permissions are owner read & write, group & others read
+ allowable_time_skew_in_minutes: 60
+ sstable_import:
+ poll_interval_millis: 100
+ cache:
+ expire_after_access_millis: 7200000 # 2 hours
+ maximum_size: 10000
+ sstable_snapshot:
+ snapshot_list_cache:
+ expire_after_access_millis: 350
+ maximum_size: 450
+ worker_pools:
+ service:
+ name: "sidecar-worker-pool"
+ size: 20
+ max_execution_time_millis: 60000 # 60 seconds
+ internal:
+ name: "sidecar-internal-worker-pool"
+ size: 20
+ max_execution_time_millis: 900000 # 15 minutes
+ jmx:
+ max_retries: 42
+ retry_delay_millis: 1234
+ schema:
+ is_enabled: false
+ keyspace: sidecar_internal
+ replication_strategy: SimpleStrategy
+ replication_factor: 1
+
+#
+# Enable SSL configuration (Disabled by default)
+#
+# ssl:
+# enabled: true
+# use_openssl: true
+# handshake_timeout_sec: 10
+# client_auth: NONE # valid options are NONE, REQUEST, REQUIRED
+# accepted_protocols:
+# - TLSv1.2
+# - TLSv1.3
+# cipher_suites: []
+# keystore:
+# type: PKCS12
+# path: "path/to/keystore.p12"
+# password: password
+# check_interval_sec: 300
+# truststore:
+# path: "path/to/truststore.p12"
+# password: password
+
+access_control:
+ enabled: true
+ authenticators:
+ - class_name: org.apache.cassandra.sidecar.acl.authentication.MutualTlsAuthenticationHandlerFactory
+ parameters:
+ certificate_validator: io.vertx.ext.auth.mtls.impl.AllowAllCertificateValidator
+ certificate_identity_extractor: org.apache.cassandra.sidecar.acl.authentication.CassandraIdentityExtractor
+ authorizer:
+ - class_name: org.apache.cassandra.sidecar.acl.authorization.UnrecognizedAuthorizationProvider
+ admin_identities:
+ - spiffe://authorized/admin/identity1
+ - spiffe://authorized/admin/identity2
+ permission_cache:
+ enabled: true
+ expire_after_access_millis: 300000
+ maximum_size: 1000
+ warmup_retries: 5
+ warmup_retry_interval_millis: 2000
+
+healthcheck:
+ initial_delay_millis: 100
+ poll_freq_millis: 30000
+
+cassandra_input_validation:
+ forbidden_keyspaces:
+ - system_schema
+ - system_traces
+ - system_distributed
+ - system
+ - system_auth
+ - system_views
+ - system_virtual_schema
+ allowed_chars_for_directory: "[a-zA-Z][a-zA-Z0-9_]{0,47}"
+ allowed_chars_for_quoted_name: "[a-zA-Z_0-9]{1,48}"
+ allowed_chars_for_component_name: "[a-zA-Z0-9_-]+(.db|.cql|.json|.crc32|TOC.txt)"
+ allowed_chars_for_restricted_component_name: "[a-zA-Z0-9_-]+(.db|TOC.txt)"
---------------------------------------------------------------------
To unsubscribe, e-mail: commits-unsubscribe@cassandra.apache.org
For additional commands, e-mail: commits-help@cassandra.apache.org