Skip to content

Commit

Permalink
[Client encryption]: Add .NET8.0 target (#4766)
Browse files Browse the repository at this point in the history
# Pull Request Template

## Description

- This is preliminary step to enable Brotli compression on
Cosmos.Encryption.Custom.
- .NET8.0 target was added to the project
- New compiler complaints were addressed

To be processed after #4757 

## Type of change

Please delete options that are not relevant.

- [] New feature (non-breaking change which adds functionality)

## Closing issues

Contributes to #4678

---------

Co-authored-by: Juraj Blazek <[email protected]>
Co-authored-by: juraj-blazek <[email protected]>
Co-authored-by: Santosh Kulkarni <[email protected]>
  • Loading branch information
4 people authored Oct 9, 2024
1 parent 2b0a021 commit 01c6218
Show file tree
Hide file tree
Showing 28 changed files with 161 additions and 48 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@ namespace Microsoft.Azure.Cosmos.Encryption.Custom
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

#pragma warning disable IDE0057 // Use range operator
#pragma warning disable VSTHRD103 // Call async methods when in an async method
internal static class AeAesEncryptionProcessor
{
public static async Task<Stream> EncryptAsync(
Expand Down Expand Up @@ -65,6 +67,7 @@ public static async Task<Stream> EncryptAsync(
encryptionOptions.PathsToEncrypt);

itemJObj.Add(Constants.EncryptedInfo, JObject.FromObject(encryptionProperties));

input.Dispose();
return EncryptionProcessor.BaseSerializer.ToStream(itemJObj);
}
Expand Down Expand Up @@ -113,4 +116,7 @@ internal static async Task<DecryptionContext> DecryptContentAsync(
return decryptionContext;
}
}

#pragma warning restore IDE0057 // Use range operator
#pragma warning restore VSTHRD103 // Call async methods when in an async method
}
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ namespace Microsoft.Azure.Cosmos.Encryption.Custom
using System.IO;
using System.Security.Cryptography;

#pragma warning disable SYSLIB0021 // Type or member is obsolete

/// <summary>
/// This class implements authenticated encryption algorithm with associated data as described in
/// http://tools.ietf.org/html/draft-mcgrew-aead-aes-cbc-hmac-sha2-05 - specifically this implements
Expand Down Expand Up @@ -483,4 +485,6 @@ private static int GetCipherTextLength(int inputSize)
return ((inputSize / BlockSizeInBytes) + 1) * BlockSizeInBytes;
}
}

