From 4aa5a481e3038c7e041e317df46f90d3512fdc5e Mon Sep 17 00:00:00 2001 From: Jon Skeet Date: Mon, 3 Aug 2020 10:59:00 +0100 Subject: [PATCH] Prevent the spec version attribute from being removed via Remove calls Signed-off-by: Jon Skeet --- .../CloudEventAttributes.cs | 8 ++++++++ .../CloudEventAttributesTest.cs | 18 ++++++++++++++++++ 2 files changed, 26 insertions(+) diff --git a/src/CloudNative.CloudEvents/CloudEventAttributes.cs b/src/CloudNative.CloudEvents/CloudEventAttributes.cs index aeecde0..4e0159f 100644 --- a/src/CloudNative.CloudEvents/CloudEventAttributes.cs +++ b/src/CloudNative.CloudEvents/CloudEventAttributes.cs @@ -267,11 +267,19 @@ namespace CloudNative.CloudEvents bool ICollection>.Remove(KeyValuePair item) { + if (item.Key.Equals(SpecVersionAttributeName(this.SpecVersion), StringComparison.InvariantCultureIgnoreCase)) + { + throw new InvalidOperationException(Strings.ErrorSpecVersionCannotBeCleared); + } return dict.Remove(item); } bool IDictionary.Remove(string key) { + if (key.Equals(SpecVersionAttributeName(this.SpecVersion), StringComparison.InvariantCultureIgnoreCase)) + { + throw new InvalidOperationException(Strings.ErrorSpecVersionCannotBeCleared); + } return dict.Remove(key); } diff --git a/test/CloudNative.CloudEvents.UnitTests/CloudEventAttributesTest.cs b/test/CloudNative.CloudEvents.UnitTests/CloudEventAttributesTest.cs index c087932..d183dc6 100644 --- a/test/CloudNative.CloudEvents.UnitTests/CloudEventAttributesTest.cs +++ b/test/CloudNative.CloudEvents.UnitTests/CloudEventAttributesTest.cs @@ -62,5 +62,23 @@ namespace CloudNative.CloudEvents.UnitTests Assert.Equal(CloudEventAttributes.SpecVersionAttributeName(), entry.Key); Assert.Equal(specVersionValue, entry.Value); } + + [Fact] + public void Dictionary_Remove_SpecVersion() + { + IDictionary attributes = new CloudEventAttributes(CloudEventsSpecVersion.Default, emptyExtensions); + string specVersionAttributeName = CloudEventAttributes.SpecVersionAttributeName(); + Assert.Throws(() => attributes.Remove(specVersionAttributeName)); + } + + [Fact] + public void Collection_Remove_SpecVersion() + { + ICollection> attributes = new CloudEventAttributes(CloudEventsSpecVersion.Default, emptyExtensions); + string specVersionAttributeName = CloudEventAttributes.SpecVersionAttributeName(); + // The value part is irrelevant; we throw on any attempt to remove a pair with a key that's the spec attribute version. + var pair = KeyValuePair.Create(specVersionAttributeName, new object()); + Assert.Throws(() => attributes.Remove(pair)); + } } }