예제 #1
0
        public async Task EncryptionResourceTokenAuth()
        {
            User user = EncryptionTests.databaseCore.GetUser(Guid.NewGuid().ToString());
            await EncryptionTests.databaseCore.CreateUserAsync(user.Id);

            PermissionProperties permission = await user.CreatePermissionAsync(
                new PermissionProperties(Guid.NewGuid().ToString(), PermissionMode.All, EncryptionTests.container));

            TestDoc testDoc = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            (string endpoint, string _) = TestCommon.GetAccountInfo();
            CosmosClient resourceTokenBasedClient = new CosmosClientBuilder(endpoint, permission.Token)
                                                    .WithEncryptionKeyWrapProvider(new TestKeyWrapProvider())
                                                    .Build();

            DatabaseCore databaseForTokenClient  = (DatabaseInlineCore)resourceTokenBasedClient.GetDatabase(EncryptionTests.databaseCore.Id);
            Container    containerForTokenClient = databaseForTokenClient.GetContainer(EncryptionTests.container.Id);

            await EncryptionTests.PerformForbiddenOperationAsync(() =>
                                                                 databaseForTokenClient.GetDataEncryptionKey(EncryptionTests.dekId).ReadAsync(), "DEK.ReadAsync");

            await EncryptionTests.PerformForbiddenOperationAsync(() =>
                                                                 containerForTokenClient.ReadItemAsync <TestDoc>(testDoc.Id, new PartitionKey(testDoc.PK)), "ReadItemAsync");

            await EncryptionTests.PerformForbiddenOperationAsync(() =>
                                                                 containerForTokenClient.ReadItemStreamAsync(testDoc.Id, new PartitionKey(testDoc.PK)), "ReadItemStreamAsync");
        }
