Esempio n. 1
0
        public void FindAService()
        {
            var identity = new CloudIdentity {
                Username = "******", APIKey = "{api-key}"
            };
            IIdentityProvider identityProvider = new CloudIdentityProvider(identity);
            var service = new ContentDeliveryNetworkService(identityProvider, "DFW");

            IPage <Service> currentPage = service.ListServices();

            Service myService;

            do
            {
                myService = currentPage.FirstOrDefault(x => x.Name == "MyService");
                if (myService != null)
                {
                    break;
                }

                currentPage = currentPage.GetNextPage();
            } while (currentPage.Any());

            if (myService == null)
            {
                Console.Error.WriteLine("Could not find MyService!");
                return;
            }

            Console.WriteLine("MyService: {0}", myService.Status);
        }
        public async void TestExecuteGetListDatabaseVulnerabilityAssessmentScans()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                string testPrefix = "sqlvulnerabilityassessmentscantest-";

                ResourceGroup       resourceGroup = context.CreateResourceGroup();
                SqlManagementClient sqlClient     = context.GetClient <SqlManagementClient>();
                Server server = context.CreateServer(resourceGroup);

                // Create database
                //
                string dbName = SqlManagementTestUtilities.GenerateName(testPrefix);
                var    db1    = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database()
                {
                    Location = server.Location,
                });
                Assert.NotNull(db1);

                // Turn ON database threat detection as a prerequisite to use VA
                DatabaseSecurityAlertPolicy updatedDatabasePolicy = new DatabaseSecurityAlertPolicy
                {
                    State = SecurityAlertPolicyState.Enabled,
                    EmailAccountAdmins = SecurityAlertPolicyEmailAccountAdmins.Enabled
                };
                sqlClient.DatabaseThreatDetectionPolicies.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, updatedDatabasePolicy);

                // Set policy
                await SetPolicy(context, sqlClient, resourceGroup, server, dbName);

                // Run some scans
                string scanId = string.Format("scantest1_{0}", testPrefix);
                sqlClient.DatabaseVulnerabilityAssessmentScans.InitiateScan(resourceGroup.Name, server.Name, dbName, scanId);

                string scanId1 = string.Format("scantest2_{0}", testPrefix);
                sqlClient.DatabaseVulnerabilityAssessmentScans.InitiateScan(resourceGroup.Name, server.Name, dbName, scanId1);

                // Verify get scan and list scans
                VulnerabilityAssessmentScanRecord scanRecord = sqlClient.DatabaseVulnerabilityAssessmentScans.Get(resourceGroup.Name, server.Name, dbName, scanId);
                Assert.Equal(scanId, scanRecord.ScanId);

                IPage <VulnerabilityAssessmentScanRecord> scanRecords = sqlClient.DatabaseVulnerabilityAssessmentScans.ListByDatabase(resourceGroup.Name, server.Name, dbName);
                Assert.Equal(2, scanRecords.ToList().Count);
                Assert.Contains(scanRecords.ToList(), item => item.ScanId == scanId);
                Assert.Contains(scanRecords.ToList(), item => item.ScanId == scanId1);

                VulnerabilityAssessmentScanRecord scanId1Record         = sqlClient.DatabaseVulnerabilityAssessmentScans.Get(resourceGroup.Name, server.Name, dbName, scanId1);
                VulnerabilityAssessmentScanRecord scanId1RecordFromList = scanRecords.FirstOrDefault(item => item.ScanId == scanId1);
                Assert.Equal(scanId1Record.ScanId, scanId1RecordFromList.ScanId);
                Assert.Equal(scanId1Record.TriggerType, scanId1RecordFromList.TriggerType);
                Assert.Equal(scanId1Record.State, scanId1RecordFromList.State);
                Assert.Equal(scanId1Record.StartTime, scanId1RecordFromList.StartTime);
                Assert.Equal(scanId1Record.EndTime, scanId1RecordFromList.EndTime);
                Assert.Equal(scanId1Record.Errors, scanId1RecordFromList.Errors);
                Assert.Equal(scanId1Record.StorageContainerPath, scanId1RecordFromList.StorageContainerPath);
                Assert.Equal(scanId1Record.NumberOfFailedSecurityChecks, scanId1RecordFromList.NumberOfFailedSecurityChecks);
            }
        }
        private async Task <ScriptSecrets> ReadHostSecrets()
        {
            IPage <SecretItem> secretItems = await _keyVaultClient.Value.GetSecretsAsync(GetVaultBaseUrl());

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

            // Add master key task
            SecretItem masterItem = secretItems.FirstOrDefault(x => x.Identifier.Name.StartsWith(MasterKey));

            if (masterItem != null)
            {
                tasks.Add(_keyVaultClient.Value.GetSecretAsync(GetVaultBaseUrl(), masterItem.Identifier.Name));
            }
            else
            {
                return(null);
            }

            // Add functionKey tasks
            foreach (SecretItem item in secretItems.Where(x => x.Identifier.Name.StartsWith(FunctionKeyPrefix)))
            {
                tasks.Add(_keyVaultClient.Value.GetSecretAsync(GetVaultBaseUrl(), item.Identifier.Name));
            }

            // Add systemKey tasks
            foreach (SecretItem item in secretItems.Where(x => x.Identifier.Name.StartsWith(SystemKeyPrefix)))
            {
                tasks.Add(_keyVaultClient.Value.GetSecretAsync(GetVaultBaseUrl(), item.Identifier.Name));
            }

            await Task.WhenAll(tasks);

            HostSecrets hostSecrets = new HostSecrets()
            {
                FunctionKeys = new List <Key>(),
                SystemKeys   = new List <Key>()
            };

            foreach (Task <SecretBundle> task in tasks)
            {
                SecretBundle item = task.Result;
                if (item.SecretIdentifier.Name.StartsWith(MasterKey))
                {
                    hostSecrets.MasterKey = SecretBundleToKey(item, MasterKey);
                }
                else if (item.SecretIdentifier.Name.StartsWith(FunctionKeyPrefix))
                {
                    hostSecrets.FunctionKeys.Add(SecretBundleToKey(item, FunctionKeyPrefix));
                }
                else if (item.SecretIdentifier.Name.StartsWith(SystemKeyPrefix))
                {
                    hostSecrets.SystemKeys.Add(SecretBundleToKey(item, SystemKeyPrefix));
                }
            }

            return(hostSecrets);
        }
        public async void TestExecuteGetListDatabaseVulnerabilityAssessmentScans()
        {
            string testPrefix = "sqlvulnerabilityassessmentscantest-";

            SqlManagementClient sqlClient = m_testFixture.Context.GetClient <SqlManagementClient>();

            // Create managed database
            //
            string dbName = SqlManagementTestUtilities.GenerateName(testPrefix);
            var    db1    = sqlClient.ManagedDatabases.CreateOrUpdate(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name, dbName, new ManagedDatabase()
            {
                Location = m_testFixture.ManagedInstance.Location,
            });

            Assert.NotNull(db1);

            // Set policy
            await SetPolicy(m_testFixture.Context, sqlClient, m_testFixture.ResourceGroup, m_testFixture.ManagedInstance, dbName);

            // Run some scans
            string scanId = string.Format("scantest1_{0}", testPrefix);

            sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.InitiateScan(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name, dbName, scanId);

            string scanId1 = string.Format("scantest2_{0}", testPrefix);

            sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.InitiateScan(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name, dbName, scanId1);

            // Verify get scan and list scans
            VulnerabilityAssessmentScanRecord scanRecord = sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.Get(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name, dbName, scanId);

            Assert.Equal(scanId, scanRecord.ScanId);

            IPage <VulnerabilityAssessmentScanRecord> scanRecords = sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.ListByDatabase(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name, dbName);

            Assert.Equal(2, scanRecords.ToList().Count);
            Assert.Contains(scanRecords.ToList(), item => item.ScanId == scanId);
            Assert.Contains(scanRecords.ToList(), item => item.ScanId == scanId1);

            VulnerabilityAssessmentScanRecord scanId1Record         = sqlClient.ManagedDatabaseVulnerabilityAssessmentScans.Get(m_testFixture.ResourceGroup.Name, m_testFixture.ManagedInstance.Name, dbName, scanId1);
            VulnerabilityAssessmentScanRecord scanId1RecordFromList = scanRecords.FirstOrDefault(item => item.ScanId == scanId1);

            Assert.Equal(scanId1Record.ScanId, scanId1RecordFromList.ScanId);
            Assert.Equal(scanId1Record.TriggerType, scanId1RecordFromList.TriggerType);
            Assert.Equal(scanId1Record.State, scanId1RecordFromList.State);
            Assert.Equal(scanId1Record.StartTime, scanId1RecordFromList.StartTime);
            Assert.Equal(scanId1Record.EndTime, scanId1RecordFromList.EndTime);
            Assert.Equal(scanId1Record.Errors, scanId1RecordFromList.Errors);
            Assert.Equal(scanId1Record.StorageContainerPath, scanId1RecordFromList.StorageContainerPath);
            Assert.Equal(scanId1Record.NumberOfFailedSecurityChecks, scanId1RecordFromList.NumberOfFailedSecurityChecks);
        }
        public void TestStartStopGetJobExecution()
        {
            using (SqlManagementTestContext context = new SqlManagementTestContext(this))
            {
                ResourceGroup resourceGroup = context.CreateResourceGroup();
                Server        server        = context.CreateServer(resourceGroup);

                SqlManagementClient sqlClient = context.GetClient <SqlManagementClient>();

                try
                {
                    // Allow all conenctions for test
                    sqlClient.FirewallRules.CreateOrUpdate(resourceGroup.Name, server.Name, "allowAll", new FirewallRule
                    {
                        StartIpAddress = "0.0.0.0",
                        EndIpAddress   = "255.255.255.255",
                    });

                    // Create database only required parameters
                    string dbName = SqlManagementTestUtilities.GenerateName();
                    var    db1    = sqlClient.Databases.CreateOrUpdate(resourceGroup.Name, server.Name, dbName, new Database()
                    {
                        Location = server.Location,
                    });
                    Assert.NotNull(db1);

                    // Create agent
                    string agentName = "agent";

                    JobAgent agent = sqlClient.JobAgents.CreateOrUpdate(resourceGroup.Name, server.Name, agentName, new JobAgent
                    {
                        Location   = server.Location,
                        DatabaseId = db1.Id
                    });


                    // Create credential
                    JobCredential credential = sqlClient.JobCredentials.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, SqlManagementTestUtilities.DefaultLogin, new JobCredential
                    {
                        Username = SqlManagementTestUtilities.DefaultLogin,
                        Password = SqlManagementTestUtilities.DefaultPassword
                    });


                    // Create target group
                    JobTargetGroup targetGroup = sqlClient.JobTargetGroups.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, "tg1", new JobTargetGroup
                    {
                        Members = new List <JobTarget>
                        {
                            // server target
                            new JobTarget
                            {
                                ServerName     = server.Name,
                                DatabaseName   = db1.Name,
                                Type           = JobTargetType.SqlDatabase,
                                MembershipType = JobTargetGroupMembershipType.Include,
                            }
                        }
                    });

                    // Create job that runs once
                    Job job1 = sqlClient.Jobs.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, "job1", new Job
                    {
                        Description = "Test description",
                        Schedule    = new JobSchedule
                        {
                            Enabled = true,
                            Type    = JobScheduleType.Once,
                        }
                    });

                    // Create job step
                    JobStep step1 = sqlClient.JobSteps.CreateOrUpdate(resourceGroup.Name, server.Name, agent.Name, job1.Name, "step1", new JobStep
                    {
                        Credential = credential.Id,
                        Action     = new JobStepAction
                        {
                            Value = "SELECT 1"
                        },
                        TargetGroup = targetGroup.Id
                    });


                    // Create job execution from job1 - do sync so we can be sure a step execution succeeds
                    JobExecution jobExecution = sqlClient.JobExecutions.Create(resourceGroup.Name, server.Name, agent.Name, job1.Name);

                    // List executions by agent
                    sqlClient.JobExecutions.ListByAgent(resourceGroup.Name, server.Name, agent.Name);

                    // List executions by job
                    sqlClient.JobExecutions.ListByJob(resourceGroup.Name, server.Name, agent.Name, job1.Name);

                    // Get root job execution
                    jobExecution = sqlClient.JobExecutions.Get(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value);

                    // List step executions by root execution
                    sqlClient.JobStepExecutions.ListByJobExecution(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value);

                    // Get step1 execution
                    sqlClient.JobStepExecutions.Get(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value, step1.Name);

                    // List target executions by root job execution
                    sqlClient.JobTargetExecutions.ListByJobExecution(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value);

                    // List target executions by job step
                    IPage <JobExecution> targetStepExecutions = sqlClient.JobTargetExecutions.ListByStep(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value, step1.Name);
                    Assert.Single(targetStepExecutions);

                    // Get target execution
                    sqlClient.JobTargetExecutions.Get(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value, step1.Name, Guid.Parse(targetStepExecutions.FirstOrDefault().Name));

                    // Cancel the job execution
                    sqlClient.JobExecutions.Cancel(resourceGroup.Name, server.Name, agent.Name, job1.Name, jobExecution.JobExecutionId.Value);
                }
                finally
                {
                    context.DeleteResourceGroup(resourceGroup.Name);
                }
            }
        }
        public async Task CreateAndDelete()
        {
            using var context = MockContext.Start(GetType());
            var testName = "unitTestingDPSLinkedHubCreateUpdateDelete";

            Initialize(context);
            var           iotHubClient  = GetClient <IotHubClient>(context);
            ResourceGroup resourceGroup = await GetResourceGroupAsync(testName).ConfigureAwait(false);

            ProvisioningServiceDescription testedService = await GetServiceAsync(resourceGroup.Name, testName).ConfigureAwait(false);

            IotHubDescription iotHub = await GetIotHubAsync(iotHubClient, resourceGroup, testName).ConfigureAwait(false);

            IPage <SharedAccessSignatureAuthorizationRule> keys = await iotHubClient.IotHubResource
                                                                  .ListKeysAsync(
                resourceGroup.Name,
                iotHub.Name)
                                                                  .ConfigureAwait(false);

            SharedAccessSignatureAuthorizationRule key = keys.FirstOrDefault(x => x.Rights.HasFlag(AccessRights.ServiceConnect));
            var connectionString = $"HostName={iotHub.Name}.azure-devices.net;SharedAccessKeyName={key.KeyName};SharedAccessKey={key.PrimaryKey}";

            testedService.Properties.IotHubs = testedService.Properties.IotHubs ?? new List <IotHubDefinitionDescription>(1);

            testedService.Properties.IotHubs.Add(new IotHubDefinitionDescription(connectionString, resourceGroup.Location, name: testName));
            ProvisioningServiceDescription updatedInstance = await _provisioningClient.IotDpsResource
                                                             .CreateOrUpdateAsync(
                resourceGroup.Name,
                testName,
                testedService)
                                                             .ConfigureAwait(false);

            IotHubDefinitionDescription returnedHub = updatedInstance.Properties.IotHubs
                                                      .FirstOrDefault(x => x.Name.Equals($"{iotHub.Name}.azure-devices.net"));

            returnedHub.Should().NotBeNull();
            connectionString = returnedHub.ConnectionString;

            bool hasUpdatedApplyPolicy = !(returnedHub.ApplyAllocationPolicy ?? false);

            returnedHub.ApplyAllocationPolicy = hasUpdatedApplyPolicy;

            int updatedPolicyWeight = Helpers.Constants.RandomAllocationWeight;

            returnedHub.AllocationWeight = updatedPolicyWeight;

            updatedInstance = await _provisioningClient.IotDpsResource
                              .CreateOrUpdateAsync(
                resourceGroup.Name,
                testName,
                updatedInstance)
                              .ConfigureAwait(false);

            IotHubDefinitionDescription updatedHub = updatedInstance.Properties.IotHubs
                                                     .FirstOrDefault(x => x.ConnectionString == connectionString);

            updatedHub.Should().NotBeNull();

            updatedHub.ApplyAllocationPolicy.Should().Be(hasUpdatedApplyPolicy);
            updatedHub.AllocationWeight.Should().Be(updatedPolicyWeight);


            // Delete the linked hub
            testedService.Properties.IotHubs = testedService.Properties.IotHubs
                                               .Except(testedService.Properties.IotHubs.Where(x => x.Name == testName))
                                               .ToList();
            updatedInstance = await _provisioningClient.IotDpsResource
                              .CreateOrUpdateAsync(
                resourceGroup.Name,
                testName,
                testedService)
                              .ConfigureAwait(false);

            updatedInstance.Properties.IotHubs.Should().NotContain(connectionString);
        }
