Skip to content
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

[Client encryption]: Adds Stream based processor #4806

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
91 commits
Select commit Hold shift + click to select a range
d6f89ea
Add baseline benchmarks for `Microsoft.Azure.Cosmos.Encryption.Custom`
juraj-blazek Sep 12, 2024
8928b88
Cleanup
juraj-blazek Sep 12, 2024
9dc7d54
Use set of static test data for benchmarks
juraj-blazek Sep 12, 2024
368dc25
Merge branch 'master' into users/juraj-blazek/encryption-benchmark-ba…
juraj-blazek Sep 12, 2024
38a198a
Add non-allocating APIs to encryptors
juraj-blazek Sep 16, 2024
e0bb8bf
WIP
juraj-blazek Sep 16, 2024
9c3c276
Revert solution update
juraj-blazek Sep 16, 2024
c37a092
Merge branch 'users/juraj-blazek/encryption-benchmark-baseline' of ht…
juraj-blazek Sep 16, 2024
f4db1c6
Merge branch 'master' into users/juraj-blazek/encryption-benchmark-ba…
juraj-blazek Sep 16, 2024
91714f9
Merge branch 'master' into users/juraj-blazek/encryption-benchmark-ba…
juraj-blazek Sep 17, 2024
2058f8b
Merge remote-tracking branch 'origin/master' into users/juraj-blazek/…
juraj-blazek Sep 17, 2024
f33538c
Add implementation, fix tests
juraj-blazek Sep 17, 2024
6923fd2
Switch to randomized encryption for benchmarks
juraj-blazek Sep 17, 2024
4ea8690
Merge branch 'master' into users/juraj-blazek/encryption-benchmark-ba…
kr-santosh Sep 18, 2024
03ef682
Some more array pooling
juraj-blazek Sep 17, 2024
1044a89
Streaming deserialization
juraj-blazek Sep 19, 2024
f1db54d
Merge remote-tracking branch 'origin/master' into users/juraj-blazek/…
juraj-blazek Sep 19, 2024
05bfc50
Cleanup
juraj-blazek Sep 20, 2024
5629f74
Update MDE and rerun benchmarks
juraj-blazek Sep 20, 2024
495d2c4
Add non-allocating APIs to encryptors
juraj-blazek Sep 16, 2024
b3f74b1
Merge branch 'master' into users/juraj-blazek/non-allocating-encryptor
Sep 30, 2024
14bce37
~ drop repeated DEK calls
Sep 30, 2024
4ff1601
! typo
Sep 30, 2024
d8a345c
~ update benchmark
Sep 30, 2024
03c06e0
~ fix tests
Sep 30, 2024
a1025c4
Merge branch 'Azure:master' into users/juraj-blazek/non-allocating-en…
JanHyka Oct 1, 2024
3bf77c8
~ cleanup
Oct 1, 2024
ceaa8b5
+ refresh benchmark
Oct 1, 2024
611b3ac
+ unit test
Oct 1, 2024
9ca89d4
~ merge predecessor PR
Oct 1, 2024
8a78fe8
~ merge fixes and initial cleanup
Oct 1, 2024
8ed2135
~ write directly to output document instead of copying
Oct 1, 2024
bbe9845
! tests
Oct 1, 2024
a107f62
~ retrieve DataEncryptionKey only once per document
Oct 1, 2024
a1ad02b
! fix tests
Oct 1, 2024
4f2f072
~ update Aes algorithm to reuse GetEncryptedByteCount
Oct 2, 2024
cbbeee2
~ refactor EncryptionProcessor
Oct 4, 2024
b6c851c
! names
Oct 4, 2024
72ccae7
~ less static
Oct 4, 2024
8ea5879
Merge branch 'master' into users/juraj-blazek/encryption-array-pooling
Oct 6, 2024
8c60e69
Merge branch 'master' into users/juraj-blazek/encryption-array-pooling
Oct 6, 2024
5554aa0
~ merge fixes
Oct 6, 2024
28620ed
~ cleanup
Oct 6, 2024
eb059c8
~ unwanted changes
Oct 6, 2024
cc2eab5
- unused method
Oct 6, 2024
c9ba300
~ updates (PR)
Oct 6, 2024
9f9cbca
~ add stable vs preview release duplicity
Oct 7, 2024
c347e71
Merge branch 'users/juraj-blazek/encryption-array-pooling' into users…
Oct 7, 2024
64172b8
~ cleanup and parent branch merge
Oct 7, 2024
ff583f9
Merge branch 'master' into users/jan-hyka/refactor-encryption-processor
Oct 7, 2024
0ba8c34
Merge branch 'master' into users/jan-hyka/refactor-encryption-processor
Oct 7, 2024
326b1be
~ master merges
Oct 7, 2024
c520e16
- duplicate
Oct 7, 2024
5c40821
~ cleanup
Oct 7, 2024
99c7a75
+ Add .NET8.0 target for Cosmos.Encryption.Custom
Oct 8, 2024
31c20e7
- remove implicit IsPreview from csproj
Oct 8, 2024
90b2cec
+ JsonNodeSqlSerializer
Oct 9, 2024
6f27d9d
+ initial commit
Oct 9, 2024
d7c06d6
! EncryptioProperties System.Text.Json annotations
Oct 9, 2024
cb9d166
+ bump benchmark
Oct 9, 2024
5fc5165
~ wip
Oct 9, 2024
c9e7f30
+ initial for JsonNode decryption
Oct 9, 2024
9215f67
~ Merge branch 'master' into users/jan-hyka/jsonnode_serializer
Oct 10, 2024
fed6a3a
~ polishing and benchmark refresh
Oct 10, 2024
38cc928
- remove explicit System.Text.Json 8.0.5
Oct 10, 2024
ba4f73b
Merge branch 'users/jan-hyka/jsonnode_serializer' into users/jan-hyka…
Oct 10, 2024
424028c
Merge branch 'master' into users/jan-hyka/jsonnode_encryptionProcessor
Oct 10, 2024
2af9ddb
~ propagate changes from master
Oct 10, 2024
30c18d0
Merge branch 'users/jan-hyka/jsonnode_encryptionProcessor' into users…
Oct 10, 2024
54b0ad9
~ fixes for preview x non-preview branching
Oct 10, 2024
69c8978
Merge branch 'master' into users/jan-hyka/jsonnode_encryptionProcessor
JanHyka Oct 11, 2024
ad15ceb
+ tests
Oct 11, 2024
a0ccd44
Merge branch 'master' into users/jan-hyka/jsonnode_encryptionProcessor
Oct 13, 2024
d9c315d
~ complete merge from master & update benchmark
Oct 13, 2024
b11db28
Merge branch 'users/jan-hyka/jsonnode_encryptionProcessor' into users…
Oct 13, 2024
996252b
+ initial
Oct 14, 2024
758e98d
+ tests, fixes and benchmark
Oct 14, 2024
420a35d
! bugfix
Oct 14, 2024
d08be05
~ benchmark update
Oct 14, 2024
0bf29b8
+ cleanup
Oct 15, 2024
2b2209f
+ stream serializer
Oct 15, 2024
f03c92d
Merge branch 'master' into users/jan-hyka/stream_deserializer
Oct 15, 2024
42462d5
~ preview branching fixes
Oct 15, 2024
703830f
+ add support for Stream deserialization of obsoleted encryption algo…
Oct 15, 2024
4319524
~ final touches
Oct 16, 2024
940d667
Merge branch 'master' into users/jan-hyka/stream_deserializer
Oct 17, 2024
fa0020c
~ PR based changes
Oct 18, 2024
8e45769
Merge branch 'master' into users/jan-hyka/stream_deserializer
kirankumarkolli Oct 18, 2024
6bd6fee
Merge branch 'master' into users/jan-hyka/stream_deserializer
kirankumarkolli Oct 23, 2024
ca5b1aa
~ alter StreamProcessor.TransformDecryptProperty to local method
Oct 23, 2024
4c9c75c
Merge branch 'users/jan-hyka/stream_deserializer' of https://github.c…
Oct 23, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ internal static async Task<DecryptionContext> DecryptContentAsync(
{
_ = diagnosticsContext;

if (encryptionProperties.EncryptionFormatVersion != 2)
if (encryptionProperties.EncryptionFormatVersion != EncryptionFormatVersion.AeAes)
{
throw new NotSupportedException($"Unknown encryption format version: {encryptionProperties.EncryptionFormatVersion}. Please upgrade your SDK to the latest version.");
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------

namespace Microsoft.Azure.Cosmos.Encryption.Custom
{
internal static class EncryptionFormatVersion
{
public const int AeAes = 2;
public const int Mde = 3;
public const int MdeWithCompression = 4;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,18 @@ public enum JsonProcessor
/// </summary>
Newtonsoft,

#if NET8_0_OR_GREATER
#if ENCRYPTION_CUSTOM_PREVIEW && NET8_0_OR_GREATER
/// <summary>
/// System.Text.Json
/// </summary>
/// <remarks>Available with .NET8.0 package only.</remarks>
SystemTextJson,

/// <summary>
/// Ut8JsonReader/Writer
/// </summary>
/// <remarks>Available with .NET8.0 package only.</remarks>
Stream,
kirankumarkolli marked this conversation as resolved.
Show resolved Hide resolved
#endif
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@
namespace Microsoft.Azure.Cosmos.Encryption.Custom
{
using System;
using System.Collections.Generic;
using System.Linq;

internal static class EncryptionOptionsExtensions
{
Expand All @@ -31,6 +33,24 @@ internal static void Validate(this EncryptionOptions options)
#pragma warning restore CA2208 // Instantiate argument exceptions correctly
}

if (options.PathsToEncrypt is not HashSet<string> && options.PathsToEncrypt.Distinct().Count() != options.PathsToEncrypt.Count())
{
throw new InvalidOperationException("Duplicate paths in PathsToEncrypt passed via EncryptionOptions.");
}

foreach (string path in options.PathsToEncrypt)
{
if (string.IsNullOrWhiteSpace(path) || path[0] != '/' || path.IndexOf('/', 1) != -1)
{
throw new InvalidOperationException($"Invalid path {path ?? string.Empty}, {nameof(options.PathsToEncrypt)}");
}

if (path.AsSpan(1).Equals("id".AsSpan(), StringComparison.Ordinal))
{
throw new InvalidOperationException($"{nameof(options.PathsToEncrypt)} includes a invalid path: '{path}'.");
}
}

options.CompressionOptions?.Validate();
}

Expand Down
159 changes: 141 additions & 18 deletions Microsoft.Azure.Cosmos.Encryption.Custom/src/EncryptionProcessor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ internal static class EncryptionProcessor

#if ENCRYPTION_CUSTOM_PREVIEW && NET8_0_OR_GREATER
private static readonly JsonWriterOptions JsonWriterOptions = new () { SkipValidation = true };
private static readonly StreamProcessor StreamProcessor = new ();
#endif

private static readonly MdeEncryptionProcessor MdeEncryptionProcessor = new ();
Expand Down Expand Up @@ -62,24 +63,6 @@ public static async Task<Stream> EncryptAsync(
return input;
}

if (encryptionOptions.PathsToEncrypt.Distinct().Count() != encryptionOptions.PathsToEncrypt.Count())
{
throw new InvalidOperationException("Duplicate paths in PathsToEncrypt passed via EncryptionOptions.");
}

foreach (string path in encryptionOptions.PathsToEncrypt)
{
if (string.IsNullOrWhiteSpace(path) || path[0] != '/' || path.IndexOf('/', 1) != -1)
{
throw new InvalidOperationException($"Invalid path {path ?? string.Empty}, {nameof(encryptionOptions.PathsToEncrypt)}");
}

if (path.AsSpan(1).Equals("id".AsSpan(), StringComparison.Ordinal))
{
throw new InvalidOperationException($"{nameof(encryptionOptions.PathsToEncrypt)} includes a invalid path: '{path}'.");
}
}

#pragma warning disable CS0618 // Type or member is obsolete
return encryptionOptions.EncryptionAlgorithm switch
{
Expand All @@ -90,6 +73,42 @@ public static async Task<Stream> EncryptAsync(
#pragma warning restore CS0618 // Type or member is obsolete
}

#if ENCRYPTION_CUSTOM_PREVIEW && NET8_0_OR_GREATER
public static async Task EncryptAsync(
Stream input,
Stream output,
Encryptor encryptor,
EncryptionOptions encryptionOptions,
CosmosDiagnosticsContext diagnosticsContext,
CancellationToken cancellationToken)
{
_ = diagnosticsContext;

ValidateInputForEncrypt(
input,
encryptor,
encryptionOptions);

if (!encryptionOptions.PathsToEncrypt.Any())
{
await input.CopyToAsync(output, cancellationToken);
return;
}

if (encryptionOptions.EncryptionAlgorithm != CosmosEncryptionAlgorithm.MdeAeadAes256CbcHmac256Randomized)
{
throw new NotSupportedException($"Streaming mode is only allowed for {nameof(CosmosEncryptionAlgorithm.MdeAeadAes256CbcHmac256Randomized)}");
}

if (encryptionOptions.JsonProcessor != JsonProcessor.Stream)
{
throw new NotSupportedException($"Streaming mode is only allowed for {nameof(JsonProcessor.Stream)}");
}

await EncryptionProcessor.StreamProcessor.EncryptStreamAsync(input, output, encryptor, encryptionOptions, cancellationToken);
}
#endif

/// <remarks>
/// If there isn't any data that needs to be decrypted, input stream will be returned without any modification.
/// Else input stream will be disposed, and a new stream is returned.
Expand Down Expand Up @@ -140,11 +159,76 @@ public static async Task<Stream> EncryptAsync(
JsonProcessor.Newtonsoft => await DecryptAsync(input, encryptor, diagnosticsContext, cancellationToken),
#if ENCRYPTION_CUSTOM_PREVIEW && NET8_0_OR_GREATER
JsonProcessor.SystemTextJson => await DecryptJsonNodeAsync(input, encryptor, diagnosticsContext, cancellationToken),
JsonProcessor.Stream => await DecryptStreamAsync(input, encryptor, diagnosticsContext, cancellationToken),
#endif
_ => throw new InvalidOperationException("Unsupported Json Processor")
};
}

#if ENCRYPTION_CUSTOM_PREVIEW && NET8_0_OR_GREATER
public static async Task<DecryptionContext> DecryptAsync(
Stream input,
Stream output,
Encryptor encryptor,
CosmosDiagnosticsContext diagnosticsContext,
JsonProcessor jsonProcessor,
CancellationToken cancellationToken)
{
if (input == null)
{
return null;
}

if (jsonProcessor != JsonProcessor.Stream)
JanHyka marked this conversation as resolved.
Show resolved Hide resolved
{
throw new NotSupportedException($"Streaming mode is only allowed for {nameof(JsonProcessor.Stream)}");
}

Debug.Assert(input.CanSeek);
Debug.Assert(output.CanWrite);
Debug.Assert(output.CanSeek);
Debug.Assert(encryptor != null);
Debug.Assert(diagnosticsContext != null);
input.Position = 0;

EncryptionPropertiesWrapper properties = await System.Text.Json.JsonSerializer.DeserializeAsync<EncryptionPropertiesWrapper>(input, cancellationToken: cancellationToken);
input.Position = 0;
if (properties?.EncryptionProperties == null)
{
await input.CopyToAsync(output, cancellationToken: cancellationToken);
return null;
}

DecryptionContext context;
#pragma warning disable CS0618 // Type or member is obsolete
if (properties.EncryptionProperties.EncryptionAlgorithm == CosmosEncryptionAlgorithm.MdeAeadAes256CbcHmac256Randomized)
{
context = await StreamProcessor.DecryptStreamAsync(input, output, encryptor, properties.EncryptionProperties, diagnosticsContext, cancellationToken);
}
else if (properties.EncryptionProperties.EncryptionAlgorithm == CosmosEncryptionAlgorithm.AEAes256CbcHmacSha256Randomized)
{
(Stream stream, context) = await DecryptAsync(input, encryptor, diagnosticsContext, cancellationToken);
await stream.CopyToAsync(output, cancellationToken);
output.Position = 0;
}
else
{
input.Position = 0;
throw new NotSupportedException($"Encryption Algorithm: {properties.EncryptionProperties.EncryptionAlgorithm} is not supported.");
}
#pragma warning restore CS0618 // Type or member is obsolete

if (context == null)
{
input.Position = 0;
return null;
}

await input.DisposeAsync();
return context;
}
#endif

#if ENCRYPTION_CUSTOM_PREVIEW && NET8_0_OR_GREATER
public static async Task<(Stream, DecryptionContext)> DecryptJsonNodeAsync(
Stream input,
Expand Down Expand Up @@ -182,6 +266,45 @@ public static async Task<Stream> EncryptAsync(
}
#endif

#if ENCRYPTION_CUSTOM_PREVIEW && NET8_0_OR_GREATER
public static async Task<(Stream, DecryptionContext)> DecryptStreamAsync(
Stream input,
Encryptor encryptor,
CosmosDiagnosticsContext diagnosticsContext,
CancellationToken cancellationToken)
{
if (input == null)
{
return (input, null);
}

Debug.Assert(input.CanSeek);
Debug.Assert(encryptor != null);
Debug.Assert(diagnosticsContext != null);
input.Position = 0;

EncryptionPropertiesWrapper properties = await System.Text.Json.JsonSerializer.DeserializeAsync<EncryptionPropertiesWrapper>(input, cancellationToken: cancellationToken);
input.Position = 0;
if (properties?.EncryptionProperties == null)
{
return (input, null);
}

MemoryStream ms = new ();

DecryptionContext context = await StreamProcessor.DecryptStreamAsync(input, ms, encryptor, properties.EncryptionProperties, diagnosticsContext, cancellationToken);
if (context == null)
{
input.Position = 0;
return (input, null);
}

await input.DisposeAsync();
return (ms, context);
}

#endif

public static async Task<(JObject, DecryptionContext)> DecryptAsync(
JObject document,
Encryptor encryptor,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// ------------------------------------------------------------

namespace Microsoft.Azure.Cosmos.Encryption.Custom
{
using System.Text.Json.Serialization;

internal class EncryptionPropertiesWrapper
kirankumarkolli marked this conversation as resolved.
Show resolved Hide resolved
{
[JsonPropertyName(Constants.EncryptedInfo)]
public EncryptionProperties EncryptionProperties { get; }

public EncryptionPropertiesWrapper(EncryptionProperties encryptionProperties)
{
this.EncryptionProperties = encryptionProperties;
}
}
}
Loading