isaric commented on code in PR #5416:
URL: https://github.com/apache/solr/pull/5416#discussion_r4772781978


##########
solr/solrj/src/java/org/apache/solr/common/schema/SchemaMetadataValidator.java:
##########
@@ -0,0 +1,343 @@
+/*
+ * 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.solr.common.schema;
+
+import java.util.HashMap;
+import java.util.List;
+import java.util.Locale;
+import java.util.Map;
+import java.util.regex.Pattern;
+import org.apache.solr.common.SolrException;
+import org.apache.solr.common.SolrException.ErrorCode;
+import org.apache.solr.common.util.EnvUtils;
+
+/**
+ * Checks descriptive schema metadata. Solr runs every metadata value through 
{@link #validate(Map,
+ * String)} before it enters a schema, and checks the total size of a schema's 
metadata with {@link
+ * #validateTotalSize(long, String, Limits)}. Clients may run the same checks, 
but the limits come
+ * from the system properties of the JVM that runs them, so only the server's 
check is binding.
+ *
+ * <p>Rules:
+ *
+ * <ul>
+ *   <li>Keys look like {@code prefix:name} or {@code name}: the prefix 
matches {@code
+ *       [A-Za-z][A-Za-z0-9]*} and the name {@code [A-Za-z][A-Za-z0-9_.-]*}.
+ *   <li>Top-level keys follow {@link SchemaMetadataVocabulary}: a key without 
a prefix must be a
+ *       DCMI Term, a {@code dc:} key must name one, and {@code solr:} is 
reserved. {@code
+ *       description} and {@code dc:description} are the same key and can't 
both be given. Prefixes
+ *       are case-insensitive, names are case-sensitive. Keys in nested maps 
are checked for syntax
+ *       only.
+ *   <li>Values are strings, integers, longs, floats, doubles, booleans, null, 
and nested maps and
+ *       lists of those.
+ *   <li>Key length, string length, the number of entries, the nesting depth 
and the total size per
+ *       schema are limited; see {@link Limits}.
+ * </ul>
+ */
+public final class SchemaMetadataValidator {
+
+  /** Element and property name used for metadata. */
+  public static final String META = "meta";
+
+  /** Syntax of every key, top-level or nested. */
+  private static final Pattern KEY_PATTERN =
+      Pattern.compile("(?:[A-Za-z][A-Za-z0-9]*:)?[A-Za-z][A-Za-z0-9_.-]*");
+
+  public static final String PROP_KEY_LENGTH_MAX = 
"solr.schema.meta.key.length.max";
+  public static final String PROP_STRING_LENGTH_MAX = 
"solr.schema.meta.string.length.max";
+  public static final String PROP_ENTRIES_MAX = "solr.schema.meta.entries.max";
+  public static final String PROP_DEPTH_MAX = "solr.schema.meta.depth.max";
+  public static final String PROP_TOTAL_SIZE_MAX = 
"solr.schema.meta.total.size.max";
+
+  /**
+   * Highest value the depth limit can be set to. Solr's parser rejects deeper 
nesting before the
+   * limits are checked.
+   */
+  public static final int MAX_DEPTH_CEILING = 10;
+
+  /**
+   * Metadata limits.
+   *
+   * @param maxKeyLength longest key, in characters
+   * @param maxStringLength longest string value, in characters
+   * @param maxEntries most entries in one element's metadata, counting nested 
entries and list
+   *     items
+   * @param maxDepth deepest nesting of maps and lists, at most {@link 
#MAX_DEPTH_CEILING}
+   * @param maxTotalSize largest total size of all {@code <meta>} elements in 
a schema file, in
+   *     UTF-8 bytes
+   */
+  public record Limits(
+      int maxKeyLength, int maxStringLength, int maxEntries, int maxDepth, 
long maxTotalSize) {
+
+    /** The default limits. */
+    public static final Limits DEFAULTS = new Limits(64, 1024, 64, 3, 256 * 
1024);
+
+    /**
+     * @throws IllegalArgumentException if a limit is not positive, or the 
depth limit is above
+     *     {@link #MAX_DEPTH_CEILING}
+     */
+    public Limits {
+      if (maxKeyLength <= 0
+          || maxStringLength <= 0
+          || maxEntries <= 0
+          || maxDepth <= 0
+          || maxTotalSize <= 0) {
+        throw new IllegalArgumentException("metadata limits must be positive");
+      }
+      if (maxDepth > MAX_DEPTH_CEILING) {
+        throw new IllegalArgumentException(
+            "the metadata depth limit must be at most " + MAX_DEPTH_CEILING + 
", got " + maxDepth);
+      }
+    }
+
+    /**
+     * Returns the limits set by system properties, with {@link #DEFAULTS} for 
those not set.
+     *
+     * @throws SolrException if a property is not a whole number in its 
allowed range; the message
+     *     names the property
+     */
+    public static Limits fromSystemProperties() {
+      return new Limits(
+          (int) property(PROP_KEY_LENGTH_MAX, DEFAULTS.maxKeyLength, 
Integer.MAX_VALUE),
+          (int) property(PROP_STRING_LENGTH_MAX, DEFAULTS.maxStringLength, 
Integer.MAX_VALUE),
+          (int) property(PROP_ENTRIES_MAX, DEFAULTS.maxEntries, 
Integer.MAX_VALUE),
+          (int) property(PROP_DEPTH_MAX, DEFAULTS.maxDepth, MAX_DEPTH_CEILING),
+          property(PROP_TOTAL_SIZE_MAX, DEFAULTS.maxTotalSize, 
Long.MAX_VALUE));
+    }
+
+    private static long property(String name, long defaultValue, long max) {
+      String value = EnvUtils.getProperty(name);
+      if (value == null) {
+        return defaultValue;
+      }
+      long parsed;
+      try {
+        parsed = Long.parseLong(value.trim());
+      } catch (NumberFormatException e) {
+        parsed = -1;
+      }
+      if (parsed <= 0 || parsed > max) {
+        throw new SolrException(
+            ErrorCode.SERVER_ERROR,
+            "Invalid value '"
+                + value
+                + "' for the system property "
+                + name
+                + " (environment variable "
+                + environmentVariable(name)
+                + "): expected a whole number from 1 to "
+                + max);
+      }
+      return parsed;
+    }
+  }
+
+  private SchemaMetadataValidator() {}
+
+  /**
+   * Validates one element's metadata with the limits from system properties.
+   *
+   * @param entries top-level entries, with nested values as maps and lists
+   * @param context names the owning element in error messages, e.g. {@code 
field 'id'}
+   * @throws SolrException with code 400 if a rule is broken
+   */
+  public static void validate(Map<String, ?> entries, String context) {

Review Comment:
   Non-blocking, a question on the dropped character check. I follow the 
reasoning in SOLR-18696 that the problem is general and that the escapers keep 
the file well-formed, so a bad character changes the value rather than breaking 
the load. Until that ticket lands, though, metadata is the one place where a 
Schema API string can now be silently altered on save where Part 1 would have 
rejected it with a clear message. Keeping Part 1's check here until SOLR-18696 
is in would cost little; your call, since you own both.



-- 
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