diff --git a/CHANGES.txt b/CHANGES.txt index dfa56b68810d..88910136b815 100644 --- a/CHANGES.txt +++ b/CHANGES.txt @@ -1,3 +1,12 @@ +7.0 + * Support pluggable default role initialization (CASSANDRA-21546) + * Add prepared statement cache stats to nodetool info (CASSANDRA-14366) + * Don't increment client metrics on messaging service connection unpause (CASSANDRA-21491) + * Add nodetool getreplicas (CASSANDRA-17665) + * Implementation of CEP-49: Hardware-accelerated compression (CASSANDRA-20975) + * Avoid using ObjectUtils.getFirstNonNull in Schema (CASSANDRA-21394) + * Allow nodetool garbagecollect to take a user defined list of SSTables (CASSANDRA-16767) + * Add a guardrail for misprepared statements (CASSANDRA-21139) 6.0-alpha3 * Enable trickle fsync by default (CASSANDRA-21572) * Protect uncaught_exceptions virtual table against the crash path (CASSANDRA-21578) diff --git a/NEWS.txt b/NEWS.txt index 1f82fb6809c0..650ce7c2e372 100644 --- a/NEWS.txt +++ b/NEWS.txt @@ -74,6 +74,31 @@ restore snapshots created with the previous major version using the 'sstableloader' tool. You can upgrade the file format of your snapshots using the provided 'sstableupgrade' tool. +7.0 +=== + +New features +------------ + + - CEP-49 - it is possible to implement custom compression providers, e.g. + integrating with a specialized hardware which makes de/compression faster. + See CASSANDRA-20975 for more information. + - It is now possible to bootstrap a cluster's initial superuser role without + creating the 'cassandra/cassandra' password, by configuring 'default_role_initializer' + in cassandra.yaml. The new MutualTlsDefaultRoleInitializer creates the role + passwordless and maps a client certificate identity onto it instead, for + deployments that authenticate over mutual TLS. PasswordDefaultRoleInitializer + remains the default and produces the historical behaviour. See CASSANDRA-21546 + for more information. + +Upgrading +--------- + + - trickle_fsync is by default set to "true" instead of "false" in cassandra.yaml (see CASSANDRA-21572) + +Deprecation +----------- + 6.0 === diff --git a/conf/cassandra.yaml b/conf/cassandra.yaml index 67901e12bb66..1b873ae51ba3 100644 --- a/conf/cassandra.yaml +++ b/conf/cassandra.yaml @@ -241,6 +241,26 @@ role_manager: # invalid_role_disconnect_task_period: 4h # invalid_role_disconnect_task_max_jitter: 1h +# Creates the initial role on a cluster which has no roles yet, implementing IDefaultRoleInitializer. +# Most functions of the IRoleManager require an authenticated login, so a cluster with no roles has no way +# to create the first one; this option controls how that role is bootstrapped. +# +# Defaults to PasswordDefaultRoleInitializer, which creates a 'cassandra' superuser whose password is also +# 'cassandra'. That password is a published constant, so deployments using it must rotate or drop the role +# before the native transport is reachable. +# +# MutualTlsDefaultRoleInitializer instead creates the role with no password at all and maps a client +# certificate identity onto it, so there is no credential to guess. It requires an authenticator supporting +# mutual TLS, such as MutualTlsAuthenticator or MutualTlsWithPasswordFallbackAuthenticator. +# +# default_role_initializer: +# class_name: PasswordDefaultRoleInitializer # or: MutualTlsDefaultRoleInitializer +# parameters: +# role: cassandra +# password: cassandra # PasswordDefaultRoleInitializer: plaintext password +# # password_hash: "$2a$04$wsvzFamDJPDrTwMjgfcgpO.mKc.CMEuHBFZSjhGz2Ts6.v8PUO2rC" # ...or a bcrypt hash instead +# # identity: "spiffe1" # MutualTlsDefaultRoleInitializer: cert identity to map + # Network authorization backend, implementing INetworkAuthorizer; used to restrict user # access to certain DCs # Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllNetworkAuthorizer, diff --git a/conf/cassandra_latest.yaml b/conf/cassandra_latest.yaml index b33d102340dd..0038f2fe4687 100644 --- a/conf/cassandra_latest.yaml +++ b/conf/cassandra_latest.yaml @@ -244,6 +244,26 @@ role_manager: invalid_role_disconnect_task_period: 4h invalid_role_disconnect_task_max_jitter: 1h +# Creates the initial role on a cluster which has no roles yet, implementing IDefaultRoleInitializer. +# Most functions of the IRoleManager require an authenticated login, so a cluster with no roles has no way +# to create the first one; this option controls how that role is bootstrapped. +# +# Defaults to PasswordDefaultRoleInitializer, which creates a 'cassandra' superuser whose password is also +# 'cassandra'. That password is a published constant, so deployments using it must rotate or drop the role +# before the native transport is reachable. +# +# MutualTlsDefaultRoleInitializer instead creates the role with no password at all and maps a client +# certificate identity onto it, so there is no credential to guess. It requires an authenticator supporting +# mutual TLS, such as MutualTlsAuthenticator or MutualTlsWithPasswordFallbackAuthenticator. +# +# default_role_initializer: +# class_name: PasswordDefaultRoleInitializer # or: MutualTlsDefaultRoleInitializer +# parameters: +# role: cassandra +# password: cassandra # PasswordDefaultRoleInitializer: plaintext password +# # password_hash: "$2a$04$wsvzFamDJPDrTwMjgfcgpO.mKc.CMEuHBFZSjhGz2Ts6.v8PUO2rC" # ...or a bcrypt hash instead +# # identity: "spiffe1" # MutualTlsDefaultRoleInitializer: cert identity to map + # Network authorization backend, implementing INetworkAuthorizer; used to restrict user # access to certain DCs # Out of the box, Cassandra provides org.apache.cassandra.auth.{AllowAllNetworkAuthorizer, diff --git a/doc/modules/cassandra/pages/managing/operating/security.adoc b/doc/modules/cassandra/pages/managing/operating/security.adoc index 8abf888296c0..3f8031600dba 100644 --- a/doc/modules/cassandra/pages/managing/operating/security.adoc +++ b/doc/modules/cassandra/pages/managing/operating/security.adoc @@ -216,6 +216,49 @@ information in the tables of the `system_auth` keyspace. See also the xref:cassandra:developing/cql/security.adoc#database-roles[`CQL documentation on roles`]. +[[default-role-initialization]] +=== Bootstrapping the default role + +`IRoleManager` requires an authenticated login, so a freshly started cluster +with no roles yet has no way to create the first one. This bootstrap step is +pluggable and is configured by using `default_role_initializer` setting in +`cassandra.yaml`. + +By default, Cassandra uses `PasswordDefaultRoleInitializer`, which creates a +`cassandra` superuser whose password is also `cassandra` - reproducing +Cassandra's historical bootstrap behaviour. Because that password is published, +well-known constant, any deployment relying on this default must rotate or disable +the `cassandra` role before the native transport is reachable by anyone other than +the operator performing this setup. + +[source,yaml] +---- +default_role_initializer: +class_name: MutualTlsDefaultRoleInitializer +parameters: + role: cassandra + identity: "spiffe://example.org/cassandra-admin" +---- + +This requires an authenticator that supports mutual TLS, such as a `MutualTlsAuthenticator` +or `MutualTlsWithPasswordFallbackAuthenticator` - Cassandra refuses to start otherwise, +since the role it would create could never be logged into. + +`PasswordDefaultRoleInitializer` also accepts `role`, `password` and `password_hash` +parameters, to choose a different default role name or avoid the known default password +entirely. + +[source,yaml] +---- +default_role_initializer: +class_name: PasswordDefaultRoleInitializer +parameters: + role: cassandra + password_hash: "$2a$04$wsvzFamDJPDrTwMjgfcgpO.mKc.CMEuHBFZSjhGz2Ts6.v8PUO2rC" +---- + +See `conf/cassandra.yaml` for full list of supported parameters. + == Authentication Authentication is pluggable in Cassandra and is configured using the diff --git a/src/java/org/apache/cassandra/auth/AbstractDefaultRoleInitializer.java b/src/java/org/apache/cassandra/auth/AbstractDefaultRoleInitializer.java new file mode 100644 index 000000000000..ce741a0f337d --- /dev/null +++ b/src/java/org/apache/cassandra/auth/AbstractDefaultRoleInitializer.java @@ -0,0 +1,64 @@ +/* + * 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.auth; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.cql3.QueryProcessor; +import org.apache.cassandra.db.ConsistencyLevel; +import org.apache.cassandra.exceptions.RequestExecutionException; +import org.apache.cassandra.schema.SchemaConstants; +import org.apache.cassandra.tcm.ClusterMetadata; + +import static org.apache.cassandra.auth.AuthUtils.escapeCqlLiteral; + +public abstract class AbstractDefaultRoleInitializer implements IDefaultRoleInitializer +{ + private static final Logger logger = LoggerFactory.getLogger(AbstractDefaultRoleInitializer.class); + + @Override + public final void initializeDefaultRoleIfNeeded() + { + if (ClusterMetadata.current().tokenMap.tokens().isEmpty()) + throw new IllegalStateException(getClass().getSimpleName() + " skipped role setup: no known tokens in the ring"); + + try + { + if (!hasExistingRoles()) + createDefaultRole(); + } + catch (RequestExecutionException e) + { + logger.warn("{} skipped default role setup: some nodes were not ready", getClass().getSimpleName()); + throw e; + } + } + + @Override + public final boolean hasExistingRoles() + { + // Try looking up the configured default role first, to avoid the range query if possible. + String defaultRoleQuery = String.format("SELECT * FROM %s.%s WHERE role = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, escapeCqlLiteral(defaultRoleName())); + String allUsersQuery = String.format("SELECT * FROM %s.%s LIMIT 1", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES); + return !QueryProcessor.process(defaultRoleQuery, ConsistencyLevel.ONE).isEmpty() + || !QueryProcessor.process(defaultRoleQuery, ConsistencyLevel.QUORUM).isEmpty() + || !QueryProcessor.process(allUsersQuery, ConsistencyLevel.QUORUM).isEmpty(); + } +} diff --git a/src/java/org/apache/cassandra/auth/AuthConfig.java b/src/java/org/apache/cassandra/auth/AuthConfig.java index a9257f19059d..cfa43a897ce3 100644 --- a/src/java/org/apache/cassandra/auth/AuthConfig.java +++ b/src/java/org/apache/cassandra/auth/AuthConfig.java @@ -92,6 +92,14 @@ public static void applyAuth() DatabaseDescriptor.setAuthorizer(authorizer); + // default role initializer: bootstraps the first role on a cluster which has none yet. Instantiated + // before the role manager because the role manager depends on it (see IRoleManager#defaultRoleInitializer). + + IDefaultRoleInitializer defaultRoleInitializer = authInstantiate(conf.default_role_initializer, + IDefaultRoleInitializer.class, + PasswordDefaultRoleInitializer.instance); + DatabaseDescriptor.setDefaultRoleInitializer(defaultRoleInitializer); + // role manager IRoleManager roleManager = authInstantiate(conf.role_manager, IRoleManager.class, CassandraRoleManager.class); @@ -99,6 +107,8 @@ public static void applyAuth() if (authenticator instanceof PasswordAuthenticator && !(roleManager instanceof CassandraRoleManager)) throw new ConfigurationException(authenticator.getClass().getName() + " requires " + CassandraRoleManager.class.getName(), false); + validateDefaultRoleInitializerSupportsRoleManager(conf.default_role_initializer, defaultRoleInitializer, roleManager); + DatabaseDescriptor.setRoleManager(roleManager); // authenticator @@ -136,18 +146,33 @@ public static void applyAuth() authenticator.validateConfiguration(); authorizer.validateConfiguration(); roleManager.validateConfiguration(); + defaultRoleInitializer.validateConfiguration(); networkAuthorizer.validateConfiguration(); cidrAuthorizer.validateConfiguration(); DatabaseDescriptor.getInternodeAuthenticator().validateConfiguration(); } - private static T authInstantiate(ParameterizedClass authCls, Class expectedType, Class defaultCls) { + @VisibleForTesting + static void validateDefaultRoleInitializerSupportsRoleManager(ParameterizedClass configuredInitializer, + IDefaultRoleInitializer defaultRoleInitializer, + IRoleManager roleManager) + { + boolean explicitlyConfigured = configuredInitializer != null && configuredInitializer.class_name != null; + if (explicitlyConfigured && !defaultRoleInitializer.supportsRoleManager(roleManager)) + throw new ConfigurationException(defaultRoleInitializer.getClass().getName() + " does not support " + roleManager.getClass().getName(), false); + } + + private static T authInstantiate(ParameterizedClass authCls, Class expectedType, Class defaultCls) + { if (authCls != null && authCls.class_name != null) { String authPackage = AuthConfig.class.getPackage().getName(); return ParameterizedClass.newInstance(authCls, List.of("", authPackage), expectedType); } + if (defaultCls == null) + return null; + // for now, this has to stay and can not be replaced by ParameterizedClass.newInstance as above // due to that failing for simulator dtests. See CASSANDRA-20450 for more information. try @@ -159,4 +184,14 @@ private static T authInstantiate(ParameterizedClass authCls, Class expect throw new ConfigurationException("Failed to instantiate " + defaultCls.getName(), e); } } + + private static T authInstantiate(ParameterizedClass authCls, Class expectedType, T defaultInstance) + { + if (authCls != null && authCls.class_name != null) + { + String authPackage = AuthConfig.class.getPackage().getName(); + return ParameterizedClass.newInstance(authCls, List.of("", authPackage), expectedType); + } + return defaultInstance; + } } diff --git a/src/java/org/apache/cassandra/auth/AuthUtils.java b/src/java/org/apache/cassandra/auth/AuthUtils.java new file mode 100644 index 000000000000..821845fe559e --- /dev/null +++ b/src/java/org/apache/cassandra/auth/AuthUtils.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.auth; + +import org.apache.commons.lang3.StringUtils; +import org.mindrot.jbcrypt.BCrypt; + +import org.apache.cassandra.config.DatabaseDescriptor; +import org.apache.cassandra.db.ConsistencyLevel; + +import static org.apache.cassandra.auth.PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME; + +public class AuthUtils +{ + static final ConsistencyLevel DEFAULT_SUPERUSER_CONSISTENCY_LEVEL = ConsistencyLevel.QUORUM; + + private AuthUtils() {} + + public static String hashpw(String password) + { + return BCrypt.hashpw(password, PasswordSaltSupplier.get()); + } + + /** + * Escapes a value for safe interpolation into a single-quoted CQL string literal by doubling any + * single quotes it contains (e.g. {@code o'brien} becomes {@code o''brien}). Used when building auth + * DDL/DML from role, identity and resource names via {@link String#format}. + * + * @param name the raw value to escape; {@code null} is returned unchanged + * @return the value with every {@code '} doubled + */ + public static String escapeCqlLiteral(String name) + { + return StringUtils.replace(name, "'", "''"); + } + + /** Allows selective overriding of the consistency level for specific roles. */ + public static ConsistencyLevel consistencyForRoleWrite(String role) + { + return defaultRoleName().equals(role) ? DEFAULT_SUPERUSER_CONSISTENCY_LEVEL : CassandraAuthorizer.authWriteConsistencyLevel(); + } + + public static ConsistencyLevel consistencyForRoleRead(String role) + { + return defaultRoleName().equals(role) ? DEFAULT_SUPERUSER_CONSISTENCY_LEVEL : CassandraAuthorizer.authReadConsistencyLevel(); + } + + private static String defaultRoleName() + { + IRoleManager roleManager = DatabaseDescriptor.getRoleManager(); + IDefaultRoleInitializer initializer = roleManager != null + ? roleManager.defaultRoleInitializer() + : DatabaseDescriptor.getDefaultRoleInitializer(); + return initializer != null ? initializer.defaultRoleName() : DEFAULT_SUPERUSER_NAME; + } +} diff --git a/src/java/org/apache/cassandra/auth/CassandraAuthorizer.java b/src/java/org/apache/cassandra/auth/CassandraAuthorizer.java index 245c87a91ef3..be375d3d6322 100644 --- a/src/java/org/apache/cassandra/auth/CassandraAuthorizer.java +++ b/src/java/org/apache/cassandra/auth/CassandraAuthorizer.java @@ -67,6 +67,8 @@ import org.apache.cassandra.utils.ByteBufferUtil; import org.apache.cassandra.utils.Pair; +import static org.apache.cassandra.auth.AuthUtils.escapeCqlLiteral; + /** * CassandraAuthorizer is an IAuthorizer implementation that keeps * user permissions internally in C* using the system_auth.role_permissions @@ -113,8 +115,8 @@ public Set authorize(AuthenticatedUser user, IResource resource) public Set grant(AuthenticatedUser performer, Set permissions, IResource resource, RoleResource grantee) throws RequestValidationException, RequestExecutionException { - String roleName = escape(grantee.getRoleName()); - String resourceName = escape(resource.getName()); + String roleName = escapeCqlLiteral(grantee.getRoleName()); + String resourceName = escapeCqlLiteral(resource.getName()); Set existingPermissions = getExistingPermissions(roleName, resourceName, permissions); Set nonExistingPermissions = Sets.difference(permissions, existingPermissions); @@ -130,8 +132,8 @@ public Set grant(AuthenticatedUser performer, Set permis public Set revoke(AuthenticatedUser performer, Set permissions, IResource resource, RoleResource revokee) throws RequestValidationException, RequestExecutionException { - String roleName = escape(revokee.getRoleName()); - String resourceName = escape(resource.getName()); + String roleName = escapeCqlLiteral(revokee.getRoleName()); + String resourceName = escapeCqlLiteral(resource.getName()); Set existingPermissions = getExistingPermissions(roleName, resourceName, permissions); if (!existingPermissions.isEmpty()) @@ -155,7 +157,7 @@ public void revokeAllFrom(RoleResource revokee) UntypedResultSet rows = process(String.format("SELECT resource FROM %s.%s WHERE role = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLE_PERMISSIONS, - escape(revokee.getRoleName())), + escapeCqlLiteral(revokee.getRoleName())), authReadConsistencyLevel()); List statements = new ArrayList<>(); @@ -165,8 +167,8 @@ public void revokeAllFrom(RoleResource revokee) QueryProcessor.getStatement(String.format("DELETE FROM %s.%s WHERE resource = '%s' AND role = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.RESOURCE_ROLE_INDEX, - escape(row.getString("resource")), - escape(revokee.getRoleName())), + escapeCqlLiteral(row.getString("resource")), + escapeCqlLiteral(revokee.getRoleName())), ClientState.forInternalCalls())); } @@ -174,7 +176,7 @@ public void revokeAllFrom(RoleResource revokee) statements.add(QueryProcessor.getStatement(String.format("DELETE FROM %s.%s WHERE role = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLE_PERMISSIONS, - escape(revokee.getRoleName())), + escapeCqlLiteral(revokee.getRoleName())), ClientState.forInternalCalls())); executeLoggedBatch(statements); @@ -195,7 +197,7 @@ public void revokeAllOn(IResource droppedResource) UntypedResultSet rows = process(String.format("SELECT role FROM %s.%s WHERE resource = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.RESOURCE_ROLE_INDEX, - escape(droppedResource.getName())), + escapeCqlLiteral(droppedResource.getName())), authReadConsistencyLevel()); List statements = new ArrayList<>(); @@ -204,15 +206,15 @@ public void revokeAllOn(IResource droppedResource) statements.add(QueryProcessor.getStatement(String.format("DELETE FROM %s.%s WHERE role = '%s' AND resource = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLE_PERMISSIONS, - escape(row.getString("role")), - escape(droppedResource.getName())), + escapeCqlLiteral(row.getString("role")), + escapeCqlLiteral(droppedResource.getName())), ClientState.forInternalCalls())); } statements.add(QueryProcessor.getStatement(String.format("DELETE FROM %s.%s WHERE resource = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.RESOURCE_ROLE_INDEX, - escape(droppedResource.getName())), + escapeCqlLiteral(droppedResource.getName())), ClientState.forInternalCalls())); executeLoggedBatch(statements); @@ -297,8 +299,8 @@ private void modifyRolePermissions(Set permissions, IResource resour AuthKeyspace.ROLE_PERMISSIONS, op, "'" + StringUtils.join(permissions, "','") + "'", - escape(role.getRoleName()), - escape(resource.getName())), + escapeCqlLiteral(role.getRoleName()), + escapeCqlLiteral(resource.getName())), authWriteConsistencyLevel()); } @@ -308,8 +310,8 @@ private void removeLookupEntry(IResource resource, RoleResource role) throws Req process(String.format("DELETE FROM %s.%s WHERE resource = '%s' and role = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.RESOURCE_ROLE_INDEX, - escape(resource.getName()), - escape(role.getRoleName())), + escapeCqlLiteral(resource.getName()), + escapeCqlLiteral(role.getRoleName())), authWriteConsistencyLevel()); } @@ -319,8 +321,8 @@ private void addLookupEntry(IResource resource, RoleResource role) throws Reques process(String.format("INSERT INTO %s.%s (resource, role) VALUES ('%s','%s')", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.RESOURCE_ROLE_INDEX, - escape(resource.getName()), - escape(role.getRoleName())), + escapeCqlLiteral(resource.getName()), + escapeCqlLiteral(role.getRoleName())), authWriteConsistencyLevel()); } @@ -384,13 +386,13 @@ private String buildListQuery(IResource resource, RoleResource grantee) if (resource != null) { conditions.add("resource = '%s'"); - vars.add(escape(resource.getName())); + vars.add(escapeCqlLiteral(resource.getName())); } if (grantee != null) { conditions.add(ROLE + " = '%s'"); - vars.add(escape(grantee.getRoleName())); + vars.add(escapeCqlLiteral(grantee.getRoleName())); } String query = "SELECT " + ROLE + ", resource, permissions FROM %s.%s"; @@ -428,12 +430,6 @@ private SelectStatement prepare(String entityname, String permissionsTable) return (SelectStatement) QueryProcessor.getStatement(query, ClientState.forInternalCalls()); } - // We only worry about one character ('). Make sure it's properly escaped. - private String escape(String name) - { - return StringUtils.replace(name, "'", "''"); - } - ResultMessage.Rows select(SelectStatement statement, QueryOptions options) { return statement.execute(QueryState.forInternalCalls(), options, Dispatcher.RequestTime.forImmediateExecution()); diff --git a/src/java/org/apache/cassandra/auth/CassandraRoleManager.java b/src/java/org/apache/cassandra/auth/CassandraRoleManager.java index ec4f873b5c57..4a70108a8ebc 100644 --- a/src/java/org/apache/cassandra/auth/CassandraRoleManager.java +++ b/src/java/org/apache/cassandra/auth/CassandraRoleManager.java @@ -45,8 +45,6 @@ import com.google.common.base.Strings; import com.google.common.collect.ImmutableSet; -import org.apache.commons.lang3.StringUtils; -import org.mindrot.jbcrypt.BCrypt; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -77,7 +75,6 @@ import org.apache.cassandra.service.ClientState; import org.apache.cassandra.service.StorageProxy; import org.apache.cassandra.service.StorageService; -import org.apache.cassandra.tcm.ClusterMetadata; import org.apache.cassandra.transport.Dispatcher; import org.apache.cassandra.transport.messages.ResultMessage; import org.apache.cassandra.utils.ByteBufferUtil; @@ -86,6 +83,10 @@ import org.apache.cassandra.utils.MBeanWrapper; import org.apache.cassandra.utils.NoSpamLogger; +import static org.apache.cassandra.auth.AuthUtils.consistencyForRoleRead; +import static org.apache.cassandra.auth.AuthUtils.consistencyForRoleWrite; +import static org.apache.cassandra.auth.AuthUtils.escapeCqlLiteral; +import static org.apache.cassandra.auth.AuthUtils.hashpw; import static org.apache.cassandra.service.QueryState.forInternalCalls; import static org.apache.cassandra.utils.ByteBufferUtil.bytes; @@ -106,9 +107,6 @@ public class CassandraRoleManager implements IRoleManager, CassandraRoleManagerM private static final Logger logger = LoggerFactory.getLogger(CassandraRoleManager.class); private static final NoSpamLogger nospamLogger = NoSpamLogger.getLogger(logger, 1L, TimeUnit.MINUTES); - public static final String DEFAULT_SUPERUSER_NAME = "cassandra"; - public static final String DEFAULT_SUPERUSER_PASSWORD = "cassandra"; - /** * Role options which are supported for all authentication mechanisms. IAuthenticator implementations can declare * additional supported role options via {@link IAuthenticator#getSupportedRoleOptions()}. @@ -132,13 +130,6 @@ public class CassandraRoleManager implements IRoleManager, CassandraRoleManagerM public static final String MBEAN_NAME = "org.apache.cassandra.auth:type=CassandraRoleManager"; - /** - * We need to treat the default superuser as a special case since during initial node startup, we may end up with - * duplicate creation or deletion + re-creation of this user on different nodes unless we check at quorum to see if - * it's already been done. - */ - static final ConsistencyLevel DEFAULT_SUPERUSER_CONSISTENCY_LEVEL = ConsistencyLevel.QUORUM; - // Transform a row in the AuthKeyspace.ROLES to a Role instance private static final Function ROW_TO_ROLE = row -> { @@ -217,6 +208,21 @@ public CassandraRoleManager(Map parameters) MBeanWrapper.instance.registerMBean(this, MBEAN_NAME); } + /** + * The default role initializer is configured as a top-level {@code default_role_initializer} option and + * applied by {@link AuthConfig#applyAuth()}. Returning it here lets the startup logic (see + * {@link #setup(boolean)}, {@link #hasExistingRoles()} and {@link #consistencyForRoleWrite(String)}) reach the + * configured initializer through the role manager, and lets custom {@link IRoleManager} implementations + * override how they integrate it. Falls back to the historical password initializer when auth setup has not + * run, e.g. in tests which do not call {@link AuthConfig#applyAuth()}. + */ + @Override + public IDefaultRoleInitializer defaultRoleInitializer() + { + IDefaultRoleInitializer initializer = DatabaseDescriptor.getDefaultRoleInitializer(); + return initializer == null ? PasswordDefaultRoleInitializer.instance : initializer; + } + @Override public void setup(boolean asyncRoleSetup) { @@ -228,7 +234,7 @@ public void setup(boolean asyncRoleSetup) try { // Try to set up synchronously - setupDefaultRole(); + defaultRoleInitializer().initializeDefaultRoleIfNeeded(); return; } catch (Throwable t) @@ -237,7 +243,7 @@ public void setup(boolean asyncRoleSetup) } } scheduleSetupTask(() -> { - setupDefaultRole(); + defaultRoleInitializer().initializeDefaultRoleIfNeeded(); return null; }); } @@ -342,14 +348,14 @@ public void createRole(AuthenticatedUser performer, RoleResource role, RoleOptio ? String.format("INSERT INTO %s.%s (role, is_superuser, can_login, salted_hash) VALUES ('%s', %s, %s, '%s')", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, - escape(role.getRoleName()), + escapeCqlLiteral(role.getRoleName()), options.getSuperuser().orElse(false), options.getLogin().orElse(false), - options.getHashedPassword().orElseGet(() -> escape(hashpw(options.getPassword().get())))) + options.getHashedPassword().orElseGet(() -> escapeCqlLiteral(hashpw(options.getPassword().get())))) : String.format("INSERT INTO %s.%s (role, is_superuser, can_login) VALUES ('%s', %s, %s)", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, - escape(role.getRoleName()), + escapeCqlLiteral(role.getRoleName()), options.getSuperuser().orElse(false), options.getLogin().orElse(false)); process(insertCql, consistencyForRoleWrite(role.getRoleName())); @@ -360,7 +366,7 @@ public void dropRole(AuthenticatedUser performer, RoleResource role) throws Requ process(String.format("DELETE FROM %s.%s WHERE role = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, - escape(role.getRoleName())), + escapeCqlLiteral(role.getRoleName())), consistencyForRoleWrite(role.getRoleName())); removeAllMembers(role.getRoleName()); removeAllIdentitiesOfRole(role.getRoleName()); @@ -380,7 +386,7 @@ public void alterRole(AuthenticatedUser performer, RoleResource role, RoleOption SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, assignments, - escape(role.getRoleName())), + escapeCqlLiteral(role.getRoleName())), consistencyForRoleWrite(role.getRoleName())); } } @@ -415,8 +421,8 @@ public void grantRole(AuthenticatedUser performer, RoleResource role, RoleResour process(String.format("INSERT INTO %s.%s (role, member) values ('%s', '%s')", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLE_MEMBERS, - escape(role.getRoleName()), - escape(grantee.getRoleName())), + escapeCqlLiteral(role.getRoleName()), + escapeCqlLiteral(grantee.getRoleName())), consistencyForRoleWrite(role.getRoleName())); } @@ -432,8 +438,8 @@ public void revokeRole(AuthenticatedUser performer, RoleResource role, RoleResou process(String.format("DELETE FROM %s.%s WHERE role = '%s' and member = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLE_MEMBERS, - escape(role.getRoleName()), - escape(revokee.getRoleName())), + escapeCqlLiteral(role.getRoleName()), + escapeCqlLiteral(revokee.getRoleName())), consistencyForRoleWrite(role.getRoleName())); } @@ -519,51 +525,10 @@ public void validateConfiguration() throws ConfigurationException { } - /* - * Create the default superuser role to bootstrap role creation on a clean system. Preemptively - * gives the role the default password so PasswordAuthenticator can be used to log in (if - * configured) - */ - private static void setupDefaultRole() - { - if (ClusterMetadata.current().tokenMap.tokens().isEmpty()) - throw new IllegalStateException("CassandraRoleManager skipped default role setup: no known tokens in ring"); - - try - { - if (!hasExistingRoles()) - { - QueryProcessor.process(createDefaultRoleQuery(), - consistencyForRoleWrite(DEFAULT_SUPERUSER_NAME)); - logger.info("Created default superuser role '{}'", DEFAULT_SUPERUSER_NAME); - } - } - catch (RequestExecutionException e) - { - logger.warn("CassandraRoleManager skipped default role setup: some nodes were not ready"); - throw e; - } - } - - @VisibleForTesting - public static String createDefaultRoleQuery() - { - return String.format("INSERT INTO %s.%s (role, is_superuser, can_login, salted_hash) VALUES ('%s', true, true, '%s') USING TIMESTAMP 0", - SchemaConstants.AUTH_KEYSPACE_NAME, - AuthKeyspace.ROLES, - DEFAULT_SUPERUSER_NAME, - escape(hashpw(DEFAULT_SUPERUSER_PASSWORD))); - } - @VisibleForTesting public static boolean hasExistingRoles() throws RequestExecutionException { - // Try looking up the 'cassandra' default role first, to avoid the range query if possible. - String defaultSUQuery = String.format("SELECT * FROM %s.%s WHERE role = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, DEFAULT_SUPERUSER_NAME); - String allUsersQuery = String.format("SELECT * FROM %s.%s LIMIT 1", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES); - return !QueryProcessor.process(defaultSUQuery, ConsistencyLevel.ONE).isEmpty() - || !QueryProcessor.process(defaultSUQuery, ConsistencyLevel.QUORUM).isEmpty() - || !QueryProcessor.process(allUsersQuery, ConsistencyLevel.QUORUM).isEmpty(); + return DatabaseDescriptor.getRoleManager().defaultRoleInitializer().hasExistingRoles(); } protected void scheduleSetupTask(final Callable setupTask) @@ -652,8 +617,8 @@ private void modifyRoleMembership(String grantee, String role, String op) SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, op, - escape(role), - escape(grantee)), + escapeCqlLiteral(role), + escapeCqlLiteral(grantee)), consistencyForRoleWrite(grantee)); } @@ -691,7 +656,7 @@ private void removeAllMembers(String role) throws RequestValidationException, Re UntypedResultSet rows = process(String.format("SELECT member FROM %s.%s WHERE role = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLE_MEMBERS, - escape(role)), + escapeCqlLiteral(role)), consistencyForRoleRead(role)); if (rows.isEmpty()) return; @@ -704,7 +669,7 @@ private void removeAllMembers(String role) throws RequestValidationException, Re process(String.format("DELETE FROM %s.%s WHERE role = '%s'", SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLE_MEMBERS, - escape(role)), + escapeCqlLiteral(role)), consistencyForRoleWrite(role)); } @@ -725,7 +690,7 @@ private String optionsToAssignments(Map options) case SUPERUSER: return String.format("is_superuser = %s", entry.getValue()); case PASSWORD: - return String.format("salted_hash = '%s'", escape(hashpw((String) entry.getValue()))); + return String.format("salted_hash = '%s'", escapeCqlLiteral(hashpw((String) entry.getValue()))); case HASHED_PASSWORD: return String.format("salted_hash = '%s'", (String) entry.getValue()); default: @@ -771,36 +736,11 @@ private void enforcePasswordUpdateRateLimit(AuthenticatedUser performer, String throw new OverloadedException(failure); } - private static String hashpw(String password) - { - return BCrypt.hashpw(password, PasswordSaltSupplier.get()); - } - - private static String escape(String name) - { - return StringUtils.replace(name, "'", "''"); - } - private static ByteBuffer byteBuf(String str) { return UTF8Type.instance.decompose(str); } - /** Allows selective overriding of the consistency level for specific roles. */ - protected static ConsistencyLevel consistencyForRoleWrite(String role) - { - return role.equals(DEFAULT_SUPERUSER_NAME) ? - DEFAULT_SUPERUSER_CONSISTENCY_LEVEL : - CassandraAuthorizer.authWriteConsistencyLevel(); - } - - protected static ConsistencyLevel consistencyForRoleRead(String role) - { - return role.equals(DEFAULT_SUPERUSER_NAME) ? - DEFAULT_SUPERUSER_CONSISTENCY_LEVEL : - CassandraAuthorizer.authReadConsistencyLevel(); - } - /** * Executes the provided query. * This shouldn't be used during setup as this will directly return an error if the manager is not setup yet. Setup tasks diff --git a/src/java/org/apache/cassandra/auth/IDefaultRoleInitializer.java b/src/java/org/apache/cassandra/auth/IDefaultRoleInitializer.java new file mode 100644 index 000000000000..1ed020a7f9da --- /dev/null +++ b/src/java/org/apache/cassandra/auth/IDefaultRoleInitializer.java @@ -0,0 +1,97 @@ +/* + * 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.auth; + +import java.util.Map; +import java.util.Set; + +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.cassandra.exceptions.RequestExecutionException; + +/** + * Creates the initial role on a cluster which has no roles yet, so that there is some + * identity available to authenticate as and grant permissions from. Selected via + * {@code default_role_initializer} option in cassandra.yaml and instantiated by + * {@link AuthConfig#applyAuth()} + *

