-
Notifications
You must be signed in to change notification settings - Fork 836
Introduce type converter for DataClassification #5887
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
859042b
Introduce type converter for data classification struct to be able to…
dariusclay 736df75
supress warnings for test class
dariusclay 5f7f28d
Merge branch 'main' into dletterman/dataclass-typeconverter
dariusclay fddeecb
full test coverage and optimizations
dariusclay 4edc94b
Merge branch 'main' into dletterman/dataclass-typeconverter
dariusclay 77aac5c
comment grammar
dariusclay c30c587
wording
dariusclay ffd482f
Add experimental attribute
dariusclay e708e88
ignore LA0001 causing issues in code coverage
dariusclay 1e43155
Remove unnecessary using
dariusclay e35d2ad
Update readme
dariusclay 72d1c8b
add more edge cases
dariusclay 73e3ec1
Merge branch 'main' into dletterman/dataclass-typeconverter
dariusclay File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
108 changes: 108 additions & 0 deletions
108
...soft.Extensions.Compliance.Abstractions/Classification/DataClassificationTypeConverter.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,108 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.ComponentModel; | ||
using System.Diagnostics.CodeAnalysis; | ||
using System.Globalization; | ||
using Microsoft.Shared.DiagnosticIds; | ||
|
||
namespace Microsoft.Extensions.Compliance.Classification; | ||
|
||
/// <summary> | ||
/// Provides a way to convert a <see cref="DataClassification"/> to and from a string. | ||
/// </summary> | ||
[Experimental(DiagnosticIds.Experiments.Compliance, UrlFormat = DiagnosticIds.UrlFormat)] | ||
public class DataClassificationTypeConverter : TypeConverter | ||
{ | ||
private const char Delimiter = ':'; | ||
|
||
/// <inheritdoc/> | ||
public override bool CanConvertFrom(ITypeDescriptorContext? context, Type sourceType) | ||
{ | ||
return sourceType == typeof(string); | ||
} | ||
|
||
/// <inheritdoc/> | ||
public override bool CanConvertTo(ITypeDescriptorContext? context, Type? destinationType) | ||
{ | ||
return destinationType == typeof(DataClassification); | ||
} | ||
|
||
/// <inheritdoc/> | ||
[SuppressMessage("Performance", | ||
"LA0001:Use the 'Microsoft.Shared.Diagnostics.Throws' class instead of explicitly throwing exception for improved performance", | ||
Justification = "Using the Throws class causes static analysis to incorrectly assume that code after the throw is reachable.")] | ||
public override object? ConvertFrom(ITypeDescriptorContext? context, CultureInfo? culture, object value) | ||
{ | ||
if (value is not string stringValue) | ||
{ | ||
throw new ArgumentException("Value must be a string.", nameof(value)); | ||
} | ||
|
||
if (stringValue == nameof(DataClassification.None)) | ||
{ | ||
return DataClassification.None; | ||
} | ||
|
||
if (stringValue == nameof(DataClassification.Unknown)) | ||
{ | ||
return DataClassification.Unknown; | ||
} | ||
|
||
if (TryParse(stringValue, out var taxonomyName, out var taxonomyValue)) | ||
{ | ||
return new DataClassification(taxonomyName, taxonomyValue); | ||
} | ||
|
||
throw new FormatException($"Invalid data classification format: '{stringValue}'."); | ||
} | ||
|
||
/// <inheritdoc/> | ||
public override bool IsValid(ITypeDescriptorContext? context, object? value) | ||
{ | ||
if (value is not string stringValue) | ||
{ | ||
return false; | ||
} | ||
|
||
if (stringValue == nameof(DataClassification.None) || | ||
stringValue == nameof(DataClassification.Unknown)) | ||
{ | ||
return true; | ||
} | ||
|
||
return TryParse(stringValue, out var taxonomyName, out var taxonomyValue); | ||
} | ||
|
||
/// <summary> | ||
/// Attempts to parse a string in the format "TaxonomyName:Value". | ||
/// </summary> | ||
/// <param name="value">The input string to parse.</param> | ||
/// <param name="taxonomyName">When this method returns, contains the parsed taxonomy name if the parsing succeeded, or an empty string if it failed.</param> | ||
/// <param name="taxonomyValue">When this method returns, contains the parsed taxonomy value if the parsing succeeded, or the original input string if it failed.</param> | ||
/// <returns><see langword="true"/> if the string was successfully parsed; otherwise, <see langword="false"/>.</returns> | ||
private static bool TryParse(string value, out string taxonomyName, out string taxonomyValue) | ||
{ | ||
taxonomyName = string.Empty; | ||
taxonomyValue = value; | ||
|
||
if (value.Length <= 1) | ||
{ | ||
return false; | ||
} | ||
|
||
ReadOnlySpan<char> valueSpan = value.AsSpan(); | ||
int index = valueSpan.IndexOf(Delimiter); | ||
|
||
if (index <= 0 || index >= (value.Length - 1)) | ||
{ | ||
return false; | ||
} | ||
|
||
taxonomyName = valueSpan.Slice(0, index).ToString(); | ||
taxonomyValue = valueSpan.Slice(index + 1).ToString(); | ||
|
||
return true; | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
182 changes: 182 additions & 0 deletions
182
...ions.Compliance.Abstractions.Tests/Classification/DataClassificationTypeConverterTests.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,182 @@ | ||
// Licensed to the .NET Foundation under one or more agreements. | ||
// The .NET Foundation licenses this file to you under the MIT license. | ||
|
||
using System; | ||
using System.Collections.Generic; | ||
using FluentAssertions; | ||
using Microsoft.Extensions.Configuration; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using Microsoft.Extensions.Options; | ||
using Xunit; | ||
|
||
namespace Microsoft.Extensions.Compliance.Classification.Tests; | ||
|
||
public class DataClassificationTypeConverterTests | ||
{ | ||
public static IEnumerable<object[]> DefaultDataClassificationTestData() | ||
{ | ||
yield return new object[] { "None", DataClassification.None }; | ||
yield return new object[] { "Unknown", DataClassification.Unknown }; | ||
} | ||
|
||
public static IEnumerable<object[]> CustomDataClassificationTestData() | ||
{ | ||
yield return new object[] { "Example:Test", new DataClassification("Example", "Test") }; | ||
yield return new object[] { "Taxonomy:Value", new DataClassification("Taxonomy", "Value") }; | ||
yield return new object[] { "Custom:Data", new DataClassification("Custom", "Data") }; | ||
} | ||
|
||
[Fact] | ||
public void BindServiceCollection_ShouldReturnIOptionsWithExpectedDataClassification() | ||
{ | ||
// Arrange | ||
var configuration = new ConfigurationBuilder() | ||
.AddInMemoryCollection(new[] | ||
{ | ||
new KeyValuePair<string, string?>("Key:Example", "Example:Test"), | ||
new KeyValuePair<string, string?>("Key:Facts:Value", "Taxonomy:Value"), | ||
new KeyValuePair<string, string?>("Key:Facts:Data", "Custom:Data"), | ||
new KeyValuePair<string, string?>("Key:Facts:None", "None"), | ||
new KeyValuePair<string, string?>("Key:Facts:Unknown", "Unknown"), | ||
new KeyValuePair<string, string?>("Key:Facts:Invalid", "Invalid"), | ||
}) | ||
.Build(); | ||
|
||
IServiceCollection serviceCollection = new ServiceCollection() | ||
.Configure<TestOptions>(configuration.GetSection("Key")); | ||
|
||
// Act | ||
using var sp = serviceCollection.BuildServiceProvider(); | ||
var options = sp.GetRequiredService<IOptions<TestOptions>>(); | ||
|
||
var expected = new Dictionary<string, DataClassification> | ||
{ | ||
{ "Value", new DataClassification("Taxonomy", "Value") }, | ||
{ "Data", new DataClassification("Custom", "Data") }, | ||
{ "None", DataClassification.None }, | ||
{ "Unknown", DataClassification.Unknown }, | ||
}; | ||
|
||
// Assert | ||
options.Value.Example.Should().NotBeNull().And.Be(new DataClassification("Example", "Test")); | ||
options.Value.Facts.Should().NotBeEmpty().And.Equal(expected); | ||
|
||
// Odd quirk: binding to dictionary succeeds but doesn't include invalid values | ||
options.Value.Facts.Should().NotContainKey("Invalid"); | ||
} | ||
|
||
[Theory] | ||
[InlineData(typeof(string), true)] | ||
[InlineData(typeof(int), false)] | ||
[InlineData(typeof(DataClassification), false)] | ||
public void CanConvertFrom_ShouldReturnExpectedResult(Type sourceType, bool expected) | ||
{ | ||
// Arrange | ||
var converter = new DataClassificationTypeConverter(); | ||
|
||
// Act | ||
var result = converter.CanConvertFrom(null, sourceType); | ||
|
||
// Assert | ||
result.Should().Be(expected); | ||
} | ||
|
||
[Theory] | ||
[InlineData(typeof(DataClassification), true)] | ||
[InlineData(typeof(int), false)] | ||
[InlineData(typeof(string), false)] | ||
public void CanConvertTo_ShouldReturnExpectedResult(Type destinationType, bool expected) | ||
{ | ||
// Arrange | ||
var converter = new DataClassificationTypeConverter(); | ||
|
||
// Act | ||
var result = converter.CanConvertTo(null, destinationType); | ||
|
||
// Assert | ||
result.Should().Be(expected); | ||
} | ||
|
||
[Theory] | ||
[InlineData("None", "", "None")] | ||
[InlineData("Unknown", "", "Unknown")] | ||
[InlineData("Example:Test", "Example", "Test")] | ||
public void ConvertFrom_ShouldReturnExpectedResult_ForValidInput(string input, string expectedTaxonomyName, string expectedValue) | ||
{ | ||
// Arrange | ||
var converter = new DataClassificationTypeConverter(); | ||
|
||
// Act | ||
var result = converter.ConvertFrom(null, null, input); | ||
|
||
// Assert | ||
result.Should().NotBeNull(); | ||
result.Should().BeOfType<DataClassification>(); | ||
|
||
#pragma warning disable CS8605 // Unboxing a possibly null value. | ||
var dataClassification = (DataClassification)result; | ||
#pragma warning restore CS8605 // Unboxing a possibly null value. | ||
|
||
dataClassification.TaxonomyName.Should().Be(expectedTaxonomyName); | ||
dataClassification.Value.Should().Be(expectedValue); | ||
} | ||
|
||
[Theory] | ||
[InlineData("InvalidFormat", typeof(FormatException))] | ||
[InlineData("InvalidFormat:", typeof(FormatException))] | ||
[InlineData(":InvalidFormat", typeof(FormatException))] | ||
[InlineData(":", typeof(FormatException))] | ||
[InlineData("", typeof(FormatException))] | ||
[InlineData("\t", typeof(FormatException))] | ||
[InlineData("\n", typeof(FormatException))] | ||
[InlineData(42, typeof(ArgumentException))] | ||
[InlineData(false, typeof(ArgumentException))] | ||
[InlineData(null, typeof(ArgumentException))] | ||
public void ConvertFrom_ShouldThrowException_ForInvalidInput(object? input, Type expectedException) | ||
{ | ||
// Arrange | ||
var converter = new DataClassificationTypeConverter(); | ||
|
||
// Act | ||
var act = () => converter.ConvertFrom(null, null, input!); | ||
|
||
// Assert | ||
Assert.Throws(expectedException, act); | ||
} | ||
|
||
[Theory] | ||
[InlineData("None", true)] | ||
[InlineData("Unknown", true)] | ||
[InlineData("Example:Test", true)] | ||
[InlineData("InvalidFormat", false)] | ||
[InlineData("InvalidFormat:", false)] | ||
[InlineData(":InvalidFormat", false)] | ||
[InlineData(":", false)] | ||
[InlineData("", false)] | ||
[InlineData("\t", false)] | ||
[InlineData("\n", false)] | ||
[InlineData(42, false)] | ||
[InlineData(false, false)] | ||
[InlineData(null, false)] | ||
public void IsValid_ShouldReturnExpectedResult(object? input, bool expected) | ||
{ | ||
// Arrange | ||
var converter = new DataClassificationTypeConverter(); | ||
|
||
// Act | ||
var result = converter.IsValid(null, input); | ||
|
||
// Assert | ||
result.Should().Be(expected); | ||
} | ||
|
||
private class TestOptions | ||
{ | ||
#pragma warning disable S3459 // Unassigned members should be removed | ||
#pragma warning disable S1144 // Unused private types or members should be removed | ||
public DataClassification? Example { get; set; } | ||
#pragma warning restore S1144 // Unused private types or members should be removed | ||
#pragma warning restore S3459 // Unassigned members should be removed | ||
public IDictionary<string, DataClassification> Facts { get; set; } = new Dictionary<string, DataClassification>(); | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.