#pragma warning restore SYSLIB0021 // Type or member is obsolete
}
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,14 @@ internal CosmosJsonDotNetSerializer(JsonSerializerSettings jsonSerializerSetting
/// <returns>The object representing the deserialized stream</returns>
public T FromStream<T>(Stream stream)
{
#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(stream);
#else
if (stream == null)
{
throw new ArgumentNullException(nameof(stream));
}
#endif

if (typeof(Stream).IsAssignableFrom(typeof(T)))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,14 @@ public async Task InitializeAsync(
throw new InvalidOperationException($"{nameof(CosmosDataEncryptionKeyProvider)} has already been initialized.");
}

#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(database);
#else
if (database == null)
{
throw new ArgumentNullException(nameof(database));
}
#endif

ContainerResponse containerResponse = await database.CreateContainerIfNotExistsAsync(
containerId,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,14 @@ public static DataEncryptionKey Create(
byte[] rawKey,
string encryptionAlgorithm)
{
#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(rawKey);
#else
if (rawKey == null)
{
throw new ArgumentNullException(nameof(rawKey));
}
#endif

#pragma warning disable CS0618 // Type or member is obsolete
if (!string.Equals(encryptionAlgorithm, CosmosEncryptionAlgorithm.AEAes256CbcHmacSha256Randomized))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,14 @@ public override async Task<ItemResponse<DataEncryptionKeyProperties>> CreateData
throw new ArgumentException(string.Format("Unsupported Encryption Algorithm {0}", encryptionAlgorithm), nameof(encryptionAlgorithm));
}

#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(encryptionKeyWrapMetadata);
#else
if (encryptionKeyWrapMetadata == null)
{
throw new ArgumentNullException(nameof(encryptionKeyWrapMetadata));
}
#endif

CosmosDiagnosticsContext diagnosticsContext = CosmosDiagnosticsContext.Create(requestOptions);

Expand Down Expand Up @@ -155,10 +159,14 @@ public override async Task<ItemResponse<DataEncryptionKeyProperties>> RewrapData
ItemRequestOptions requestOptions = null,
CancellationToken cancellationToken = default)
{
#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(newWrapMetadata);
#else
if (newWrapMetadata == null)
{
throw new ArgumentNullException(nameof(newWrapMetadata));
}
#endif

CosmosDiagnosticsContext diagnosticsContext = CosmosDiagnosticsContext.Create(requestOptions);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,14 @@ public override Task<ItemResponse<DataEncryptionKeyProperties>> RewrapDataEncryp
throw new ArgumentNullException(nameof(id));
}

#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(newWrapMetadata);
#else
if (newWrapMetadata == null)
{
throw new ArgumentNullException(nameof(newWrapMetadata));
}
#endif

return TaskHelper.RunInlineIfNeededAsync(() =>
this.dataEncryptionKeyContainerCore.RewrapDataEncryptionKeyAsync(id, newWrapMetadata, encryptionAlgorithm, requestOptions, cancellationToken));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace Microsoft.Azure.Cosmos.Encryption.Custom

internal sealed class DataEncryptionKeyFeedIterator<T> : FeedIterator<T>
{
private readonly FeedIterator feedIterator;
private readonly DataEncryptionKeyFeedIterator feedIterator;
private readonly CosmosResponseFactory responseFactory;

public DataEncryptionKeyFeedIterator(
Expand Down Expand Up @@ -57,7 +57,7 @@ public override async Task<FeedResponse<T>> ReadNextAsync(CancellationToken canc

if (responseMessage.IsSuccessStatusCode && responseMessage.Content != null)
{
dataEncryptionKeyPropertiesList = this.ConvertResponseToDataEncryptionKeyPropertiesList(
dataEncryptionKeyPropertiesList = DataEncryptionKeyFeedIterator<T>.ConvertResponseToDataEncryptionKeyPropertiesList(
responseMessage.Content);

return (responseMessage, dataEncryptionKeyPropertiesList);
Expand All @@ -67,7 +67,7 @@ public override async Task<FeedResponse<T>> ReadNextAsync(CancellationToken canc
}
}

private List<T> ConvertResponseToDataEncryptionKeyPropertiesList(
private static List<T> ConvertResponseToDataEncryptionKeyPropertiesList(
Stream content)
{
JObject contentJObj = EncryptionProcessor.BaseSerializer.FromStream<JObject>(content);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,14 @@ internal static DecryptableFeedResponse<T> CreateResponse(
ResponseMessage responseMessage,
IReadOnlyCollection<T> resource)
{
#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(responseMessage);
#else
if (responseMessage == null)
{
throw new ArgumentNullException(nameof(responseMessage));
}
#endif

using (responseMessage)
{
Expand Down
28 changes: 18 additions & 10 deletions Microsoft.Azure.Cosmos.Encryption.Custom/src/EncryptionContainer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,10 +122,14 @@ public override async Task<ResponseMessage> CreateItemStreamAsync(
ItemRequestOptions requestOptions = null,
CancellationToken cancellationToken = default)
{
#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(streamPayload);
#else
if (streamPayload == null)
{
throw new ArgumentNullException(nameof(streamPayload));
}
#endif

CosmosDiagnosticsContext diagnosticsContext = CosmosDiagnosticsContext.Create(requestOptions);
using (diagnosticsContext.CreateScope("CreateItemStream"))
Expand Down Expand Up @@ -304,6 +308,10 @@ public override async Task<ItemResponse<T>> ReplaceItemAsync<T>(
ItemRequestOptions requestOptions = null,
CancellationToken cancellationToken = default)
{
#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(id);
ArgumentNullException.ThrowIfNull(item);
#else
if (id == null)
{
throw new ArgumentNullException(nameof(id));
Expand All @@ -313,6 +321,7 @@ public override async Task<ItemResponse<T>> ReplaceItemAsync<T>(
{
throw new ArgumentNullException(nameof(item));
}
#endif

if (requestOptions is not EncryptionItemRequestOptions encryptionItemRequestOptions ||
encryptionItemRequestOptions.EncryptionOptions == null)
Expand Down Expand Up @@ -384,6 +393,10 @@ public override async Task<ResponseMessage> ReplaceItemStreamAsync(
ItemRequestOptions requestOptions = null,
CancellationToken cancellationToken = default)
{
#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(id);
ArgumentNullException.ThrowIfNull(streamPayload);
#else
if (id == null)
{
throw new ArgumentNullException(nameof(id));
Expand All @@ -393,6 +406,7 @@ public override async Task<ResponseMessage> ReplaceItemStreamAsync(
{
throw new ArgumentNullException(nameof(streamPayload));
}
#endif

CosmosDiagnosticsContext diagnosticsContext = CosmosDiagnosticsContext.Create(requestOptions);
using (diagnosticsContext.CreateScope("ReplaceItemStream"))
Expand Down Expand Up @@ -428,11 +442,6 @@ private async Task<ResponseMessage> ReplaceItemHelperAsync(
cancellationToken);
}

if (partitionKey == null)
{
throw new NotSupportedException($"{nameof(partitionKey)} cannot be null for operations using {nameof(EncryptionContainer)}.");
}

streamPayload = await EncryptionProcessor.EncryptAsync(
streamPayload,
this.Encryptor,
Expand Down Expand Up @@ -536,10 +545,14 @@ public override async Task<ResponseMessage> UpsertItemStreamAsync(
ItemRequestOptions requestOptions = null,
CancellationToken cancellationToken = default)
{
#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(streamPayload);
#else
if (streamPayload == null)
{
throw new ArgumentNullException(nameof(streamPayload));
}
#endif

CosmosDiagnosticsContext diagnosticsContext = CosmosDiagnosticsContext.Create(requestOptions);
using (diagnosticsContext.CreateScope("UpsertItemStream"))
Expand Down Expand Up @@ -572,11 +585,6 @@ private async Task<ResponseMessage> UpsertItemHelperAsync(
cancellationToken);
}

if (partitionKey == null)
{
throw new NotSupportedException($"{nameof(partitionKey)} cannot be null for operations using {nameof(EncryptionContainer)}.");
}

streamPayload = await EncryptionProcessor.EncryptAsync(
streamPayload,
this.Encryptor,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ namespace Microsoft.Azure.Cosmos.Encryption.Custom

internal static class EncryptionExceptionFactory
{
#pragma warning disable CA2208 // Instantiate argument exceptions correctly
internal static ArgumentException InvalidKeySize(string algorithmName, int actualKeylength, int expectedLength)
{
return new ArgumentException(
Expand All @@ -28,6 +29,7 @@ internal static ArgumentException InvalidAlgorithmVersion(byte actual, byte expe
$"Invalid encryption algorithm version; actual: {actual:X2}, expected: {expected:X2}.",
"cipherText");
}
#pragma warning restore CA2208 // Instantiate argument exceptions correctly

internal static ArgumentException InvalidAuthenticationTag()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ namespace Microsoft.Azure.Cosmos.Encryption.Custom

internal sealed class EncryptionFeedIterator<T> : FeedIterator<T>
{
private readonly FeedIterator feedIterator;
private readonly EncryptionFeedIterator feedIterator;
private readonly CosmosResponseFactory responseFactory;

public EncryptionFeedIterator(
Expand All @@ -31,8 +31,7 @@ public override async Task<FeedResponse<T>> ReadNextAsync(CancellationToken canc
if (typeof(T) == typeof(DecryptableItem))
{
IReadOnlyCollection<T> resource;
EncryptionFeedIterator encryptionFeedIterator = this.feedIterator as EncryptionFeedIterator;
(responseMessage, resource) = await encryptionFeedIterator.ReadNextWithoutDecryptionAsync<T>(cancellationToken);
(responseMessage, resource) = await this.feedIterator.ReadNextWithoutDecryptionAsync<T>(cancellationToken);

return DecryptableFeedResponse<T>.CreateResponse(
responseMessage,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,18 +114,5 @@ public bool Equals(EncryptionKeyWrapMetadata other)
this.Value == other.Value &&
this.Name == other.Name;
}

internal string GetName(EncryptionKeyWrapMetadata encryptionKeyWrapMetadata)
{
/* A legacy DEK may not have a Name value in meta-data*/
if (string.IsNullOrWhiteSpace(encryptionKeyWrapMetadata.Name))
{
return encryptionKeyWrapMetadata.Value;
}
else
{
return encryptionKeyWrapMetadata.Name;
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,11 @@ public static async Task<Stream> EncryptAsync(
}

DecryptionContext decryptionContext = await DecryptInternalAsync(encryptor, diagnosticsContext, itemJObj, encryptionPropertiesJObj, cancellationToken);
#if NET8_0_OR_GREATER
await input.DisposeAsync();
#else
input.Dispose();
#endif
return (BaseSerializer.ToStream(itemJObj), decryptionContext);
}

Expand Down Expand Up @@ -181,6 +185,11 @@ private static void ValidateInputForEncrypt(
Encryptor encryptor,
EncryptionOptions encryptionOptions)
{
#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(input);
ArgumentNullException.ThrowIfNull(encryptor);
ArgumentNullException.ThrowIfNull(encryptionOptions);
#else
if (input == null)
{
throw new ArgumentNullException(nameof(input));
Expand All @@ -195,7 +204,9 @@ private static void ValidateInputForEncrypt(
{
throw new ArgumentNullException(nameof(encryptionOptions));
}
#endif

#pragma warning disable CA2208 // Instantiate argument exceptions correctly
if (string.IsNullOrWhiteSpace(encryptionOptions.DataEncryptionKeyId))
{
throw new ArgumentNullException(nameof(encryptionOptions.DataEncryptionKeyId));
Expand All @@ -210,6 +221,7 @@ private static void ValidateInputForEncrypt(
{
throw new ArgumentNullException(nameof(encryptionOptions.PathsToEncrypt));
}
#pragma warning restore CA2208 // Instantiate argument exceptions correctly
}

private static JObject RetrieveItem(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ public MdeEncryptionAlgorithm(
TimeSpan? cacheTimeToLive,
bool withRawKey = false)
{
#if NET8_0_OR_GREATER
ArgumentNullException.ThrowIfNull(dekProperties);
ArgumentNullException.ThrowIfNull(encryptionKeyStoreProvider);
#else
if (dekProperties == null)
{
throw new ArgumentNullException(nameof(dekProperties));
Expand All @@ -43,6 +47,7 @@ public MdeEncryptionAlgorithm(
{
throw new ArgumentNullException(nameof(encryptionKeyStoreProvider));
}
#endif

KeyEncryptionKey keyEncryptionKey = KeyEncryptionKey.GetOrCreate(
dekProperties.EncryptionKeyWrapMetadata.Name,
Expand Down
Loading

0 comments on commit 01c6218

Please sign in to comment.