check for allowed characters in metadata key

pull/3125/head
Jan Tattermusch 9 years ago
parent 400e0cdd32
commit 727956741d
  1. 11
      src/csharp/Grpc.Core.Tests/MetadataTest.cs
  2. 7
      src/csharp/Grpc.Core/Metadata.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()
{

@ -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;
}
}
}

Loading…
Cancel
Save