From 9f22a3c1499ec6c439cf41a355d55af5fe6a3228 Mon Sep 17 00:00:00 2001
From: issazhang <issazhang@tencent.com>
Date: Tue, 5 Sep 2023 17:26:58 +0800
Subject: [PATCH] [refine]mongod: check duplicated fields in create indexes

---
 src/mongo/db/catalog/index_key_validate.cpp      | 11 +++++++++++
 src/mongo/db/catalog/index_key_validate_test.cpp |  5 +++++
 2 files changed, 16 insertions(+)

diff --git a/src/mongo/db/catalog/index_key_validate.cpp b/src/mongo/db/catalog/index_key_validate.cpp
index fbbf2004d4525..3008aa5c0f0e9 100644
--- a/src/mongo/db/catalog/index_key_validate.cpp
+++ b/src/mongo/db/catalog/index_key_validate.cpp
@@ -370,9 +370,20 @@ StatusWith<BSONObj> validateIndexSpec(OperationContext* opCtx, const BSONObj& in
 
     boost::optional<IndexVersion> resolvedIndexVersion;
     std::string indexType;
+    std::set<StringData> fieldsNames;
 
     for (auto&& indexSpecElem : indexSpec) {
         auto indexSpecElemFieldName = indexSpecElem.fieldNameStringData();
+
+        if (fieldsNames.count(indexSpecElemFieldName)) {
+            return {ErrorCodes::BadValue,
+                    str::stream() << "The field '" << indexSpecElemFieldName
+                    << "' appears more than one times in the index specification "
+                    << indexSpec
+            };
+        }
+        fieldsNames.insert(indexSpecElemFieldName);
+
         if (IndexDescriptor::kKeyPatternFieldName == indexSpecElemFieldName) {
             if (indexSpecElem.type() != BSONType::Object) {
                 return {ErrorCodes::TypeMismatch,
diff --git a/src/mongo/db/catalog/index_key_validate_test.cpp b/src/mongo/db/catalog/index_key_validate_test.cpp
index 8323df5485db1..6d885195ea34b 100644
--- a/src/mongo/db/catalog/index_key_validate_test.cpp
+++ b/src/mongo/db/catalog/index_key_validate_test.cpp
@@ -526,5 +526,10 @@ TEST(IndexKeyValidateTest, GeoIndexSpecs) {
         fromjson("{'key':{'loc':'2dsphere'},'name':'loc_2dsphere','finestIndexedLevel':true,'"
                  "coarsestIndexedLevel':5}")));
 }
+
+TEST(IndexKeyValidateTest, DuplicatedFieldNames) {
+    ASSERT_NOT_OK(index_key_validate::validateIndexSpec(
+        nullptr, fromjson("{key: {a: 1}, name: 'index', background: true, background: true}")));
+}
 }  // namespace
 }  // namespace mongo