예제 #2
0
        public async Task EncryptionBulkCrud()
        {
            TestDoc docToReplace = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            docToReplace.NonSensitive = Guid.NewGuid().ToString();
            docToReplace.Sensitive    = Guid.NewGuid().ToString();

            TestDoc docToUpsert = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            docToUpsert.NonSensitive = Guid.NewGuid().ToString();
            docToUpsert.Sensitive    = Guid.NewGuid().ToString();

            TestDoc docToDelete = await EncryptionTests.CreateItemAsync(EncryptionTests.containerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            (string endpoint, string authKey) = TestCommon.GetAccountInfo();
            CosmosClient clientWithBulk = new CosmosClientBuilder(endpoint, authKey)
                                          .WithEncryptionKeyWrapProvider(new TestKeyWrapProvider())
                                          .WithBulkExecution(true)
                                          .Build();

            DatabaseCore  databaseWithBulk  = (DatabaseInlineCore)clientWithBulk.GetDatabase(EncryptionTests.databaseCore.Id);
            ContainerCore containerWithBulk = (ContainerInlineCore)databaseWithBulk.GetContainer(EncryptionTests.container.Id);

            List <Task> tasks = new List <Task>();

            tasks.Add(EncryptionTests.CreateItemAsync(containerWithBulk, EncryptionTests.dekId, TestDoc.PathsToEncrypt));
            tasks.Add(EncryptionTests.UpsertItemAsync(containerWithBulk, TestDoc.Create(), EncryptionTests.dekId, TestDoc.PathsToEncrypt, HttpStatusCode.Created));
            tasks.Add(EncryptionTests.ReplaceItemAsync(containerWithBulk, docToReplace, EncryptionTests.dekId, TestDoc.PathsToEncrypt));
            tasks.Add(EncryptionTests.UpsertItemAsync(containerWithBulk, docToUpsert, EncryptionTests.dekId, TestDoc.PathsToEncrypt, HttpStatusCode.OK));
            tasks.Add(EncryptionTests.DeleteItemAsync(containerWithBulk, docToDelete));
            await Task.WhenAll(tasks);
        }
        public async Task EncryptionResourceTokenAuthRestricted()
        {
            TestDoc testDoc = await EncryptionTests.CreateItemAsync(EncryptionTests.itemContainerCore, EncryptionTests.dekId, TestDoc.PathsToEncrypt);

            User restrictedUser = EncryptionTests.databaseCore.GetUser(Guid.NewGuid().ToString());
            await EncryptionTests.databaseCore.CreateUserAsync(restrictedUser.Id);

            PermissionProperties restrictedUserPermission = await restrictedUser.CreatePermissionAsync(
                new PermissionProperties(Guid.NewGuid().ToString(), PermissionMode.All, EncryptionTests.itemContainer));

            CosmosDataEncryptionKeyProvider dekProvider = new CosmosDataEncryptionKeyProvider(new TestKeyWrapProvider());
            TestEncryptor encryptor = new TestEncryptor(dekProvider);

            (string endpoint, string _) = TestCommon.GetAccountInfo();
            CosmosClient clientForRestrictedUser = new CosmosClientBuilder(endpoint, restrictedUserPermission.Token)
                                                   .WithEncryptor(encryptor)
                                                   .Build();

            Database  databaseForRestrictedUser  = clientForRestrictedUser.GetDatabase(EncryptionTests.databaseCore.Id);
            Container containerForRestrictedUser = databaseForRestrictedUser.GetContainer(EncryptionTests.itemContainer.Id);

            await EncryptionTests.PerformForbiddenOperationAsync(() =>
                                                                 dekProvider.InitializeAsync(databaseForRestrictedUser, EncryptionTests.keyContainer.Id), "CosmosDekProvider.InitializeAsync");

            await EncryptionTests.PerformOperationOnUninitializedDekProviderAsync(() =>
                                                                                  dekProvider.DataEncryptionKeyContainer.ReadDataEncryptionKeyAsync(EncryptionTests.dekId), "DEK.ReadAsync");

            await EncryptionTests.PerformOperationOnUninitializedDekProviderAsync(() =>
                                                                                  containerForRestrictedUser.ReadItemAsync <TestDoc>(testDoc.Id, new PartitionKey(testDoc.PK)), "ReadItemAsync");

            await EncryptionTests.PerformOperationOnUninitializedDekProviderAsync(() =>
                                                                                  containerForRestrictedUser.ReadItemStreamAsync(testDoc.Id, new PartitionKey(testDoc.PK)), "ReadItemStreamAsync");
        }
예제 #4
0
        private async Task <Result> TestCosmosRead()
        {
            try
            {
                var cosmosClient = new CosmosClientBuilder(_configuration.GetConnectionString("Cosmos")).
                                   WithApplicationRegion(Regions.SouthCentralUS).
                                   WithThrottlingRetryOptions(TimeSpan.FromSeconds(5), 5).Build();

                var    db        = cosmosClient.GetDatabase("test");
                var    container = db.GetContainer("items");
                string fqdn      = cosmosClient.Endpoint.Host;
                var    entry     = Dns.GetHostEntry(fqdn);

                ItemResponse <Doc> readItemResponse = await container.ReadItemAsync <Doc>("5ae9ec8c-897b-4cd3-9529-14f47ff27ff3", new PartitionKey("5ae9ec8c-897b-4cd3-9529-14f47ff27ff3"));

                return(new Result()
                {
                    success = readItemResponse.StatusCode == System.Net.HttpStatusCode.OK,
                    serverName = "N/A",
                    endpointIPAddress = entry.AddressList.First().ToString(),
                    endpoint = fqdn
                });
            }
            catch (Exception ex)
            {
                return(new Result()
                {
                    serverName = ex.Message + ": " + ex.StackTrace,
                    success = false
                });
            }
        }
예제 #5
0
        public async Task <IEnumerable <Session> > GetSessionsAsync()
        {
            // Get session data from Azure Cosmos DB.
            var cosmosClient = new CosmosClientBuilder
                                   (GetDBConnectionString("AzureCosmosDB-ConnectionString-ReadOnly", Environment.GetEnvironmentVariable("VaultUri")))
                               .WithSerializerOptions(new CosmosSerializationOptions {
                Indented = true
            })
                               .Build();
            var container = cosmosClient.GetDatabase("SessionsData").GetContainer("SessionsContainer");

            var sqlQueryText  = "SELECT * FROM c";
            var queryIterator = container.GetItemQueryIterator <Session>(new QueryDefinition(sqlQueryText));

            // Fetch session data from data base.
            List <Session> sessions = new();

            //Asynchronous query execution
            while (queryIterator.HasMoreResults)
            {
                foreach (var item in await queryIterator.ReadNextAsync())
                {
                    sessions.Add(item);
                }
            }

            return(sessions);
        }
        private static async Task <Container> CosmosContainerFactory()
        {
            string connectionString  = "AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw==";
            var    serializerOptions = new CosmosSerializationOptions {
                PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
            };
            CosmosClient client = new CosmosClientBuilder(connectionString).WithSerializerOptions(serializerOptions).Build();

            await client.CreateDatabaseIfNotExistsAsync("UnitTesting");

            Database database = client.GetDatabase("UnitTesting");

            var containerProperties = new ContainerProperties(id: "Default", partitionKeyPath: "/id");
            await database.CreateContainerIfNotExistsAsync(containerProperties);

            return(database.GetContainer("Default"));
        }
예제 #7
0
        public static async Task Main(string[] args)
        {
            var configurationRoot = new ConfigurationBuilder()
                                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                                    .AddEnvironmentVariables()
                                    .Build();

            var client = new CosmosClientBuilder(configurationRoot["ZeroFrictionDatabaseConnectionString"])
                         .WithSerializerOptions(new CosmosSerializationOptions {
                PropertyNamingPolicy = CosmosPropertyNamingPolicy.CamelCase
            })
                         .Build();

            await client.CreateDatabaseIfNotExistsAsync("zerofriction");

            var database = client.GetDatabase("zerofriction");
            await database.CreateContainerIfNotExistsAsync("customers", "/tenantId");

            await database.CreateContainerIfNotExistsAsync("invoices", "/tenantId");
        }
 private Container ConnectToCosmosDBContainer(ICosmosDBAccount cosmosDB, string cosmosDBDatabase, string cosmosDBContainer)
 {
     try
     {
         var client = new CosmosClientBuilder(
             cosmosDB.DocumentEndpoint,
             cosmosDB.ListKeys().PrimaryMasterKey)
                      .Build();
         return(client
                .GetDatabase(cosmosDBDatabase)
                .GetContainer(cosmosDBContainer));
     }
     catch (Exception e)
     {
         this.logger.LogCritical(
             e,
             "Couldn't retrieve Cosmos DB container {cosmosDBContainer}",
             cosmosDBContainer);
         throw;
     }
 }
        public async Task EncryptionResourceTokenAuthAllowed()
        {
            User keyManagerUser = EncryptionTests.databaseCore.GetUser(Guid.NewGuid().ToString());
            await EncryptionTests.databaseCore.CreateUserAsync(keyManagerUser.Id);

            PermissionProperties keyManagerUserPermission = await keyManagerUser.CreatePermissionAsync(
                new PermissionProperties(Guid.NewGuid().ToString(), PermissionMode.All, EncryptionTests.keyContainer));

            CosmosDataEncryptionKeyProvider dekProvider = new CosmosDataEncryptionKeyProvider(new TestKeyWrapProvider());
            TestEncryptor encryptor = new TestEncryptor(dekProvider);

            (string endpoint, string _) = TestCommon.GetAccountInfo();
            CosmosClient clientForKeyManagerUser = new CosmosClientBuilder(endpoint, keyManagerUserPermission.Token)
                                                   .WithEncryptor(encryptor)
                                                   .Build();

            Database databaseForKeyManagerUser = clientForKeyManagerUser.GetDatabase(EncryptionTests.databaseCore.Id);

            await dekProvider.InitializeAsync(databaseForKeyManagerUser, EncryptionTests.keyContainer.Id);

            DataEncryptionKeyProperties readDekProperties = await dekProvider.DataEncryptionKeyContainer.ReadDataEncryptionKeyAsync(EncryptionTests.dekId);

            Assert.AreEqual(EncryptionTests.dekProperties, readDekProperties);
        }