Esempio n. 7
0
        public void TestScriptActionsOnRunningCluster()
        {
            string clusterName = "hdisdk-scriptactions";
            string testName    = "TestScriptActionsOnRunningCluster";
            string suiteName   = GetType().FullName;
            ClusterCreateParameters createParams = ClusterCreateParametersHelpers.GetCustomCreateParametersIaas(testName);

            HDInsightManagementTestUtilities.CreateClusterInNewResourceGroupAndRunTest(suiteName, testName, clusterName, createParams, (client, rgName) =>
            {
                string scriptName = "script1";

                //Upload script to storage account.
                UploadScriptToStorageAccount(createParams);

                //Execute script actions, and persist on success.
                IList <RuntimeScriptAction> scriptActionParams = GetExecuteScriptActionParams(scriptName, InstallGiraph);
                client.Clusters.ExecuteScriptActions(rgName, clusterName, scriptActionParams, true);

                //List script actions and validate script is persisted.
                IPage <RuntimeScriptActionDetail> scriptActionsList = client.ScriptActions.ListByCluster(rgName, clusterName);
                Assert.Single(scriptActionsList);
                RuntimeScriptActionDetail scriptAction = scriptActionsList.First();
                Assert.Equal(scriptActionParams[0].Name, scriptAction.Name);
                Assert.Equal(scriptActionParams[0].Uri, scriptAction.Uri);
                Assert.Equal(scriptActionParams[0].Roles, scriptAction.Roles);

                //Delete script action.
                client.ScriptActions.Delete(rgName, clusterName, scriptName);

                //List script actions and validate script is deleted.
                scriptActionsList = client.ScriptActions.ListByCluster(rgName, clusterName);
                Assert.Empty(scriptActionsList);

                //List script action history and validate script appears there.
                IPage <RuntimeScriptActionDetail> listHistoryResponse = client.ScriptExecutionHistory.ListByCluster(rgName, clusterName);
                Assert.Single(listHistoryResponse);
                scriptAction = listHistoryResponse.First();
                Assert.Equal(1, scriptAction.ExecutionSummary.Count);
                Assert.Equal(scriptActionParams[0].Name, scriptAction.Name);
                Assert.Equal(scriptActionParams[0].Uri, scriptAction.Uri);
                Assert.Equal(scriptActionParams[0].Roles, scriptAction.Roles);
                Assert.Equal("Succeeded", scriptAction.Status);

                //Get the script action by ID and validate it's the same action.
                scriptAction = client.ScriptActions.GetExecutionDetail(rgName, clusterName, listHistoryResponse.First().ScriptExecutionId.Value.ToString());
                Assert.Equal(scriptActionParams[0].Name, scriptAction.Name);

                //Execute script actions, but don't persist on success.
                scriptActionParams = GetExecuteScriptActionParams("script5baf", InstallGiraph);
                client.Clusters.ExecuteScriptActions(rgName, clusterName, scriptActionParams, false);

                //List script action history and validate the new script also appears.
                listHistoryResponse = client.ScriptExecutionHistory.ListByCluster(rgName, clusterName);
                Assert.Equal(2, listHistoryResponse.Count());
                scriptAction = listHistoryResponse.FirstOrDefault(a => a.Name.Equals(scriptActionParams[0].Name, StringComparison.OrdinalIgnoreCase));
                Assert.NotNull(scriptAction);
                Assert.Equal(1, scriptAction.ExecutionSummary.Count);
                Assert.Equal(scriptActionParams[0].Name, scriptAction.Name);
                Assert.Equal(scriptActionParams[0].Uri, scriptAction.Uri);
                Assert.Equal(scriptActionParams[0].Roles, scriptAction.Roles);
                Assert.Equal("Succeeded", scriptAction.Status);

                //Promote non-persisted script.
                client.ScriptExecutionHistory.Promote(rgName, clusterName, listHistoryResponse.First().ScriptExecutionId.Value.ToString());

                //Execute failing script action.
                string failingScriptUri = GetFailingScriptUri(createParams);
                IList <RuntimeScriptAction> failingScriptActionParams = GetExecuteScriptActionParams(string.Format("script0cc4", Guid.NewGuid()).Substring(0, 10), failingScriptUri);
                CloudException ex = Assert.Throws <CloudException>(() => client.Clusters.ExecuteScriptActions(rgName, clusterName, failingScriptActionParams, true));

                //List script action list and validate the promoted script is the only one there.
                scriptActionsList = client.ScriptActions.ListByCluster(rgName, clusterName);
                Assert.Single(scriptActionsList);
                Assert.Equal(1, scriptAction.ExecutionSummary.Count);
                Assert.Equal(scriptActionParams[0].Name, scriptAction.Name);
                Assert.Equal(scriptActionParams[0].Uri, scriptAction.Uri);
                Assert.Equal(scriptActionParams[0].Roles, scriptAction.Roles);
                Assert.Equal("Succeeded", scriptAction.Status);

                //List script action history and validate all three scripts are there.
                listHistoryResponse = client.ScriptExecutionHistory.ListByCluster(rgName, clusterName);
                Assert.Equal(3, listHistoryResponse.Count());
                Assert.Equal(2, listHistoryResponse.Count(a => a.Status == "Succeeded"));
                Assert.Equal(1, listHistoryResponse.Count(a => a.Status == "Failed"));
            });
        }