+ * Implementations decide both what the role is called and how it is authenticated. + * See {@link PasswordDefaultRoleInitializer} which gives the role a password, and + * {@link MutualTlsDefaultRoleInitializer} which gives no password and instead + * maps a client certificate identity to itself. + */ +public interface IDefaultRoleInitializer +{ + /** + * Creates the default role. + * When using this in connection with CassandraRoleManager, every node runs this independently during initial + * startup so implementations must write at {@link CassandraRoleManager#consistencyForRoleWrite(String)} to + * avoid concurrent duplicate creation and must use {@code USING TIMESTAMP 0} so that any operator changes + * to the role later supersede it. + *

+ * The caller retries on failure so this may be invoked more than once on a node: it must not fail + * + * @throws RequestExecutionException if not enough nodes are available + * yet which the caller treats as a signal to reschedule + */ + void createDefaultRole(); + + /** + * The name of the role {@link #createDefaultRole()} creates. + */ + String defaultRoleName(); + + /** + * Validates configuration of the IDefaultRoleInitializer implementation (if configurable). + *

+ * Called by {@link AuthConfig#applyAuth()} after the authenticator, authorizer and role manager have been + * set, so implementations may inspect those to reject combinations which would leave the cluster with no + * usable login. + * + * @throws ConfigurationException when there is a configuration error. + */ + void validateConfiguration() throws ConfigurationException; + + /** + * Checks {@link #hasExistingRoles()} and, if the cluster has none yet, calls {@link #createDefaultRole()}. + * Implemented once, sealed, by {@link AbstractDefaultRoleInitializer} — see that class for the logic. + */ + void initializeDefaultRoleIfNeeded(); + + /** + * @return true if the cluster already has at least one role (or the configured default role specifically). + * Implemented once, sealed, by {@link AbstractDefaultRoleInitializer} — see that class for the logic. + */ + boolean hasExistingRoles(); + + /** + * @param manager manager to check the support of + * @return true if this role initializer conceptually works together with specified role manager, false otherwise + */ + boolean supportsRoleManager(IRoleManager manager); + + static void validateSupportedParams(Map parameters, Set supportedParams, Class implClass) + { + for (String param : parameters.keySet()) + { + if (!supportedParams.contains(param)) + throw new ConfigurationException(String.format("Unsupported parameter '%s' for %s, supported parameters are %s", + param, implClass.getSimpleName(), supportedParams)); + } + } +} diff --git a/src/java/org/apache/cassandra/auth/IRoleManager.java b/src/java/org/apache/cassandra/auth/IRoleManager.java index ef4f816775dd..af3070ceeee3 100644 --- a/src/java/org/apache/cassandra/auth/IRoleManager.java +++ b/src/java/org/apache/cassandra/auth/IRoleManager.java @@ -330,4 +330,8 @@ default void dropIdentity(String identity) } + default IDefaultRoleInitializer defaultRoleInitializer() + { + return PasswordDefaultRoleInitializer.instance; + } } diff --git a/src/java/org/apache/cassandra/auth/MutualTlsDefaultRoleInitializer.java b/src/java/org/apache/cassandra/auth/MutualTlsDefaultRoleInitializer.java new file mode 100644 index 000000000000..9e255da3ee69 --- /dev/null +++ b/src/java/org/apache/cassandra/auth/MutualTlsDefaultRoleInitializer.java @@ -0,0 +1,125 @@ +/* + * 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.auth; + +import java.util.List; +import java.util.Map; +import java.util.Set; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Strings; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.config.DatabaseDescriptor; +import org.apache.cassandra.cql3.QueryProcessor; +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.cassandra.schema.SchemaConstants; + +import static org.apache.cassandra.auth.AuthUtils.consistencyForRoleWrite; +import static org.apache.cassandra.auth.AuthUtils.escapeCqlLiteral; + +public class MutualTlsDefaultRoleInitializer extends AbstractDefaultRoleInitializer +{ + private static final Logger logger = LoggerFactory.getLogger(MutualTlsDefaultRoleInitializer.class); + public static final String ROLE = "role"; + public static final String IDENTITY = "identity"; + + private static final Set SUPPORTED_PARAMS = Set.of(ROLE, IDENTITY); + private final String role; + private final String identity; + + public MutualTlsDefaultRoleInitializer(Map parameters) + { + IDefaultRoleInitializer.validateSupportedParams(parameters, SUPPORTED_PARAMS, getClass()); + role = parameters.get(ROLE); + identity = parameters.get(IDENTITY); + } + + @Override + public boolean supportsRoleManager(IRoleManager manager) + { + return manager instanceof CassandraRoleManager; + } + + @Override + public void createDefaultRole() + { + for (String cql : defaultRoleStatements()) + QueryProcessor.process(cql, consistencyForRoleWrite(role)); + + logger.info("Created passwordless default superuser role '{}' with mapped identity '{}'", role, identity); + } + + /** + * The statements {@link #createDefaultRole()} runs, in execution order. The role row is written LAST because + * {@link #hasExistingRoles()} gates on it: if a write fails after the identity mapping but before the role, the + * retry sees no role, re-runs both idempotent ({@code USING TIMESTAMP 0}) statements and heals the mapping. Were + * the role written first, a failure before the mapping would leave the gate satisfied and the mapping never written. + */ + @VisibleForTesting + List defaultRoleStatements() + { + return List.of(String.format("INSERT INTO %s.%s (identity, role) " + + "VALUES ('%s', '%s') USING TIMESTAMP 0", + SchemaConstants.AUTH_KEYSPACE_NAME, + AuthKeyspace.IDENTITY_TO_ROLES, + escapeCqlLiteral(identity), + escapeCqlLiteral(role)), + String.format("INSERT INTO %s.%s (role, is_superuser, can_login) " + + "VALUES ('%s', true, true) USING TIMESTAMP 0", + SchemaConstants.AUTH_KEYSPACE_NAME, + AuthKeyspace.ROLES, + escapeCqlLiteral(role))); + } + + @Override + public String defaultRoleName() + { + return role; + } + + @Override + public void validateConfiguration() throws ConfigurationException + { + if (Strings.isNullOrEmpty(role)) + throw new ConfigurationException(String.format("%s requires a non-empty '%s' parameter", + getClass().getSimpleName(), ROLE)); + + if (Strings.isNullOrEmpty(identity)) + throw new ConfigurationException(String.format("%s requires a non-empty '%s' parameter", + getClass().getSimpleName(), IDENTITY)); + + // The role this creates has no password, so an authenticator which cannot authenticate by certificate + // would leave a freshly bootstrapped cluster with no way to log in at all. + IAuthenticator authenticator = DatabaseDescriptor.getAuthenticator(); + Set modes = authenticator.getSupportedAuthenticationModes(); + if (authenticator.requireAuthentication() && !modes.isEmpty() && !modes.contains(IAuthenticator.AuthenticationMode.MTLS)) + { + throw new ConfigurationException(String.format("%s creates a role with no password, which %s cannot " + + "authenticate (supported modes: %s). Configure an " + + "authenticator supporting mutual TLS, such as %s.", + getClass().getSimpleName(), + authenticator.getClass().getSimpleName(), + modes, + MutualTlsAuthenticator.class.getSimpleName())); + } + } +} diff --git a/src/java/org/apache/cassandra/auth/PasswordAuthenticator.java b/src/java/org/apache/cassandra/auth/PasswordAuthenticator.java index 9b810f644b8d..cfedbed8e734 100644 --- a/src/java/org/apache/cassandra/auth/PasswordAuthenticator.java +++ b/src/java/org/apache/cassandra/auth/PasswordAuthenticator.java @@ -50,7 +50,7 @@ import org.apache.cassandra.transport.messages.ResultMessage; import org.apache.cassandra.utils.ByteBufferUtil; -import static org.apache.cassandra.auth.CassandraRoleManager.consistencyForRoleRead; +import static org.apache.cassandra.auth.AuthUtils.consistencyForRoleRead; /** * PasswordAuthenticator is an IAuthenticator implementation diff --git a/src/java/org/apache/cassandra/auth/PasswordDefaultRoleInitializer.java b/src/java/org/apache/cassandra/auth/PasswordDefaultRoleInitializer.java new file mode 100644 index 000000000000..5e86ec04a8f1 --- /dev/null +++ b/src/java/org/apache/cassandra/auth/PasswordDefaultRoleInitializer.java @@ -0,0 +1,130 @@ +/* + * 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.auth; + +import java.util.Map; +import java.util.Set; + +import com.google.common.annotations.VisibleForTesting; +import com.google.common.base.Strings; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import org.apache.cassandra.cql3.QueryProcessor; +import org.apache.cassandra.exceptions.ConfigurationException; +import org.apache.cassandra.schema.SchemaConstants; + +import static org.apache.cassandra.auth.AuthUtils.consistencyForRoleWrite; +import static org.apache.cassandra.auth.AuthUtils.escapeCqlLiteral; +import static org.apache.cassandra.auth.AuthUtils.hashpw; + +/** + * Creates the default role with a password, so that it can be authenticated with + * {@link PasswordAuthenticator}. This is the default {@link IDefaultRoleInitializer} and reproduces the + * historical bootstrap behaviour of creating a {@code cassandra} superuser whose password is also + * {@code cassandra}. + *

+ * Because that password is a well known constant, deployments which can authenticate by other means should + * prefer an initializer which does not create a password at all, such as + * {@link MutualTlsDefaultRoleInitializer}. Deployments which do use this initializer should rotate or drop the + * created role before the native transport is reachable. + */ +public class PasswordDefaultRoleInitializer extends AbstractDefaultRoleInitializer +{ + private static final Logger logger = LoggerFactory.getLogger(PasswordDefaultRoleInitializer.class); + + public static final String DEFAULT_SUPERUSER_NAME = "cassandra"; + public static final String DEFAULT_SUPERUSER_PASSWORD = "cassandra"; + @VisibleForTesting + public static final String ROLE = "role"; + @VisibleForTesting + public static final String PASSWORD = "password"; + @VisibleForTesting + public static final String PASSWORD_HASH = "password_hash"; + + private static final Set SUPPORTED_PARAMS = Set.of(ROLE, PASSWORD, PASSWORD_HASH); + + private final String role; + private final String password; + private final String passwordHash; + + public static final PasswordDefaultRoleInitializer instance = new PasswordDefaultRoleInitializer(); + + public PasswordDefaultRoleInitializer() + { + this(Map.of()); + } + + public PasswordDefaultRoleInitializer(Map parameters) + { + IDefaultRoleInitializer.validateSupportedParams(parameters, SUPPORTED_PARAMS, getClass()); + + role = parameters.getOrDefault(ROLE, DEFAULT_SUPERUSER_NAME); + passwordHash = parameters.get(PASSWORD_HASH); + String configuredPassword = parameters.get(PASSWORD); + password = (configuredPassword == null && passwordHash == null) + ? DEFAULT_SUPERUSER_PASSWORD + : configuredPassword; + } + + @Override + public boolean supportsRoleManager(IRoleManager manager) + { + return manager instanceof CassandraRoleManager; + } + + @Override + public void createDefaultRole() + { + QueryProcessor.process(createDefaultRoleQuery(), consistencyForRoleWrite(role)); + logger.info("Created default superuser role '{}'", role); + } + + @Override + public String defaultRoleName() + { + return role; + } + + @Override + public void validateConfiguration() throws ConfigurationException + { + if (Strings.isNullOrEmpty(role)) + throw new ConfigurationException(String.format("%s requires a non-empty %s parameter", getClass().getSimpleName(), ROLE)); + + boolean specifiedPassword = !Strings.isNullOrEmpty(password); + boolean specifiedPasswordHash = !Strings.isNullOrEmpty(passwordHash); + + if (!specifiedPassword && !specifiedPasswordHash) + throw new ConfigurationException(String.format("There has to be one of %s, %s specified.", PASSWORD, PASSWORD_HASH)); + else if (specifiedPassword && specifiedPasswordHash) + throw new ConfigurationException(String.format("Only one of %s, %s can be specified.", PASSWORD, PASSWORD_HASH)); + } + + @VisibleForTesting + public String createDefaultRoleQuery() + { + return String.format("INSERT INTO %s.%s (role, is_superuser, can_login, salted_hash) VALUES ('%s', true, true, '%s') USING TIMESTAMP 0", + SchemaConstants.AUTH_KEYSPACE_NAME, + AuthKeyspace.ROLES, + escapeCqlLiteral(role), + escapeCqlLiteral(password == null ? passwordHash : hashpw(password))); + } +} diff --git a/src/java/org/apache/cassandra/config/Config.java b/src/java/org/apache/cassandra/config/Config.java index 9e0bbab8080b..9c90a0152f6c 100644 --- a/src/java/org/apache/cassandra/config/Config.java +++ b/src/java/org/apache/cassandra/config/Config.java @@ -86,6 +86,7 @@ public static Set splitCommaDelimited(String src) public ParameterizedClass authenticator; public ParameterizedClass authorizer; public ParameterizedClass role_manager; + public ParameterizedClass default_role_initializer; public ParameterizedClass crypto_provider; public ParameterizedClass network_authorizer; public ParameterizedClass cidr_authorizer; diff --git a/src/java/org/apache/cassandra/config/DatabaseDescriptor.java b/src/java/org/apache/cassandra/config/DatabaseDescriptor.java index 6bd66bd49910..67b9cf319381 100644 --- a/src/java/org/apache/cassandra/config/DatabaseDescriptor.java +++ b/src/java/org/apache/cassandra/config/DatabaseDescriptor.java @@ -77,6 +77,7 @@ import org.apache.cassandra.auth.IAuthenticator; import org.apache.cassandra.auth.IAuthorizer; import org.apache.cassandra.auth.ICIDRAuthorizer; +import org.apache.cassandra.auth.IDefaultRoleInitializer; import org.apache.cassandra.auth.IInternodeAuthenticator; import org.apache.cassandra.auth.INetworkAuthorizer; import org.apache.cassandra.auth.IRoleManager; @@ -239,6 +240,7 @@ public class DatabaseDescriptor // Don't initialize the role manager until applying config. The options supported by CassandraRoleManager // depend on the configured IAuthenticator, so defer creating it until that's been set. private static IRoleManager roleManager; + private static IDefaultRoleInitializer defaultRoleInitializer; private static long preparedStatementsCacheSizeInMiB; @@ -2210,6 +2212,16 @@ public static void setRoleManager(IRoleManager roleManager) DatabaseDescriptor.roleManager = roleManager; } + public static IDefaultRoleInitializer getDefaultRoleInitializer() + { + return defaultRoleInitializer; + } + + public static void setDefaultRoleInitializer(IDefaultRoleInitializer defaultRoleInitializer) + { + DatabaseDescriptor.defaultRoleInitializer = defaultRoleInitializer; + } + public static int getPermissionsValidity() { return conf.permissions_validity.toMilliseconds(); diff --git a/src/java/org/apache/cassandra/config/ParameterizedClass.java b/src/java/org/apache/cassandra/config/ParameterizedClass.java index 803fcb1fac18..ea7258c2a09f 100644 --- a/src/java/org/apache/cassandra/config/ParameterizedClass.java +++ b/src/java/org/apache/cassandra/config/ParameterizedClass.java @@ -22,6 +22,8 @@ import java.util.Collections; import java.util.List; import java.util.Map; +import java.util.Map.Entry; +import java.util.TreeMap; import java.util.function.Predicate; import java.util.stream.Collectors; @@ -30,6 +32,7 @@ import org.apache.cassandra.exceptions.ConfigurationException; import org.apache.cassandra.utils.Shared; +import static org.apache.cassandra.utils.LocalizeString.toLowerCaseLocalized; import static org.apache.cassandra.utils.Shared.Scope.SIMULATION; @Shared(scope = SIMULATION) @@ -168,6 +171,23 @@ public int hashCode() @Override public String toString() { - return class_name + parameters; + if (parameters == null) + { + return class_name + "{}"; + } + else + { + Map sanitizedMap = new TreeMap<>(); + for (Entry entry : parameters.entrySet()) + sanitizedMap.put(entry.getKey(), isSensitive(entry.getKey()) ? "" : entry.getValue()); + return class_name + sanitizedMap; + } + } + + protected boolean isSensitive(String key) + { + String lowerCaseKey = toLowerCaseLocalized(key); + return lowerCaseKey.contains("password") + || lowerCaseKey.contains("hash"); } } diff --git a/src/java/org/apache/cassandra/tools/HashPassword.java b/src/java/org/apache/cassandra/tools/HashPassword.java index 68a13d603c94..ff8c41860e6b 100644 --- a/src/java/org/apache/cassandra/tools/HashPassword.java +++ b/src/java/org/apache/cassandra/tools/HashPassword.java @@ -31,11 +31,12 @@ import org.apache.commons.cli.OptionGroup; import org.apache.commons.cli.Options; import org.apache.commons.cli.ParseException; -import org.apache.commons.lang3.StringUtils; import org.mindrot.jbcrypt.BCrypt; import org.apache.cassandra.io.util.File; +import static org.apache.cassandra.auth.AuthUtils.escapeCqlLiteral; + public class HashPassword { private static final String LOGROUNDS_OPTION = "logrounds"; @@ -131,7 +132,7 @@ else if (cmd.hasOption(INPUT)) "(bcrypt) can only compare up to 72 bytes. The password will be accepted and work, but only compared up to 72 bytes.", password.getBytes().length)); - String hashed = escape(hashpw(password, logRounds)); + String hashed = escapeCqlLiteral(hashpw(password, logRounds)); System.out.print(hashed); System.out.flush(); } @@ -180,11 +181,6 @@ private static String hashpw(String password, int rounds) return BCrypt.hashpw(password, BCrypt.gensalt(rounds)); } - private static String escape(String name) - { - return StringUtils.replace(name, "'", "''"); - } - public static void printUsage(Options options) { String usage = "hash_password [options]"; diff --git a/test/distributed/org/apache/cassandra/distributed/test/ColumnMaskTest.java b/test/distributed/org/apache/cassandra/distributed/test/ColumnMaskTest.java index c07e08a46cdf..fb99ccbacf46 100644 --- a/test/distributed/org/apache/cassandra/distributed/test/ColumnMaskTest.java +++ b/test/distributed/org/apache/cassandra/distributed/test/ColumnMaskTest.java @@ -39,8 +39,8 @@ import static com.datastax.driver.core.Cluster.Builder; import static java.lang.String.format; -import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME; -import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD; +import static org.apache.cassandra.auth.PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME; +import static org.apache.cassandra.auth.PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_PASSWORD; import static org.apache.cassandra.distributed.api.Feature.GOSSIP; import static org.apache.cassandra.distributed.api.Feature.NATIVE_PROTOCOL; import static org.apache.cassandra.distributed.shared.AssertUtils.assertRows; diff --git a/test/distributed/org/apache/cassandra/distributed/test/auth/AuthAuditLoggingTest.java b/test/distributed/org/apache/cassandra/distributed/test/auth/AuthAuditLoggingTest.java index 8b7d82197408..578b562c8647 100644 --- a/test/distributed/org/apache/cassandra/distributed/test/auth/AuthAuditLoggingTest.java +++ b/test/distributed/org/apache/cassandra/distributed/test/auth/AuthAuditLoggingTest.java @@ -52,8 +52,8 @@ import static org.apache.cassandra.audit.AuditLogEntryType.LOGIN_ERROR; import static org.apache.cassandra.audit.AuditLogEntryType.LOGIN_SUCCESS; -import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME; -import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD; +import static org.apache.cassandra.auth.PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME; +import static org.apache.cassandra.auth.PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_PASSWORD; import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD; import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD; import static org.apache.cassandra.transport.TlsTestUtils.configureIdentity; diff --git a/test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java b/test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java index 3cccccf135b6..277a755932ee 100644 --- a/test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java +++ b/test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsCertificateValidityPeriodTest.java @@ -57,7 +57,6 @@ import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_SPIFFE_IDENTITY; import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD; import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD; -import static org.apache.cassandra.transport.TlsTestUtils.configureIdentity; import static org.apache.cassandra.transport.TlsTestUtils.generateClientCertificate; import static org.apache.cassandra.transport.TlsTestUtils.getSSLOptions; import static org.assertj.core.api.Assertions.as; @@ -104,6 +103,8 @@ public static void setupClass() throws Exception .set("authenticator.parameters", Collections.singletonMap("validator_class_name", "org.apache.cassandra.auth.SpiffeCertificateValidator")) .set("role_manager", "CassandraRoleManager") .set("authorizer", "CassandraAuthorizer") + .set("default_role_initializer.class_name", "org.apache.cassandra.auth.MutualTlsDefaultRoleInitializer") + .set("default_role_initializer.parameters", Map.of("role", "cassandra_ssl_test", "identity", CLIENT_SPIFFE_IDENTITY)) .set("client_encryption_options.enabled", "true") .set("client_encryption_options.require_client_auth", "optional") .set("client_encryption_options.keystore", serverKeystorePath.toString()) @@ -115,8 +116,6 @@ public static void setupClass() throws Exception .set("client_encryption_options.certificate_validity_warn_threshold", "5d") .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP)); CLUSTER = builder.start(); - - configureIdentity(CLUSTER, getSSLOptions(null, truststorePath)); } @AfterClass diff --git a/test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsDefaultRoleInitializerTest.java b/test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsDefaultRoleInitializerTest.java new file mode 100644 index 000000000000..de341cfb031a --- /dev/null +++ b/test/distributed/org/apache/cassandra/distributed/test/auth/MutualTlsDefaultRoleInitializerTest.java @@ -0,0 +1,177 @@ +/* + * 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.distributed.test.auth; + +import java.net.InetAddress; +import java.nio.file.Path; +import java.util.Collections; +import java.util.Map; + +import com.datastax.driver.core.Session; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.ClassRule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; + +import org.apache.cassandra.auth.AuthKeyspace; +import org.apache.cassandra.cql3.QueryProcessor; +import org.apache.cassandra.cql3.UntypedResultSet; +import org.apache.cassandra.distributed.Cluster; +import org.apache.cassandra.distributed.api.Feature; +import org.apache.cassandra.distributed.api.ICluster; +import org.apache.cassandra.distributed.api.IInvokableInstance; +import org.apache.cassandra.distributed.api.IIsolatedExecutor.SerializableCallable; +import org.apache.cassandra.distributed.test.JavaDriverUtils; +import org.apache.cassandra.distributed.test.TestBaseImpl; +import org.apache.cassandra.schema.SchemaConstants; +import org.apache.cassandra.utils.tls.CertificateBuilder; +import org.apache.cassandra.utils.tls.CertificateBundle; + +import static org.apache.cassandra.transport.TlsTestUtils.CLIENT_SPIFFE_IDENTITY; +import static org.apache.cassandra.transport.TlsTestUtils.SERVER_KEYSTORE_PASSWORD; +import static org.apache.cassandra.transport.TlsTestUtils.SERVER_TRUSTSTORE_PASSWORD; +import static org.apache.cassandra.transport.TlsTestUtils.generateClientCertificate; +import static org.apache.cassandra.transport.TlsTestUtils.getSSLOptions; +import static org.apache.cassandra.transport.TlsTestUtils.withAuthenticatedSession; +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Verifies that {@code default_role_initializer: MutualTlsDefaultRoleInitializer} bootstraps a passwordless + * superuser role and its identity mapping without any post-startup CQL step, that a client presenting a + * matching certificate can authenticate as that role with superuser access, and that password authentication + * against the same role fails cleanly since it has no {@code salted_hash}. + */ +public class MutualTlsDefaultRoleInitializerTest extends TestBaseImpl +{ + private static final String TEST_ROLE = "cassandra_mtls_bootstrap_test_role"; + + @ClassRule + public static TemporaryFolder tempFolder = new TemporaryFolder(); + + private static ICluster CLUSTER; + private static CertificateBundle CA; + private static Path truststorePath; + private static Path clientKeystorePath; + + @BeforeClass + public static void setupClass() throws Exception + { + Cluster.Builder builder = Cluster.build(1).withDynamicPortAllocation(true); + + CA = new CertificateBuilder().subject("CN=Apache Cassandra Root CA, OU=Certification Authority, O=Unknown, C=Unknown") + .alias("fakerootca") + .isCertificateAuthority(true) + .buildSelfSigned(); + + truststorePath = CA.toTempKeyStorePath(tempFolder.getRoot().toPath(), + SERVER_TRUSTSTORE_PASSWORD.toCharArray(), + SERVER_TRUSTSTORE_PASSWORD.toCharArray()); + + CertificateBundle serverKeystore = new CertificateBuilder().subject("CN=Apache Cassandra, OU=ssl_test, O=Unknown, L=Unknown, ST=Unknown, C=Unknown") + .addSanDnsName(InetAddress.getLocalHost().getCanonicalHostName()) + .addSanDnsName(InetAddress.getLocalHost().getHostName()) + .buildIssuedBy(CA); + + Path serverKeystorePath = serverKeystore.toTempKeyStorePath(tempFolder.getRoot().toPath(), + SERVER_KEYSTORE_PASSWORD.toCharArray(), + SERVER_KEYSTORE_PASSWORD.toCharArray()); + + builder.withConfig(c -> c.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("default_role_initializer.class_name", "org.apache.cassandra.auth.MutualTlsDefaultRoleInitializer") + .set("default_role_initializer.parameters", Map.of("role", TEST_ROLE, "identity", CLIENT_SPIFFE_IDENTITY)) + .set("client_encryption_options.enabled", "true") + .set("client_encryption_options.require_client_auth", "optional") + .set("client_encryption_options.keystore", serverKeystorePath.toString()) + .set("client_encryption_options.keystore_password", SERVER_KEYSTORE_PASSWORD) + .set("client_encryption_options.truststore", truststorePath.toString()) + .set("client_encryption_options.truststore_password", SERVER_TRUSTSTORE_PASSWORD) + .set("client_encryption_options.require_endpoint_verification", "false") + .with(Feature.NATIVE_PROTOCOL, Feature.GOSSIP, Feature.NETWORK)); + CLUSTER = builder.start(); + + clientKeystorePath = generateClientCertificate(null, tempFolder.getRoot(), CA); + } + + @AfterClass + public static void teardown() throws Exception + { + if (CLUSTER != null) + CLUSTER.close(); + } + + @Test + public void testDefaultRoleAndIdentityCreatedAtBootstrap() + { + String identity = CLIENT_SPIFFE_IDENTITY; + + Object[] roleRow = CLUSTER.get(1).callOnInstance((SerializableCallable) () -> { + UntypedResultSet result = QueryProcessor.executeInternal( + String.format("SELECT is_superuser, can_login, salted_hash FROM %s.%s WHERE role = '%s'", + SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, TEST_ROLE)); + Assert.assertNotNull(result); + if (result.isEmpty()) + return null; + UntypedResultSet.Row row = result.one(); + return new Object[]{ row.getBoolean("is_superuser"), row.getBoolean("can_login"), row.has("salted_hash") }; + }); + + assertThat(roleRow).isNotNull(); + assertThat((Boolean) roleRow[0]).as("is_superuser").isTrue(); + assertThat((Boolean) roleRow[1]).as("can_login").isTrue(); + assertThat((Boolean) roleRow[2]).as("has salted_hash").isFalse(); + + String mappedRole = CLUSTER.get(1).callOnInstance((SerializableCallable) () -> { + UntypedResultSet result = QueryProcessor.executeInternal( + String.format("SELECT role FROM %s.%s WHERE identity = '%s'", + SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.IDENTITY_TO_ROLES, identity)); + Assert.assertNotNull(result); + return result.isEmpty() ? null : result.one().getString("role"); + }); + + assertThat(mappedRole).isEqualTo(TEST_ROLE); + } + + @Test + public void testCertificateAuthenticationGrantsSuperuser() throws Exception + { + try (com.datastax.driver.core.Cluster c = JavaDriverUtils.create(CLUSTER, null, b -> b.withSSL(getSSLOptions(clientKeystorePath, truststorePath))); + Session session = c.connect()) + { + // system_auth.roles is a protected resource (CassandraRoleManager#protectedResources); reading it + // without ever being granted SELECT proves this connection authenticated with superuser status. + com.datastax.driver.core.ResultSet rows = session.execute("SELECT role FROM system_auth.roles WHERE role = ?", TEST_ROLE); + assertThat(rows.one().getString("role")).isEqualTo(TEST_ROLE); + } + } + + @Test + public void testPasswordAuthenticationFailsCleanly() throws Exception + { + assertThatThrownBy(() -> withAuthenticatedSession(CLUSTER.get(1), TEST_ROLE, "irrelevant-password", session -> { + }, getSSLOptions(null, truststorePath))) + .isInstanceOf(com.datastax.driver.core.exceptions.AuthenticationException.class); + } +} diff --git a/test/distributed/org/apache/cassandra/distributed/test/auth/PasswordDefaultRoleInitializerTest.java b/test/distributed/org/apache/cassandra/distributed/test/auth/PasswordDefaultRoleInitializerTest.java new file mode 100644 index 000000000000..bed3156052b5 --- /dev/null +++ b/test/distributed/org/apache/cassandra/distributed/test/auth/PasswordDefaultRoleInitializerTest.java @@ -0,0 +1,123 @@ +/* + * 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.distributed.test.auth; + +import java.net.InetAddress; +import java.util.function.Consumer; + +import com.datastax.driver.core.Cluster.Builder; +import com.datastax.driver.core.Session; +import com.datastax.driver.core.policies.LoadBalancingPolicy; + +import org.junit.AfterClass; +import org.junit.Assert; +import org.junit.BeforeClass; +import org.junit.Test; + +import org.apache.cassandra.auth.AuthKeyspace; +import org.apache.cassandra.cql3.QueryProcessor; +import org.apache.cassandra.cql3.UntypedResultSet; +import org.apache.cassandra.distributed.Cluster; +import org.apache.cassandra.distributed.api.Feature; +import org.apache.cassandra.distributed.api.ICluster; +import org.apache.cassandra.distributed.api.IInvokableInstance; +import org.apache.cassandra.distributed.api.IIsolatedExecutor.SerializableCallable; +import org.apache.cassandra.distributed.test.TestBaseImpl; +import org.apache.cassandra.distributed.util.Auth; +import org.apache.cassandra.distributed.util.SingleHostLoadBalancingPolicy; +import org.apache.cassandra.schema.SchemaConstants; + +import static org.apache.cassandra.auth.PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME; +import static org.apache.cassandra.auth.PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_PASSWORD; +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Regression test for the {@code default_role_initializer} refactor (see {@link org.apache.cassandra.auth.IDefaultRoleInitializer}): + * when the option is left unconfigured, bootstrap must still fall back to {@link org.apache.cassandra.auth.PasswordDefaultRoleInitializer} + * and create the classic {@code cassandra}/{@code cassandra} superuser exactly as it always has, so deployments and + * tests that rely on the historical default (e.g. {@code CQLTester}) keep working unchanged. + */ +public class PasswordDefaultRoleInitializerTest extends TestBaseImpl +{ + private static ICluster CLUSTER; + + @BeforeClass + public static void setupClass() throws Exception + { + CLUSTER = Cluster.build(1) + .withConfig(conf -> conf.with(Feature.GOSSIP, Feature.NATIVE_PROTOCOL) + .set("authenticator", "PasswordAuthenticator") + .set("authorizer", "CassandraAuthorizer") + .set("role_manager", "CassandraRoleManager")) + .start(); + } + + @AfterClass + public static void teardown() throws Exception + { + if (CLUSTER != null) + CLUSTER.close(); + } + + @Test + public void testClassicSuperuserBootstrappedByDefault() + { + Object[] roleRow = CLUSTER.get(1).callOnInstance((SerializableCallable) () -> { + UntypedResultSet result = QueryProcessor.executeInternal( + String.format("SELECT is_superuser, can_login, salted_hash FROM %s.%s WHERE role = '%s'", + SchemaConstants.AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, DEFAULT_SUPERUSER_NAME)); + Assert.assertNotNull(result); + if (result.isEmpty()) + return null; + UntypedResultSet.Row row = result.one(); + return new Object[]{ row.getBoolean("is_superuser"), row.getBoolean("can_login"), row.has("salted_hash") }; + }); + + assertThat(roleRow).isNotNull(); + assertThat((Boolean) roleRow[0]).as("is_superuser").isTrue(); + assertThat((Boolean) roleRow[1]).as("can_login").isTrue(); + assertThat((Boolean) roleRow[2]).as("has salted_hash").isTrue(); + + // and the credential actually works end-to-end, not just the raw row contents + withAuthenticatedSession(CLUSTER.get(1), DEFAULT_SUPERUSER_NAME, DEFAULT_SUPERUSER_PASSWORD, session -> { + com.datastax.driver.core.ResultSet rows = session.execute("SELECT role FROM system_auth.roles WHERE role = ?", DEFAULT_SUPERUSER_NAME); + assertThat(rows.one().getString("role")).isEqualTo(DEFAULT_SUPERUSER_NAME); + }); + } + + // No client_encryption_options are configured for this cluster, so unlike TlsTestUtils#withAuthenticatedSession + // (which always requires SSLOptions) this connects in plaintext, matching ColumnMaskTest's local helper. + private static void withAuthenticatedSession(IInvokableInstance instance, String username, String password, Consumer consumer) + { + Auth.waitForExistingRoles(instance); + + InetAddress address = instance.broadcastAddress().getAddress(); + LoadBalancingPolicy lbc = new SingleHostLoadBalancingPolicy(address); + + Builder builder = com.datastax.driver.core.Cluster.builder() + .addContactPoints(address) + .withLoadBalancingPolicy(lbc) + .withCredentials(username, password); + + try (com.datastax.driver.core.Cluster cluster = builder.build(); Session session = cluster.connect()) + { + consumer.accept(session); + } + } +} diff --git a/test/unit/org/apache/cassandra/auth/AllowAllCIDRAuthorizerTest.java b/test/unit/org/apache/cassandra/auth/AllowAllCIDRAuthorizerTest.java index 467b70e3a035..6bbf6eaa49ea 100644 --- a/test/unit/org/apache/cassandra/auth/AllowAllCIDRAuthorizerTest.java +++ b/test/unit/org/apache/cassandra/auth/AllowAllCIDRAuthorizerTest.java @@ -81,7 +81,7 @@ private void testAccessSucceeds(String userName, String ip) @Test public void testSuperUser() { - testAccessSucceeds(CassandraRoleManager.DEFAULT_SUPERUSER_NAME, "10.20.30.5"); + testAccessSucceeds(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "10.20.30.5"); } @Test diff --git a/test/unit/org/apache/cassandra/auth/AuthConfigTest.java b/test/unit/org/apache/cassandra/auth/AuthConfigTest.java index 90c10d16cf5b..e674b8f88bc3 100644 --- a/test/unit/org/apache/cassandra/auth/AuthConfigTest.java +++ b/test/unit/org/apache/cassandra/auth/AuthConfigTest.java @@ -23,6 +23,7 @@ import java.security.cert.CertificateException; import java.util.Arrays; import java.util.Collections; +import java.util.Map; import org.junit.After; import org.junit.Before; @@ -164,6 +165,70 @@ public void testNewInstanceForMutualTlsAuthenticator() assertTrue(DatabaseDescriptor.getRoleManager().alterableOptions().containsAll(authenticator.getAlterableRoleOptions())); } + private static ParameterizedClass mutualTlsDefaultRoleInitializer() + { + return new ParameterizedClass(MutualTlsDefaultRoleInitializer.class.getName(), + Map.of(MutualTlsDefaultRoleInitializer.ROLE, "cassandra", + MutualTlsDefaultRoleInitializer.IDENTITY, "spiffe1")); + } + + @Test + public void testNewInstanceForMutualTlsDefaultRoleInitializer() + { + Config config = load("cassandra-mtls.yaml"); + config.default_role_initializer = mutualTlsDefaultRoleInitializer(); + DatabaseDescriptor.unsafeDaemonInitialization(()->config); + + assertThat(DatabaseDescriptor.getRoleManager().defaultRoleInitializer()).isInstanceOf(MutualTlsDefaultRoleInitializer.class); + assertThat(DatabaseDescriptor.getRoleManager().defaultRoleInitializer().defaultRoleName()).isEqualTo("cassandra"); + } + + @Test + public void testMutualTlsDefaultRoleInitializerRejectedWithIncompatibleAuthenticator() + { + Config config = load("cassandra-passwordauth.yaml"); + config.default_role_initializer = mutualTlsDefaultRoleInitializer(); + assertThatThrownBy(() -> DatabaseDescriptor.unsafeDaemonInitialization(()->config)) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("creates a role with no password"); + } + + @Test + public void testDefaultRoleInitializerSupportEnforcedOnlyWhenExplicitlyConfigured() + { + baseConfig(); + IRoleManager roleManager = DatabaseDescriptor.getRoleManager(); + assertNotNull(roleManager); + ParameterizedClass configured = new ParameterizedClass("SomeInitializer", Collections.emptyMap()); + + // Explicitly configured + unsupported role manager -> rejected (the guard is still active). + assertThatThrownBy(() -> AuthConfig.validateDefaultRoleInitializerSupportsRoleManager(configured, new FixedSupportInitializer(false), roleManager)) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("does not support"); + + AuthConfig.validateDefaultRoleInitializerSupportsRoleManager(null, new FixedSupportInitializer(false), roleManager); + + AuthConfig.validateDefaultRoleInitializerSupportsRoleManager(configured, new FixedSupportInitializer(true), roleManager); + } + + /** IDefaultRoleInitializer whose role-manager support is fixed at construction, for exercising the guard. */ + private static class FixedSupportInitializer implements IDefaultRoleInitializer + { + private final boolean supports; + + FixedSupportInitializer(boolean supports) + { + this.supports = supports; + } + + public void createDefaultRole() {} + public String defaultRoleName() { return "test"; } + public void validateConfiguration() {} + public void initializeDefaultRoleIfNeeded() {} + public boolean hasExistingRoles() { return false; } + public boolean supportsRoleManager(IRoleManager manager) { return supports; } + } + private static final String PROBE = ClassLoadingTestNonAssignable.class.getName(); private static Config baseConfig() diff --git a/test/unit/org/apache/cassandra/auth/AuthTestUtils.java b/test/unit/org/apache/cassandra/auth/AuthTestUtils.java index d17d39ec4e09..03972963d36d 100644 --- a/test/unit/org/apache/cassandra/auth/AuthTestUtils.java +++ b/test/unit/org/apache/cassandra/auth/AuthTestUtils.java @@ -321,7 +321,7 @@ public static ClientState getClientState(String role) public static ClientState getClientState() { - return getClientState(CassandraRoleManager.DEFAULT_SUPERUSER_NAME); + return getClientState(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME); } public static AuthenticationStatement authWithoutInvalidate(String query, ClientState clientState, Object... args) @@ -467,6 +467,6 @@ static String createName() public static void setupSuperUser() { QueryProcessor.executeInternal(String.format("INSERT INTO %s.%s (role, is_superuser, can_login, salted_hash) VALUES ('%s', true, true, '%s')", - AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, CassandraRoleManager.DEFAULT_SUPERUSER_NAME, "xxx")); + AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "xxx")); } } diff --git a/test/unit/org/apache/cassandra/auth/AuthUtilsTest.java b/test/unit/org/apache/cassandra/auth/AuthUtilsTest.java new file mode 100644 index 000000000000..26ec25c1d58e --- /dev/null +++ b/test/unit/org/apache/cassandra/auth/AuthUtilsTest.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.auth; + +import org.junit.Test; +import org.mindrot.jbcrypt.BCrypt; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * Unit tests for the pure helpers in {@link AuthUtils} + */ +public class AuthUtilsTest +{ + @Test + public void escapeCqlLiteralLeavesValuesWithoutQuotesUnchanged() + { + assertThat(AuthUtils.escapeCqlLiteral("cassandra")).isEqualTo("cassandra"); + assertThat(AuthUtils.escapeCqlLiteral("")).isEqualTo(""); + assertThat(AuthUtils.escapeCqlLiteral("role_with-various.chars")).isEqualTo("role_with-various.chars"); + } + + @Test + public void escapeCqlLiteralDoublesSingleQuotes() + { + assertThat(AuthUtils.escapeCqlLiteral("o'brien")).isEqualTo("o''brien"); + } + + @Test + public void escapeCqlLiteralDoublesEveryQuote() + { + assertThat(AuthUtils.escapeCqlLiteral("'")).isEqualTo("''"); + assertThat(AuthUtils.escapeCqlLiteral("''")).isEqualTo("''''"); + assertThat(AuthUtils.escapeCqlLiteral("a'b'c")).isEqualTo("a''b''c"); + assertThat(AuthUtils.escapeCqlLiteral("'lead")).isEqualTo("''lead"); + assertThat(AuthUtils.escapeCqlLiteral("trail'")).isEqualTo("trail''"); + } + + @Test + public void escapeCqlLiteralNeutralisesInjectionAttempt() + { + String malicious = "x'; DROP KEYSPACE system_auth; --"; + assertThat(AuthUtils.escapeCqlLiteral(malicious)).isEqualTo("x''; DROP KEYSPACE system_auth; --"); + } + + @Test + public void escapeCqlLiteralReturnsNullUnchanged() + { + assertThat(AuthUtils.escapeCqlLiteral(null)).isNull(); + } + + @Test + public void hashpwProducesVerifiableBcryptHash() + { + String hash = AuthUtils.hashpw("cassandra"); + assertThat(hash).startsWith("$2a$"); + assertThat(BCrypt.checkpw("cassandra", hash)).isTrue(); + assertThat(BCrypt.checkpw("wrong", hash)).isFalse(); + } + + @Test + public void hashpwIsSaltedSoRepeatedHashesDiffer() + { + assertThat(AuthUtils.hashpw("cassandra")).isNotEqualTo(AuthUtils.hashpw("cassandra")); + } +} diff --git a/test/unit/org/apache/cassandra/auth/CassandraCIDRAuthorizerEnforceModeTest.java b/test/unit/org/apache/cassandra/auth/CassandraCIDRAuthorizerEnforceModeTest.java index 0cbb15670a6f..c25ac157a6b7 100644 --- a/test/unit/org/apache/cassandra/auth/CassandraCIDRAuthorizerEnforceModeTest.java +++ b/test/unit/org/apache/cassandra/auth/CassandraCIDRAuthorizerEnforceModeTest.java @@ -175,7 +175,7 @@ public void testNonexistingCidrLogin() @Test public void testSuperUserAccess() { - testValidCidrAccess(CassandraRoleManager.DEFAULT_SUPERUSER_NAME, "255.255.255.255"); + testValidCidrAccess(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "255.255.255.255"); } @Test @@ -293,8 +293,8 @@ public void testInvalidCidrs() @Test public void testCidrChecksForSuperUsers() { - testValidCidrAccess(CassandraRoleManager.DEFAULT_SUPERUSER_NAME, "10.20.30.5"); - testValidCidrAccess(CassandraRoleManager.DEFAULT_SUPERUSER_NAME, "200.30.40.60"); + testValidCidrAccess(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "10.20.30.5"); + testValidCidrAccess(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "200.30.40.60"); Config conf = DatabaseDescriptor.getRawConfig(); conf.cidr_authorizer = new ParameterizedClass(CassandraCIDRAuthorizer.class.getName(), new HashMap<>()); @@ -304,10 +304,10 @@ public void testCidrChecksForSuperUsers() Collections.singletonList( CIDR.getInstance("200.30.40.60/24")))); AuthTestUtils.auth("alter role %s with access from cidrs {'cidrGroup1'}", - CassandraRoleManager.DEFAULT_SUPERUSER_NAME); + PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME); cidrAuthorizer.getCidrPermissionsCache().invalidate(); - testInvalidCidrAccess(CassandraRoleManager.DEFAULT_SUPERUSER_NAME, "10.20.30.5"); - testValidCidrAccess(CassandraRoleManager.DEFAULT_SUPERUSER_NAME, "200.30.40.60"); + testInvalidCidrAccess(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "10.20.30.5"); + testValidCidrAccess(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "200.30.40.60"); } } diff --git a/test/unit/org/apache/cassandra/auth/CassandraCIDRAuthorizerMonitorModeTest.java b/test/unit/org/apache/cassandra/auth/CassandraCIDRAuthorizerMonitorModeTest.java index b9225b519861..44ae6b48b419 100644 --- a/test/unit/org/apache/cassandra/auth/CassandraCIDRAuthorizerMonitorModeTest.java +++ b/test/unit/org/apache/cassandra/auth/CassandraCIDRAuthorizerMonitorModeTest.java @@ -106,8 +106,8 @@ public void testNonexistingCidrLogin() @Test public void testCidrChecksForSuperUsers() { - testValidCidrAccess(CassandraRoleManager.DEFAULT_SUPERUSER_NAME, "10.20.30.5"); - testValidCidrAccess(CassandraRoleManager.DEFAULT_SUPERUSER_NAME, "200.30.40.60"); + testValidCidrAccess(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "10.20.30.5"); + testValidCidrAccess(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "200.30.40.60"); Config conf = DatabaseDescriptor.getRawConfig(); conf.cidr_authorizer = new ParameterizedClass(CassandraCIDRAuthorizer.class.getName(), new HashMap<>()); @@ -117,10 +117,10 @@ public void testCidrChecksForSuperUsers() Collections.singletonList( CIDR.getInstance("200.30.40.60/24")))); AuthTestUtils.auth("alter role %s with access from cidrs {'cidrGroup1'}", - CassandraRoleManager.DEFAULT_SUPERUSER_NAME); + PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME); cidrAuthorizer.getCidrPermissionsCache().invalidate(); - testValidCidrAccess(CassandraRoleManager.DEFAULT_SUPERUSER_NAME, "10.20.30.5"); - testValidCidrAccess(CassandraRoleManager.DEFAULT_SUPERUSER_NAME, "200.30.40.60"); + testValidCidrAccess(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "10.20.30.5"); + testValidCidrAccess(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "200.30.40.60"); } } diff --git a/test/unit/org/apache/cassandra/auth/DefaultRoleInitializerTest.java b/test/unit/org/apache/cassandra/auth/DefaultRoleInitializerTest.java new file mode 100644 index 000000000000..291b71f231c2 --- /dev/null +++ b/test/unit/org/apache/cassandra/auth/DefaultRoleInitializerTest.java @@ -0,0 +1,138 @@ +/* + * 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.auth; + +import java.util.Collections; +import java.util.List; +import java.util.Map; + +import org.junit.Test; + +import org.apache.cassandra.exceptions.ConfigurationException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.assertThatThrownBy; + +/** + * Unit tests for {@link PasswordDefaultRoleInitializer} and {@link MutualTlsDefaultRoleInitializer} that don't + * require a running node: unsupported-parameter rejection at construction time, and the parameter-presence checks + * in {@link IDefaultRoleInitializer#validateConfiguration()}. The authenticator-compatibility half of + * {@link MutualTlsDefaultRoleInitializer#validateConfiguration()} needs a configured {@code DatabaseDescriptor} + * authenticator and is covered by {@link AuthConfigTest} instead. + */ +public class DefaultRoleInitializerTest +{ + @Test + public void passwordInitializerRejectsUnsupportedParameter() + { + assertThatThrownBy(() -> new PasswordDefaultRoleInitializer(Map.of("bogus", "x"))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unsupported parameter"); + } + + @Test + public void passwordInitializerDefaultsPassValidation() + { + new PasswordDefaultRoleInitializer().validateConfiguration(); + new PasswordDefaultRoleInitializer(Collections.emptyMap()).validateConfiguration(); + } + + @Test + public void passwordInitializerRejectsEmptyRole() + { + assertThatThrownBy(() -> new PasswordDefaultRoleInitializer(Map.of("role", "", "password", "x")).validateConfiguration()) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("role"); + } + + @Test + public void passwordInitializerRejectsEmptyPassword() + { + assertThatThrownBy(() -> new PasswordDefaultRoleInitializer(Map.of("role", "cassandra", "password", "")).validateConfiguration()) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("password"); + } + + @Test + public void passwordInitializerRejectsBothPasswordAndHash() + { + assertThatThrownBy(() -> new PasswordDefaultRoleInitializer(Map.of("password", "x", "password_hash", "$2a$04$abc")).validateConfiguration()) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Only one of password, password_hash can be specified."); + } + + @Test + public void passwordInitializerDefaultRoleNameMatchesConfiguredRole() + { + PasswordDefaultRoleInitializer initializer = new PasswordDefaultRoleInitializer(Map.of("role", "myrole", "password", "x")); + assertThat(initializer.defaultRoleName()).isEqualTo("myrole"); + } + + @Test + public void mutualTlsInitializerRejectsUnsupportedParameter() + { + assertThatThrownBy(() -> new MutualTlsDefaultRoleInitializer(Map.of("bogus", "x"))) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("Unsupported parameter"); + } + + @Test + public void mutualTlsInitializerRejectsMissingRole() + { + assertThatThrownBy(() -> new MutualTlsDefaultRoleInitializer(Map.of("identity", "spiffe1")).validateConfiguration()) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("role"); + } + + @Test + public void mutualTlsInitializerRejectsMissingIdentity() + { + assertThatThrownBy(() -> new MutualTlsDefaultRoleInitializer(Map.of("role", "cassandra")).validateConfiguration()) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("identity"); + } + + @Test + public void mutualTlsInitializerRejectsEmptyRoleAndIdentity() + { + assertThatThrownBy(() -> new MutualTlsDefaultRoleInitializer(Map.of("role", "", "identity", "")).validateConfiguration()) + .isInstanceOf(ConfigurationException.class) + .hasMessageContaining("role"); + } + + @Test + public void mutualTlsInitializerDefaultRoleNameMatchesConfiguredRole() + { + MutualTlsDefaultRoleInitializer initializer = new MutualTlsDefaultRoleInitializer(Map.of("role", "cassandra", "identity", "spiffe1")); + assertThat(initializer.defaultRoleName()).isEqualTo("cassandra"); + } + + @Test + public void mutualTlsWritesIdentityMappingBeforeRole() + { + MutualTlsDefaultRoleInitializer initializer = new MutualTlsDefaultRoleInitializer(Map.of("role", "cassandra", "identity", "spiffe1")); + List statements = initializer.defaultRoleStatements(); + + // The identity mapping must be written before the role row. hasExistingRoles() gates on the role, so writing + // it last means a retry after a partial write re-drives both idempotent statements and heals the mapping. + assertThat(statements).hasSize(2); + assertThat(statements.get(0)).contains(AuthKeyspace.IDENTITY_TO_ROLES).contains("(identity, role)"); + assertThat(statements.get(1)).contains("(role, is_superuser, can_login)"); + } +} diff --git a/test/unit/org/apache/cassandra/auth/PasswordAuthenticatorTest.java b/test/unit/org/apache/cassandra/auth/PasswordAuthenticatorTest.java index d40bdc634337..d6ef781b98b8 100644 --- a/test/unit/org/apache/cassandra/auth/PasswordAuthenticatorTest.java +++ b/test/unit/org/apache/cassandra/auth/PasswordAuthenticatorTest.java @@ -43,9 +43,9 @@ import org.apache.cassandra.transport.messages.AuthenticateMessage; import static org.apache.cassandra.auth.AuthTestUtils.ALL_ROLES; -import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD; import static org.apache.cassandra.auth.PasswordAuthenticator.SaslNegotiator; import static org.apache.cassandra.auth.PasswordAuthenticator.checkpw; +import static org.apache.cassandra.auth.PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_PASSWORD; import static org.apache.cassandra.auth.PasswordSaltSupplier.getGensaltLogRounds; import static org.apache.cassandra.config.CassandraRelevantProperties.AUTH_BCRYPT_GENSALT_LOG2_ROUNDS; import static org.assertj.core.api.Assertions.assertThat; diff --git a/test/unit/org/apache/cassandra/auth/RolesTest.java b/test/unit/org/apache/cassandra/auth/RolesTest.java index 77520e3631b6..b67313f1c253 100644 --- a/test/unit/org/apache/cassandra/auth/RolesTest.java +++ b/test/unit/org/apache/cassandra/auth/RolesTest.java @@ -20,6 +20,7 @@ import java.util.Arrays; import java.util.HashSet; +import java.util.Map; import java.util.Set; import java.util.stream.Collectors; @@ -118,20 +119,81 @@ public void grantedRoleResourcesAreCached() public void confirmSuperUserConsistency() { // Confirm special treatment of superuser - ConsistencyLevel readLevel = CassandraRoleManager.consistencyForRoleRead(CassandraRoleManager.DEFAULT_SUPERUSER_NAME); - Assert.assertEquals(CassandraRoleManager.DEFAULT_SUPERUSER_CONSISTENCY_LEVEL, readLevel); + ConsistencyLevel readLevel = AuthUtils.consistencyForRoleRead(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME); + Assert.assertEquals(AuthUtils.DEFAULT_SUPERUSER_CONSISTENCY_LEVEL, readLevel); - ConsistencyLevel writeLevel = CassandraRoleManager.consistencyForRoleWrite(CassandraRoleManager.DEFAULT_SUPERUSER_NAME); - Assert.assertEquals(CassandraRoleManager.DEFAULT_SUPERUSER_CONSISTENCY_LEVEL, writeLevel); + ConsistencyLevel writeLevel = AuthUtils.consistencyForRoleWrite(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME); + Assert.assertEquals(AuthUtils.DEFAULT_SUPERUSER_CONSISTENCY_LEVEL, writeLevel); // Confirm standard config-based treatment of non - ConsistencyLevel nonPrivReadLevel = CassandraRoleManager.consistencyForRoleRead("non-privilaged"); + ConsistencyLevel nonPrivReadLevel = AuthUtils.consistencyForRoleRead("non-privilaged"); Assert.assertEquals(nonPrivReadLevel, DatabaseDescriptor.getAuthReadConsistencyLevel()); - ConsistencyLevel nonPrivWriteLevel = CassandraRoleManager.consistencyForRoleWrite("non-privilaged"); + ConsistencyLevel nonPrivWriteLevel = AuthUtils.consistencyForRoleWrite("non-privilaged"); Assert.assertEquals(nonPrivWriteLevel, DatabaseDescriptor.getAuthWriteConsistencyLevel()); } + @Test + public void confirmSuperUserConsistencyWithConfiguredDefaultRoleName() + { + IRoleManager previousRoleManager = DatabaseDescriptor.getRoleManager(); + IDefaultRoleInitializer previousInitializer = DatabaseDescriptor.getDefaultRoleInitializer(); + String customRole = "cassandra_mtls_custom_test_role"; + try + { + DatabaseDescriptor.setRoleManager(new CassandraRoleManager()); + DatabaseDescriptor.setDefaultRoleInitializer(new MutualTlsDefaultRoleInitializer(Map.of( + MutualTlsDefaultRoleInitializer.ROLE, customRole, + MutualTlsDefaultRoleInitializer.IDENTITY, "spiffe1"))); + + ConsistencyLevel readLevel = AuthUtils.consistencyForRoleRead(customRole); + Assert.assertEquals(AuthUtils.DEFAULT_SUPERUSER_CONSISTENCY_LEVEL, readLevel); + + ConsistencyLevel writeLevel = AuthUtils.consistencyForRoleWrite(customRole); + Assert.assertEquals(AuthUtils.DEFAULT_SUPERUSER_CONSISTENCY_LEVEL, writeLevel); + + ConsistencyLevel legacyReadLevel = AuthUtils.consistencyForRoleRead(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME); + Assert.assertEquals(legacyReadLevel, DatabaseDescriptor.getAuthReadConsistencyLevel()); + + ConsistencyLevel legacyWriteLevel = AuthUtils.consistencyForRoleWrite(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME); + Assert.assertEquals(legacyWriteLevel, DatabaseDescriptor.getAuthWriteConsistencyLevel()); + } + finally + { + DatabaseDescriptor.setRoleManager(previousRoleManager); + DatabaseDescriptor.setDefaultRoleInitializer(previousInitializer); + } + } + + @Test + public void consistencyForRoleToleratesUnsetRoleManager() + { + IRoleManager previousRoleManager = DatabaseDescriptor.getRoleManager(); + IDefaultRoleInitializer previousInitializer = DatabaseDescriptor.getDefaultRoleInitializer(); + try + { + // Before auth setup runs, both the role manager and the initializer can be unset. consistencyForRole* + // must not NPE: it falls back to the historical default role name (see AuthUtils#defaultRoleName). + DatabaseDescriptor.setRoleManager(null); + DatabaseDescriptor.setDefaultRoleInitializer(null); + + Assert.assertEquals(AuthUtils.DEFAULT_SUPERUSER_CONSISTENCY_LEVEL, + AuthUtils.consistencyForRoleWrite(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME)); + Assert.assertEquals(AuthUtils.DEFAULT_SUPERUSER_CONSISTENCY_LEVEL, + AuthUtils.consistencyForRoleRead(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME)); + + Assert.assertEquals(DatabaseDescriptor.getAuthWriteConsistencyLevel(), + AuthUtils.consistencyForRoleWrite("non-privileged")); + Assert.assertEquals(DatabaseDescriptor.getAuthReadConsistencyLevel(), + AuthUtils.consistencyForRoleRead("non-privileged")); + } + finally + { + DatabaseDescriptor.setRoleManager(previousRoleManager); + DatabaseDescriptor.setDefaultRoleInitializer(previousInitializer); + } + } + @Test public void testSuperUsers() { diff --git a/test/unit/org/apache/cassandra/config/DatabaseDescriptorRefTest.java b/test/unit/org/apache/cassandra/config/DatabaseDescriptorRefTest.java index f031e8569179..3d7bb8da1010 100644 --- a/test/unit/org/apache/cassandra/config/DatabaseDescriptorRefTest.java +++ b/test/unit/org/apache/cassandra/config/DatabaseDescriptorRefTest.java @@ -74,6 +74,7 @@ public class DatabaseDescriptorRefTest "org.apache.cassandra.auth.IAuthorizer", "org.apache.cassandra.auth.ICIDRAuthorizer", "org.apache.cassandra.auth.ICIDRAuthorizer$CIDRAuthorizerMode", + "org.apache.cassandra.auth.IDefaultRoleInitializer", "org.apache.cassandra.auth.IInternodeAuthenticator", "org.apache.cassandra.auth.INetworkAuthorizer", "org.apache.cassandra.auth.IRoleManager", diff --git a/test/unit/org/apache/cassandra/config/ParameterizedClassTest.java b/test/unit/org/apache/cassandra/config/ParameterizedClassTest.java index 1ceaa734fa3b..ee6e45c27700 100644 --- a/test/unit/org/apache/cassandra/config/ParameterizedClassTest.java +++ b/test/unit/org/apache/cassandra/config/ParameterizedClassTest.java @@ -18,6 +18,7 @@ package org.apache.cassandra.config; +import java.util.HashMap; import java.util.List; import java.util.Map; @@ -74,34 +75,6 @@ public void testNewInstanceWithSingleEmptyConstructorUsesEmptyConstructor() assertNotNull(instance); } - @Test - public void testNewInstanceWithValidConstructorsFavorsMapConstructor() - { - ParameterizedClass parameterizedClass = new ParameterizedClass(ParameterizedClassExample.class.getName()); - ParameterizedClassExample instance = ParameterizedClass.newInstance(parameterizedClass, null); - assertNotNull(instance); - } - - @Test - public void testNewInstanceWithValidConstructorsUsingNullParamtersFavorsMapConstructor() - { - ParameterizedClass parameterizedClass = new ParameterizedClass(ParameterizedClassExample.class.getName()); - parameterizedClass.parameters = null; - - ParameterizedClassExample instance = ParameterizedClass.newInstance(parameterizedClass, null); - assertNotNull(instance); - } - - @Test - public void testNewInstanceWithConstructorExceptionPreservesOriginalFailure() - { - assertThatThrownBy(() -> ParameterizedClass.newInstance(new ParameterizedClass(ParameterizedClassExample.class.getName(), - Map.of("fail", "true")), null)) - .hasMessageStartingWith("Failed to instantiate class") - .hasMessageContaining("Simulated failure") - .isInstanceOf(ConfigurationException.class); - } - @Test public void testTypedNewInstanceRejectsWithoutInitializing() { @@ -146,4 +119,131 @@ public void testNewInstanceSearchPackageFallThroughDoesNotAbortOnWrongType() // The wrong-type class that was probed under the earlier package must not have been initialized. assertThat(ClassLoadingTestSupport.wasInitialized(org.apache.cassandra.utils.ClassLoadingSearchProbe.class)).isFalse(); } + + @Test + public void testNewInstanceWithValidConstructorsFavorsMapConstructor() + { + ParameterizedClass parameterizedClass = new ParameterizedClass(ParameterizedClassExample.class.getName()); + ParameterizedClassExample instance = ParameterizedClass.newInstance(parameterizedClass, null); + assertNotNull(instance); + } + + @Test + public void testNewInstanceWithValidConstructorsUsingNullParamtersFavorsMapConstructor() + { + ParameterizedClass parameterizedClass = new ParameterizedClass(ParameterizedClassExample.class.getName()); + parameterizedClass.parameters = null; + + ParameterizedClassExample instance = ParameterizedClass.newInstance(parameterizedClass, null); + assertNotNull(instance); + } + + @Test + public void testNewInstanceWithConstructorExceptionPreservesOriginalFailure() + { + assertThatThrownBy(() -> ParameterizedClass.newInstance(new ParameterizedClass(ParameterizedClassExample.class.getName(), + Map.of("fail", "true")), null)) + .hasMessageStartingWith("Failed to instantiate class") + .hasMessageContaining("Simulated failure") + .isInstanceOf(ConfigurationException.class); + } + + @Test + public void testToStringWithNullParametersOmitsParameters() + { + assertThat(new ParameterizedClass("Foo", null).toString()).isEqualTo("Foo{}"); + } + + @Test + public void testToStringWithEmptyParametersOmitsParameters() + { + assertThat(new ParameterizedClass("Foo").toString()).isEqualTo("Foo{}"); + } + + @Test + public void testToStringDoesNotRedactNonSensitiveParameters() + { + ParameterizedClass pc = new ParameterizedClass("Foo", Map.of("role", "cassandra", "identity", "spiffe1")); + // Keys are sorted (TreeMap) and non-sensitive values are shown verbatim. + assertThat(pc.toString()).isEqualTo("Foo{identity=spiffe1, role=cassandra}"); + } + + @Test + public void testToStringRedactsPasswordValue() + { + ParameterizedClass pc = new ParameterizedClass("Foo", Map.of("password", "secret")); + assertThat(pc.toString()).isEqualTo("Foo{password=}"); + } + + @Test + public void testToStringRedactsHashValue() + { + ParameterizedClass pc = new ParameterizedClass("Foo", Map.of("password_hash", "$2a$04$abc")); + assertThat(pc.toString()).isEqualTo("Foo{password_hash=}"); + } + + @Test + public void testToStringRedactsOnlySensitiveKeysAndSortsByKey() + { + Map params = new HashMap<>(); + params.put("role", "cassandra"); + params.put("password", "secret"); + params.put("keystore_password", "kspw"); + params.put("salted_hash", "abcd"); + ParameterizedClass pc = new ParameterizedClass("Foo", params); + assertThat(pc.toString()) + .isEqualTo("Foo{keystore_password=, password=, role=cassandra, salted_hash=}"); + } + + @Test + public void testToStringRedactionIsCaseInsensitive() + { + Map params = new HashMap<>(); + params.put("PASSWORD", "secret"); + params.put("Password_Hash", "h"); + params.put("myHASHkey", "v"); + ParameterizedClass pc = new ParameterizedClass("Foo", params); + assertThat(pc.toString()) + .isEqualTo("Foo{PASSWORD=, Password_Hash=, myHASHkey=}"); + } + + @Test + public void testToStringRedactsSensitiveKeyWithNullValueWithoutThrowing() + { + Map params = new HashMap<>(); + params.put("password", null); + ParameterizedClass pc = new ParameterizedClass("Foo", params); + // A sensitive key is redacted before its value is read, so a null value does not cause a failure. + assertThat(pc.toString()).isEqualTo("Foo{password=}"); + } + + @Test + public void testToStringRendersNonSensitiveNullValueWithoutThrowing() + { + Map params = new HashMap<>(); + params.put("identity", null); + ParameterizedClass pc = new ParameterizedClass("Foo", params); + // A non-sensitive key with a null value must render as key=null + assertThat(pc.toString()).isEqualTo("Foo{identity=null}"); + } + + @Test + public void testIsSensitiveMatchesPasswordAndHashCaseInsensitively() + { + ParameterizedClass pc = new ParameterizedClass("Foo"); + + assertThat(pc.isSensitive("password")).isTrue(); + assertThat(pc.isSensitive("PASSWORD")).isTrue(); + assertThat(pc.isSensitive("Password")).isTrue(); + assertThat(pc.isSensitive("keystore_password")).isTrue(); + assertThat(pc.isSensitive("password_hash")).isTrue(); + assertThat(pc.isSensitive("hash")).isTrue(); + assertThat(pc.isSensitive("HASH")).isTrue(); + assertThat(pc.isSensitive("salted_hash")).isTrue(); + + assertThat(pc.isSensitive("role")).isFalse(); + assertThat(pc.isSensitive("identity")).isFalse(); + assertThat(pc.isSensitive("class_name")).isFalse(); + assertThat(pc.isSensitive("keystore")).isFalse(); + } } diff --git a/test/unit/org/apache/cassandra/cql3/CQLTester.java b/test/unit/org/apache/cassandra/cql3/CQLTester.java index 6f836c0e8671..6c0d4935ec55 100644 --- a/test/unit/org/apache/cassandra/cql3/CQLTester.java +++ b/test/unit/org/apache/cassandra/cql3/CQLTester.java @@ -115,6 +115,7 @@ import org.apache.cassandra.auth.AuthTestUtils; import org.apache.cassandra.auth.IAuthenticator; import org.apache.cassandra.auth.IRoleManager; +import org.apache.cassandra.auth.PasswordDefaultRoleInitializer; import org.apache.cassandra.concurrent.Stage; import org.apache.cassandra.config.CassandraRelevantProperties; import org.apache.cassandra.config.Config; @@ -645,7 +646,7 @@ public void setup() { loadRoleStatement(); loadIdentityStatement(); - QueryProcessor.executeInternal(createDefaultRoleQuery()); + QueryProcessor.executeInternal(PasswordDefaultRoleInitializer.instance.createDefaultRoleQuery()); } }; diff --git a/test/unit/org/apache/cassandra/cql3/statements/AddIdentityStatementTest.java b/test/unit/org/apache/cassandra/cql3/statements/AddIdentityStatementTest.java index 424ea46ed076..0cfe9036884b 100644 --- a/test/unit/org/apache/cassandra/cql3/statements/AddIdentityStatementTest.java +++ b/test/unit/org/apache/cassandra/cql3/statements/AddIdentityStatementTest.java @@ -29,7 +29,7 @@ import org.apache.cassandra.auth.AuthKeyspace; import org.apache.cassandra.auth.AuthTestUtils; import org.apache.cassandra.auth.AuthenticatedUser; -import org.apache.cassandra.auth.CassandraRoleManager; +import org.apache.cassandra.auth.PasswordDefaultRoleInitializer; import org.apache.cassandra.auth.RoleResource; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.cql3.CQLStatement; @@ -62,7 +62,7 @@ private static void setupPrivilegedUser() + "VALUES ('%s', true, true, '%s')", AUTH_KEYSPACE_NAME, AuthKeyspace.ROLES, - CassandraRoleManager.DEFAULT_SUPERUSER_NAME, + PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME, "xxx")); } @@ -194,7 +194,7 @@ public void ifNotExistsTest() static QueryState getClientState() { ClientState state = ClientState.forInternalCalls(); - state.login(new AuthenticatedUser(CassandraRoleManager.DEFAULT_SUPERUSER_NAME)); + state.login(new AuthenticatedUser(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME)); return new QueryState(state); } } diff --git a/test/unit/org/apache/cassandra/db/guardrails/GuardrailTester.java b/test/unit/org/apache/cassandra/db/guardrails/GuardrailTester.java index b9fe9d6ea01d..ebcf760b4354 100644 --- a/test/unit/org/apache/cassandra/db/guardrails/GuardrailTester.java +++ b/test/unit/org/apache/cassandra/db/guardrails/GuardrailTester.java @@ -45,7 +45,7 @@ import org.junit.BeforeClass; import org.apache.cassandra.auth.AuthenticatedUser; -import org.apache.cassandra.auth.CassandraRoleManager; +import org.apache.cassandra.auth.PasswordDefaultRoleInitializer; import org.apache.cassandra.config.DatabaseDescriptor; import org.apache.cassandra.cql3.CQLStatement; import org.apache.cassandra.cql3.CQLTester; @@ -130,7 +130,7 @@ public static void setUpState() userClientState.login(user); superClientState = ClientState.forExternalCalls(InetSocketAddress.createUnresolved("127.0.0.1", 321)); - superClientState.login(new AuthenticatedUser(CassandraRoleManager.DEFAULT_SUPERUSER_NAME)); + superClientState.login(new AuthenticatedUser(PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME)); } /** diff --git a/test/unit/org/apache/cassandra/transport/TlsTestUtils.java b/test/unit/org/apache/cassandra/transport/TlsTestUtils.java index 1ff868ecf4df..a696a51cd79a 100644 --- a/test/unit/org/apache/cassandra/transport/TlsTestUtils.java +++ b/test/unit/org/apache/cassandra/transport/TlsTestUtils.java @@ -50,8 +50,8 @@ import org.apache.cassandra.utils.tls.CertificateBuilder; import org.apache.cassandra.utils.tls.CertificateBundle; -import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_NAME; -import static org.apache.cassandra.auth.CassandraRoleManager.DEFAULT_SUPERUSER_PASSWORD; +import static org.apache.cassandra.auth.PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_NAME; +import static org.apache.cassandra.auth.PasswordDefaultRoleInitializer.DEFAULT_SUPERUSER_PASSWORD; public class TlsTestUtils {