From 727956741da9e79b1f8c725ee61bc184e72e701e Mon Sep 17 00:00:00 2001
From: Jan Tattermusch <jtattermusch@google.com>
Date: Fri, 28 Aug 2015 08:54:26 -0700
Subject: check for allowed characters in metadata key

---
 src/csharp/Grpc.Core.Tests/MetadataTest.cs | 11 +++++++++++
 src/csharp/Grpc.Core/Metadata.cs           |  7 ++++++-
 2 files changed, 17 insertions(+), 1 deletion(-)

diff --git a/src/csharp/Grpc.Core.Tests/MetadataTest.cs b/src/csharp/Grpc.Core.Tests/MetadataTest.cs
index c00f945d6a..ddeb7d0926 100644
--- a/src/csharp/Grpc.Core.Tests/MetadataTest.cs
+++ b/src/csharp/Grpc.Core.Tests/MetadataTest.cs
@@ -74,6 +74,17 @@ namespace Grpc.Core.Tests
             Assert.AreEqual("[Entry: key=abc-bin, valueBytes=System.Byte[]]", entry.ToString());
         }
 
+        [Test]
+        public void AsciiEntry_KeyValidity()
+        {
+            new Metadata.Entry("ABC", "XYZ");
+            new Metadata.Entry("0123456789abc", "XYZ");
+            new Metadata.Entry("-abc", "XYZ");
+            new Metadata.Entry("a_bc_", "XYZ");
+            Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc[", "xyz"));
+            Assert.Throws(typeof(ArgumentException), () => new Metadata.Entry("abc/", "xyz"));
+        }
+
         [Test]
         public void Entry_ConstructionPreconditions()
         {
diff --git a/src/csharp/Grpc.Core/Metadata.cs b/src/csharp/Grpc.Core/Metadata.cs
index 2b08e0de51..21bdf4f114 100644
--- a/src/csharp/Grpc.Core/Metadata.cs
+++ b/src/csharp/Grpc.Core/Metadata.cs
@@ -36,6 +36,7 @@ using System.Collections.Specialized;
 using System.Globalization;
 using System.Runtime.InteropServices;
 using System.Text;
+using System.Text.RegularExpressions;
 
 using Grpc.Core.Utils;
 
@@ -189,6 +190,7 @@ namespace Grpc.Core
         public struct Entry
         {
             private static readonly Encoding Encoding = Encoding.ASCII;
+            private static readonly Regex ValidKeyRegex = new Regex("^[a-z0-9_-]+$");
 
             readonly string key;
             readonly string value;
@@ -321,7 +323,10 @@ namespace Grpc.Core
 
             private static string NormalizeKey(string key)
             {
-                return Preconditions.CheckNotNull(key, "key").ToLower(CultureInfo.InvariantCulture);
+                var normalized = Preconditions.CheckNotNull(key, "key").ToLower(CultureInfo.InvariantCulture);
+                Preconditions.CheckArgument(ValidKeyRegex.IsMatch(normalized), 
+                    "Metadata entry key not valid. Keys can only contain lowercase alphanumeric characters, underscores and hyphens.");
+                return normalized;
             }
         }
     }
-- 
cgit v1.2.3