worryg0d commented on code in PR #4379:
URL: https://github.com/apache/cassandra/pull/4379#discussion_r2355261842


##########
src/java/org/apache/cassandra/auth/IRoleManager.java:
##########
@@ -72,6 +73,23 @@ public enum Option
     void createRole(AuthenticatedUser performer, RoleResource role, 
RoleOptions options)
     throws RequestValidationException, RequestExecutionException;
 
+    /**
+     * Called during execution of a CREATE ROLE statement.
+     * options are guaranteed to be a subset of supportedOptions().
+     *
+     * @param performer User issuing the create role statement.
+     * @param role Rolei being created

Review Comment:
   Typo: -> `Role is being created`



##########
src/antlr/Parser.g:
##########
@@ -1443,9 +1443,10 @@ createUserStatement returns [CreateRoleStatement stmt]
         opts.setOption(IRoleManager.Option.LOGIN, true);
         boolean superuser = false;
         boolean ifNotExists = false;
+        boolean isGeneratedName = false;
         RoleName name = new RoleName();
     }
-    : K_CREATE K_USER (K_IF K_NOT K_EXISTS { ifNotExists = true; })? 
u=username { name.setName($u.text, true); }
+    : K_CREATE (K_GENERATED { isGeneratedName = true; })? K_USER (K_IF K_NOT 
K_EXISTS { ifNotExists = true; })? (u=username { name.setName($u.text, true); 
})?

Review Comment:
   As far as I know, the `USER` is deprecated. Therefore, does it actually make 
sense to introduce new functionality to this API?



##########
src/java/org/apache/cassandra/db/guardrails/CassandraPasswordConfiguration.java:
##########
@@ -173,6 +175,11 @@ public void validateParameters() throws 
ConfigurationException
         if (lengthWarn < 0) throw mustBePositiveException(LENGTH_WARN_KEY);
         if (lengthFail < 0) throw mustBePositiveException(LENGTH_FAIL_KEY);
 
+        if (MAX_LENGTH < maxLength)
+            throw new ConfigurationException(format("%s can not be less than 
or equal to %s",
+                                                    MAX_LENGTH_KEY,
+                                                    MAX_LENGTH));
+

Review Comment:
   I guess it is intended to be `%s can not be greater than or equal to %s`.
   
   less -> greater



##########
src/java/org/apache/cassandra/db/guardrails/UUIDRoleNameGenerator.java:
##########
@@ -0,0 +1,196 @@
+/*
+ * 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.db.guardrails;
+
+import java.util.Map;
+import java.util.Random;
+import java.util.Set;
+import java.util.UUID;
+import java.util.regex.Pattern;
+import javax.annotation.Nonnull;
+
+import org.apache.cassandra.exceptions.ConfigurationException;
+
+/**
+ * Generates random name for user / role.
+ * Generator reacts on these parameters when specified in OPTIONS map in CQL:
+ * <ul>
+ *     <li>name_prefix - arbitrary string to prepend to generated name</li>
+ *     <li>name_suffix - arbitraty string to append to generated name</li>
+ *     <li>name_size - size of generated string. Can not be less than 10 and 
more than 32</li>
+ * </ul>
+ * <p>
+ * Additionally, it reacts to this parameter put in cassandra.yaml:
+ *
+ * <ul>
+ *     <li>min_generated_name_size - sets minimum size of name. If {@code 
name_size} is specified in CQL's OPTIONS,
+ *     it will be checked against this minimum size and fail if smaller than 
that.
+ *     </li>
+ * </ul>
+ * <p>
+ * {@code name_prefix} and {@code name_suffix} string lengths are not included 
in {@code name_size} length.
+ * {@code name_size} is only related to generated part of the role name.
+ * <p>
+ * The first character of generated role name will be always one of {@code 
a,b,c,d,e,f}.
+ */
+public class UUIDRoleNameGenerator extends ValueGenerator<String>
+{
+    public static final String NAME_PREFIX_KEY = "name_prefix";
+    public static final String NAME_SUFFIX_KEY = "name_suffix";
+    public static final String NAME_SIZE = "name_size";
+    public static final String MINIMUM_NAME_SIZE_CONFIG_OPTION = 
"min_generated_name_size";
+    public static final int DEFAULT_MINIMUM_NAME_SIZE = 10;
+    private static final Set<String> KEYS_IN_OPTIONS = Set.of(NAME_PREFIX_KEY, 
NAME_SUFFIX_KEY, NAME_SIZE);
+
+    private static final Pattern PATTERN = Pattern.compile("-");
+    public static final char[] FIRST_CHARS = { 'a', 'b', 'c', 'd', 'e', 'f' };
+
+    private static final Random random = new Random();
+    // lenght of UUID without hyphens
+    // generated name can be longer than this if it has prefix / suffix
+    public static final int MAXIMUM_NAME_SIZE = 32;
+
+    private final int minimumNameSize;
+
+    public UUIDRoleNameGenerator()
+    {
+        this(new CustomGuardrailConfig());
+    }
+
+    public UUIDRoleNameGenerator(CustomGuardrailConfig config)
+    {
+        super(config);
+        minimumNameSize = 
config.resolveInteger(MINIMUM_NAME_SIZE_CONFIG_OPTION, 
DEFAULT_MINIMUM_NAME_SIZE);
+        validateParameters();
+    }
+
+    @Override
+    public Set<String> getSupportedOptionsKeys()
+    {
+        return KEYS_IN_OPTIONS;
+    }
+
+    @Override
+    public String generate(ValueValidator<String> validator, Map<String, 
Object> options)
+    {
+        int size = getSize(options);
+
+        // to always start on a letter, so we do not need to wrap in ''
+        char firstChar = FIRST_CHARS[random.nextInt(6)];
+        String uuid = UUID.randomUUID().toString();
+        String uuidWithoutHyphens = PATTERN.matcher(uuid).replaceAll("");
+        String name = firstChar + uuidWithoutHyphens.substring(1);
+
+        name = name.substring(0, size);
+
+        if (options == null)
+            return name;
+
+        name = enrich(NAME_PREFIX_KEY, name, options);
+        name = enrich(NAME_SUFFIX_KEY, name, options);
+
+        return name;
+    }
+
+    @Nonnull
+    @Override
+    public CustomGuardrailConfig getParameters()
+    {
+        return config;
+    }
+
+    @Override
+    public void validateParameters() throws ConfigurationException
+    {
+        if (minimumNameSize < DEFAULT_MINIMUM_NAME_SIZE || minimumNameSize > 
MAXIMUM_NAME_SIZE)
+            throw new ConfigurationException(MINIMUM_NAME_SIZE_CONFIG_OPTION + 
" has to be at least " + DEFAULT_MINIMUM_NAME_SIZE + " and at most " + 
MAXIMUM_NAME_SIZE);
+    }
+
+    private String enrich(String key, String generatedValue, Map<String, 
Object> options)
+    {
+        if (options == null || options.isEmpty())

Review Comment:
   Condition `options == null` is always false, since the validation on line 
102. 
   Also, it makes sense to move the second condition `|| options.isEmtpy()` to 
line 102 as well before `enrich()` method call.



##########
src/antlr/Parser.g:
##########
@@ -1443,9 +1443,10 @@ createUserStatement returns [CreateRoleStatement stmt]
         opts.setOption(IRoleManager.Option.LOGIN, true);
         boolean superuser = false;
         boolean ifNotExists = false;
+        boolean isGeneratedName = false;
         RoleName name = new RoleName();
     }
-    : K_CREATE K_USER (K_IF K_NOT K_EXISTS { ifNotExists = true; })? 
u=username { name.setName($u.text, true); }
+    : K_CREATE (K_GENERATED { isGeneratedName = true; })? K_USER (K_IF K_NOT 
K_EXISTS { ifNotExists = true; })? (u=username { name.setName($u.text, true); 
})?

Review Comment:
   OK, I assumed that this is deprecated due to this message from Cassandra 
server:
   
   ```
   cassandra@cqlsh> CREATE USER "testuser";
   SyntaxException: Quoted strings are are not supported for user names and 
USER is deprecated, please use ROLE
   cassandra@cqlsh> CREATE ROLE "testrole";
   cassandra@cqlsh> 
   ```
   
   But referring to the doc (1), it is actually an alternative syntax.
   
   Probably, it is worth updating the recognition error message for 
**username** rule. It also contains doubled `are` in the message.
   
https://github.com/apache/cassandra/blob/eb65c0e6009086fd5227251cca554596efcddf84/src/antlr/Parser.g#L2245
   
   (1) 
https://cassandra.apache.org/doc/trunk/cassandra/developing/cql/security.html#users
    



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to