public VaultData(AzureLocation location, VaultProperties properties) : base(location) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } Properties = properties; }
internal VaultData(VaultProperties properties) { if (properties == null) { throw new ArgumentNullException(nameof(properties)); } Tags = new ChangeTrackingDictionary <string, string>(); Properties = properties; }
internal static VaultData DeserializeVaultData(JsonElement element) { VaultProperties properties = default; IDictionary <string, string> tags = default; AzureLocation location = default; ResourceIdentifier id = default; string name = default; ResourceType type = default; SystemData systemData = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("properties")) { properties = VaultProperties.DeserializeVaultProperties(property.Value); continue; } if (property.NameEquals("tags")) { Dictionary <string, string> dictionary = new Dictionary <string, string>(); foreach (var property0 in property.Value.EnumerateObject()) { dictionary.Add(property0.Name, property0.Value.GetString()); } tags = dictionary; continue; } if (property.NameEquals("location")) { location = new AzureLocation(property.Value.GetString()); continue; } if (property.NameEquals("id")) { id = new ResourceIdentifier(property.Value.GetString()); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = new ResourceType(property.Value.GetString()); continue; } if (property.NameEquals("systemData")) { systemData = JsonSerializer.Deserialize <SystemData>(property.Value.ToString()); continue; } } return(new VaultData(id, name, type, systemData, tags, location, properties)); }
private void Initialize() { rgName = TestUtilities.GenerateName("sdktestrg"); resourcesClient.ResourceGroups.CreateOrUpdate(rgName, new ResourceGroup { Location = location }); vaultName = TestUtilities.GenerateName("sdktestvault"); tenantIdGuid = Guid.Parse(tenantId); objectIdGuid = objectId; tags = new Dictionary <string, string> { { "tag1", "value1" }, { "tag2", "value2" }, { "tag3", "value3" } }; accPol = new AccessPolicyEntry { TenantId = tenantIdGuid, ObjectId = objectIdGuid, Permissions = new Permissions { Keys = new string[] { "all" }, Secrets = new string[] { "all" }, Certificates = new string[] { "all" }, Storage = new string[] { "all" }, } }; IList <IPRule> ipRules = new List <IPRule>(); ipRules.Add(new IPRule() { Value = "1.2.3.4/32" }); ipRules.Add(new IPRule() { Value = "1.0.0.0/25" }); vaultProperties = new VaultProperties { EnabledForDeployment = true, EnabledForDiskEncryption = true, EnabledForTemplateDeployment = true, EnableSoftDelete = true, Sku = new Microsoft.Azure.Management.KeyVault.Models.Sku { Name = SkuName.Standard }, TenantId = tenantIdGuid, VaultUri = "", NetworkAcls = new NetworkRuleSet() { Bypass = "******", DefaultAction = "Allow", IpRules = ipRules, VirtualNetworkRules = null }, AccessPolicies = new[] { accPol } }; }
public async Task KeyVaultManagementVaultCreateWithoutAccessPolicies() { IgnoreTestInLiveMode(); VaultProperties vaultProperties = new VaultProperties(TenantIdGuid, new KeyVaultSku(KeyVaultSkuFamily.A, KeyVaultSkuName.Standard)); VaultCreateOrUpdateContent content = new VaultCreateOrUpdateContent(Location, vaultProperties); ArmOperation <VaultResource> rawVault = await VaultCollection.CreateOrUpdateAsync(WaitUntil.Completed, VaultName, content); VaultData createdVault = rawVault.Value.Data; Assert.IsNotNull(createdVault); Assert.AreEqual(VaultName, createdVault.Name); }
public IPage <Vault> ListBySubscription(int?top = null) { TestPage <Vault> ret = new TestPage <Vault>(); var vaults = KeyVaults.ToLookup(v => v.SubscriptionId)[TestKVMClient.subid]; foreach (KeyVaultProperties kv in vaults) { var aps = new List <AccessPolicyEntry>(); foreach (PrincipalPermissions pp in kv.AccessPolicies) { var objectId = ""; if (pp.Type.ToLower() == "user") { if (pp.DisplayName.ToLower().Contains('a')) { objectId = "ua"; } else if (pp.DisplayName.ToLower().Contains('b')) { objectId = "ub"; } else if (pp.DisplayName.ToLower().Contains('c')) { objectId = "uc"; } } else { objectId = pp.DisplayName; } aps.Add(new AccessPolicyEntry { ObjectId = objectId, TenantId = new Guid("00000000-0000-0000-0000-000000000000"), Permissions = new Permissions { Certificates = pp.PermissionsToCertificates, Secrets = pp.PermissionsToSecrets, Keys = pp.PermissionsToKeys, } }); } var properties = new VaultProperties { AccessPolicies = aps, TenantId = new Guid("00000000-0000-0000-0000-000000000000"), }; ret.Add(new Vault(properties, $"subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/{kv.ResourceGroupName}", kv.VaultName, null, "eastus", null)); } return(ret); }
/// <summary> /// Update an existing vault. Only EnabledForDeployment and AccessPolicies can be updated currently. /// </summary> /// <param name="existingVault">the existing vault</param> /// <param name="updatedPolicies">the update access policies</param> /// <param name="updatedEnabledForDeployment">enabled for deployment</param> /// <param name="updatedEnabledForTemplateDeployment">enabled for template deployment</param> /// <param name="updatedEnabledForDiskEncryption">enabled for disk encryption</param> /// <param name="adClient">the active directory client</param> /// <returns>the updated vault</returns> public PSKeyVault UpdateVault(PSKeyVault existingVault, PSKeyVaultAccessPolicy[] updatedPolicies, bool?updatedEnabledForDeployment, bool?updatedEnabledForTemplateDeployment, bool?updatedEnabledForDiskEncryption, ActiveDirectoryClient adClient = null) { if (existingVault == null) { throw new ArgumentNullException("existingVault"); } if (existingVault.OriginalVault == null) { throw new ArgumentNullException("existingVault.OriginalVault"); } //Update the vault properties in the object received from server //Only access policies and EnabledForDeployment can be changed VaultProperties properties = existingVault.OriginalVault.Properties; properties.EnabledForDeployment = updatedEnabledForDeployment; properties.EnabledForTemplateDeployment = updatedEnabledForTemplateDeployment; properties.EnabledForDiskEncryption = updatedEnabledForDiskEncryption; properties.AccessPolicies = (updatedPolicies == null) ? new List <AccessPolicyEntry>() : updatedPolicies.Select(a => new AccessPolicyEntry() { TenantId = a.TenantId, ObjectId = a.ObjectId, ApplicationId = a.ApplicationId, Permissions = new Permissions { Keys = a.PermissionsToKeys.ToArray(), Secrets = a.PermissionsToSecrets.ToArray(), Certificates = a.PermissionsToCertificates.ToArray(), Storage = a.PermissionsToStorage.ToArray(), } }).ToList(); var response = this.KeyVaultManagementClient.Vaults.CreateOrUpdate( resourceGroupName: existingVault.ResourceGroupName, vaultName: existingVault.VaultName, parameters: new VaultCreateOrUpdateParameters() { Location = existingVault.Location, Properties = properties, Tags = TagsConversionHelper.CreateTagDictionary(existingVault.Tags, validate: true) } ); return(new PSKeyVault(response, adClient)); }
public Vault Get(string resourceGroupName, string vaultName) { var vault = KeyVaults.ToLookup(kv => kv.VaultName)[vaultName].First(); var aps = new List <AccessPolicyEntry>(); foreach (PrincipalPermissions pp in vault.AccessPolicies) { var objectId = ""; if (pp.Type.ToLower() == "user") { if (pp.DisplayName.ToLower().Contains('a')) { objectId = "ua"; } else if (pp.DisplayName.ToLower().Contains('b')) { objectId = "ub"; } else if (pp.DisplayName.ToLower().Contains('c')) { objectId = "uc"; } } else { objectId = pp.DisplayName; } aps.Add(new AccessPolicyEntry { ObjectId = objectId, TenantId = new Guid("00000000-0000-0000-0000-000000000000"), Permissions = new Permissions { Certificates = pp.PermissionsToCertificates, Secrets = pp.PermissionsToSecrets, Keys = pp.PermissionsToKeys, } }); } var properties = new VaultProperties { AccessPolicies = aps, TenantId = new Guid("00000000-0000-0000-0000-000000000000"), }; var ret = new Vault(properties, $"subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/{resourceGroupName}", vault.VaultName, null, "eastus", null); return(ret); }
/// <summary> /// Update vault network rule set /// </summary> /// <param name="vaultProperties">Vault property</param> /// <param name="psRuleSet">Network rule set input</param> static private void UpdateVaultNetworkRuleSetProperties(VaultProperties vaultProperties, PSKeyVaultNetworkRuleSet psRuleSet) { if (vaultProperties == null) { return; } NetworkRuleSet updatedRuleSet = new NetworkRuleSet(); // It contains default settings if (psRuleSet != null) { updatedRuleSet.DefaultAction = psRuleSet.DefaultAction.ToString(); updatedRuleSet.Bypass = psRuleSet.Bypass.ToString(); if (psRuleSet.IpAddressRanges != null && psRuleSet.IpAddressRanges.Count > 0) { updatedRuleSet.IpRules = psRuleSet.IpAddressRanges.Select(ipAddress => { return(new IPRule() { Value = ipAddress }); }).ToList <IPRule>(); } else { // Send empty array [] to server to override default updatedRuleSet.IpRules = new List <IPRule>(); } if (psRuleSet.VirtualNetworkResourceIds != null && psRuleSet.VirtualNetworkResourceIds.Count > 0) { updatedRuleSet.VirtualNetworkRules = psRuleSet.VirtualNetworkResourceIds.Select(resourceId => { return(new VirtualNetworkRule() { Id = resourceId }); }).ToList <VirtualNetworkRule>(); } else { // Send empty array [] to server to override default updatedRuleSet.VirtualNetworkRules = new List <VirtualNetworkRule>(); } } vaultProperties.NetworkAcls = updatedRuleSet; }
/// <summary> /// Creates a vault with the specified parameters and coordinates. /// </summary> /// <param name="resourceGroupName"></param> /// <param name="vaultName"></param> /// <param name="vaultLocation"></param> /// <param name="enableSoftDelete"></param> /// <param name="enablePurgeProtection"></param> /// <returns></returns> protected VaultCreateOrUpdateParameters CreateVaultParameters(string resourceGroupName, string vaultName, string vaultLocation, bool enableSoftDelete, bool enablePurgeProtection) { var properties = new VaultProperties { TenantId = Guid.Parse(context.TenantId), Sku = new Sku(), AccessPolicies = new List <AccessPolicyEntry>(), EnabledForDeployment = false, EnabledForDiskEncryption = false, EnabledForTemplateDeployment = false, EnableSoftDelete = enableSoftDelete ? (bool?)enableSoftDelete : null, CreateMode = CreateMode.Default }; // accessing managed storage account functionality requires a user identity // since the login would have to be interactive, it is acceptable to expect that // the user has been granted the required roles and permissions in preamble. return(new VaultCreateOrUpdateParameters(vaultLocation, properties)); }
public async Task CreateOrUpdate() { #region Snippet:Managing_KeyVaults_CreateAVault VaultCollection vaultCollection = resourceGroup.GetVaults(); string vaultName = "myVault"; Guid tenantIdGuid = new Guid("Your tenantId"); string objectId = "Your Object Id"; IdentityAccessPermissions permissions = new IdentityAccessPermissions { Keys = { new KeyPermission("all") }, Secrets = { new SecretPermission("all") }, Certificates = { new CertificatePermission("all") }, Storage = { new StoragePermission("all") }, }; AccessPolicyEntry AccessPolicy = new AccessPolicyEntry(tenantIdGuid, objectId, permissions); VaultProperties VaultProperties = new VaultProperties(tenantIdGuid, new KeyVaultSku(KeyVaultSkuFamily.A, KeyVaultSkuName.Standard)); VaultProperties.EnabledForDeployment = true; VaultProperties.EnabledForDiskEncryption = true; VaultProperties.EnabledForTemplateDeployment = true; VaultProperties.EnableSoftDelete = true; VaultProperties.VaultUri = new Uri("http://vaulturi.com"); VaultProperties.NetworkAcls = new NetworkRuleSet() { Bypass = "******", DefaultAction = "Allow", IPRules = { new IPRule("1.2.3.4/32"), new IPRule("1.0.0.0/25") } }; VaultProperties.AccessPolicies.Add(AccessPolicy); VaultCreateOrUpdateContent parameters = new VaultCreateOrUpdateContent(AzureLocation.WestUS, VaultProperties); var rawVault = await vaultCollection.CreateOrUpdateAsync(WaitUntil.Started, vaultName, parameters).ConfigureAwait(false); VaultResource vault = await rawVault.WaitForCompletionAsync(); #endregion }
/// <summary> /// Create key vault. /// </summary> /// <param name="resourceGroupName"></param> /// <param name="vaultName"></param> /// <param name="region"></param> /// <param name="sku"></param> /// <param name="permissions"></param> /// <param name="enabledForDeployment"></param> /// <param name="enabledForDiskEncryption"></param> /// <param name="enabledForTemplateDeployment"></param> /// <param name="enableSoftDelete"></param> /// <returns></returns> public Vault CreateVault( string resourceGroupName, string vaultName, string region, SkuName sku = SkuName.Premium, Permissions permissions = null, bool?enabledForDeployment = true, bool?enabledForDiskEncryption = true, bool?enabledForTemplateDeployment = true, bool?enableSoftDelete = null) { var accessPolicies = new List <AccessPolicyEntry>() { new AccessPolicyEntry { TenantId = Guid.Parse(commonData.TenantId), ObjectId = commonData.ClientObjectId, Permissions = permissions ?? DefaultPermissions } }; var properties = new VaultProperties { TenantId = Guid.Parse(commonData.TenantId), Sku = new Sku { Name = sku }, AccessPolicies = accessPolicies, EnabledForDeployment = enabledForDeployment, EnabledForDiskEncryption = enabledForDiskEncryption, EnabledForTemplateDeployment = enabledForTemplateDeployment, EnableSoftDelete = enableSoftDelete }; var parameters = new VaultCreateOrUpdateParameters { Location = region, Properties = properties }; return(keyVaultManagementClient.Vaults.CreateOrUpdate(resourceGroupName, vaultName, parameters)); }
static private PSKeyVaultNetworkRuleSet InitNetworkRuleSet(VaultProperties properties) { // The service will return NULL when NetworkAcls is never set before or set with default property values // The default constructor will set default property values in SDK's NetworkRuleSet class if (properties == null || properties.NetworkAcls == null) { return(new PSKeyVaultNetworkRuleSet()); } NetworkRuleSet networkAcls = properties.NetworkAcls; PSKeyVaultNetworkRuleDefaultActionEnum defaultAct; if (!Enum.TryParse <PSKeyVaultNetworkRuleDefaultActionEnum>(networkAcls.DefaultAction, true, out defaultAct)) { defaultAct = PSKeyVaultNetworkRuleDefaultActionEnum.Allow; } PSKeyVaultNetworkRuleBypassEnum bypass; if (!Enum.TryParse <PSKeyVaultNetworkRuleBypassEnum>(networkAcls.Bypass, true, out bypass)) { bypass = PSKeyVaultNetworkRuleBypassEnum.AzureServices; } IList <string> allowedIpAddresses = null; if (networkAcls.IpRules != null && networkAcls.IpRules.Count > 0) { allowedIpAddresses = networkAcls.IpRules.Select(item => { return(item.Value); }).ToList(); } IList <string> allowedVirtualNetworkResourceIds = null; if (networkAcls.VirtualNetworkRules != null && networkAcls.VirtualNetworkRules.Count > 0) { allowedVirtualNetworkResourceIds = networkAcls.VirtualNetworkRules.Select(item => { return(item.Id); }).ToList(); } return(new PSKeyVaultNetworkRuleSet(defaultAct, bypass, allowedIpAddresses, allowedVirtualNetworkResourceIds)); }
/// <summary> /// Set the vault access policay can manage the secret /// </summary> /// <param name="location"></param> /// <param name="objectId"></param> /// <returns></returns> private static VaultCreateOrUpdateParameters GetVaultCreateOrUpdateParameters(string tenantId, string location, string objectId) { var properties = new VaultProperties { TenantId = Guid.Parse(tenantId), Sku = new Sku(), AccessPolicies = new List <AccessPolicyEntry>(), CreateMode = CreateMode.Default }; properties.AccessPolicies.Add(new AccessPolicyEntry { TenantId = properties.TenantId, ObjectId = objectId, Permissions = new Permissions { Secrets = new SecretPermissions[] { SecretPermissions.Get, SecretPermissions.Set } } }); return(new VaultCreateOrUpdateParameters(location, properties)); }
/// <summary> /// Update an existing vault. Only EnabledForDeployment and AccessPolicies can be updated currently. /// </summary> /// <param name="existingVault"></param> /// <returns></returns> public PSVault UpdateVault(PSVault existingVault, PSVaultAccessPolicy[] updatedPolicies, bool updatedEnabledForDeployment, ActiveDirectoryClient adClient = null) { if (existingVault == null) { throw new ArgumentNullException("existingVault"); } if (existingVault.OriginalVault == null) { throw new ArgumentNullException("existingVault.OriginalVault"); } //Update the vault properties in the object received from server //Only access policies and EnabledForDeployment can be changed VaultProperties properties = existingVault.OriginalVault.Properties; properties.EnabledForDeployment = updatedEnabledForDeployment; properties.AccessPolicies = (updatedPolicies == null) ? new List <AccessPolicyEntry>() : updatedPolicies.Select(a => new AccessPolicyEntry() { TenantId = a.TenantId, ObjectId = a.ObjectId, PermissionsToKeys = a.PermissionsToKeys.ToArray(), PermissionsToSecrets = a.PermissionsToSecrets.ToArray() }).ToList(); var response = this.KeyVaultManagementClient.Vaults.CreateOrUpdate( resourceGroupName: existingVault.ResourceGroupName, vaultName: existingVault.VaultName, parameters: new VaultCreateOrUpdateParameters() { Location = existingVault.Location, Properties = properties } ); return(new PSVault(response.Vault, adClient)); }
public void CreateDefaultVault(MFilesVault vault) { if (HasVault(vault)) { throw new Exception(string.Format("与{0}同名的vault已存在或guid={1}重复!", vault.Name, vault.Guid)); } var app = MFServerUtility.ConnectToMfApp(vault); var vp = new VaultProperties { DisplayName = vault.Name, ExtendedMetadataDrivenPermissions = true, FileDataStorageType = MFFileDataStorage.MFFileDataStorageDefault, MainDataFolder = Path.Combine(vault.ServerPath, vault.Name), VaultGUID = Guid.NewGuid().ToString() }; var version = app.GetServerVersion().Major; vp.FullTextSearchLanguage = version < 11 ? "other" : "chs"; var guid = app.VaultManagementOperations.CreateNewVault(vp); vault.Guid = guid; }
protected async Task Initialize() { var resourceManagementClient = GetResourceManagementClient(); ResourcesClient = resourceManagementClient.GetResourcesClient(); ResourceGroupsClient = resourceManagementClient.GetResourceGroupsClient(); ResourceProvidersClient = resourceManagementClient.GetProvidersClient(); var keyVaultManagementClient = GetKeyVaultManagementClient(); VaultsClient = keyVaultManagementClient.GetVaultsClient(); if (Mode == RecordedTestMode.Playback) { this.ObjectId = Recording.GetVariable(ObjectIdKey, string.Empty); } else if (Mode == RecordedTestMode.Record) { var spClient = new RbacManagementClient(TestEnvironment.TenantId, TestEnvironment.Credential).GetServicePrincipalsClient(); var servicePrincipalList = spClient.ListAsync($"appId eq '{TestEnvironment.ClientId}'"); await foreach (var servicePrincipal in servicePrincipalList) { this.ObjectId = servicePrincipal.ObjectId; Recording.GetVariable(ObjectIdKey, this.ObjectId); break; } } var provider = (await ResourceProvidersClient.GetAsync("Microsoft.KeyVault")).Value; this.Location = provider.ResourceTypes.Where( (resType) => { if (resType.ResourceType == "vaults") { return(true); } else { return(false); } } ).First().Locations.FirstOrDefault(); ResGroupName = Recording.GenerateAssetName("sdktestrg"); await ResourceGroupsClient.CreateOrUpdateAsync(ResGroupName, new Resources.Models.ResourceGroup(Location)); VaultName = Recording.GenerateAssetName("sdktestvault"); TenantIdGuid = new Guid(TestEnvironment.TenantId); Tags = new Dictionary <string, string> { { "tag1", "value1" }, { "tag2", "value2" }, { "tag3", "value3" } }; var permissions = new Permissions { Keys = new KeyPermissions[] { new KeyPermissions("all") }, Secrets = new SecretPermissions[] { new SecretPermissions("all") }, Certificates = new CertificatePermissions[] { new CertificatePermissions("all") }, Storage = new StoragePermissions[] { new StoragePermissions("all") }, }; AccessPolicy = new AccessPolicyEntry(TenantIdGuid, ObjectId, permissions); IList <IPRule> ipRules = new List <IPRule>(); ipRules.Add(new IPRule("1.2.3.4/32")); ipRules.Add(new IPRule("1.0.0.0/25")); VaultProperties = new VaultProperties(TenantIdGuid, new Sku(SkuName.Standard)); VaultProperties.EnabledForDeployment = true; VaultProperties.EnabledForDiskEncryption = true; VaultProperties.EnabledForTemplateDeployment = true; VaultProperties.EnableSoftDelete = true; VaultProperties.VaultUri = ""; VaultProperties.NetworkAcls = new NetworkRuleSet() { Bypass = "******", DefaultAction = "Allow", IpRules = ipRules, VirtualNetworkRules = null }; VaultProperties.AccessPolicies = new[] { AccessPolicy }; }
internal static void CreateForAllBackup(MFilesServerApplication app, MFilesVault vault, string templateRootPath, string impersonationUserName, string impersonationPassword, MFSqlDatabase sqlDb, string vaultIndexRootPath = null) { var vp = new VaultProperties { DisplayName = vault.Name, ExtendedMetadataDrivenPermissions = true, FileDataStorageType = MFFileDataStorage.MFFileDataStorageDisk, MainDataFolder = Path.Combine(@"C:\Program Files\M-Files\Server Vaults", vault.Name), VaultGUID = Guid.NewGuid().ToString() }; if (vp.SeparateLocationForFileData == null) { vp.SeparateLocationForFileData = new AdditionalFolders(); } var af = new AdditionalFolder { Folder = Path.Combine(vault.ServerPath, vault.Name), }; if (!String.IsNullOrEmpty(impersonationUserName) && !String.IsNullOrEmpty(impersonationPassword)) { af.Impersonation = new Impersonation { Account = impersonationUserName, Password = impersonationPassword, ImpersonationType = MFImpersonationType.MFImpersonationTypeSpecificAccount }; } vp.SeparateLocationForFileData.Add(-1, af); var version = app.GetServerVersion().Major; if (sqlDb != null) { var admin = new Impersonation { Account = sqlDb.AdminUserName, Password = sqlDb.AdminPassword, ImpersonationType = sqlDb.SqlserverUser ? MFImpersonationType.MFImpersonationTypeExtAccount : MFImpersonationType.MFImpersonationTypeSpecificAccount }; var mfsqldb = new SQLDatabase { Server = sqlDb.Server, Name = sqlDb.Catelog, Engine = MFDBEngine.MFDBEngineMSSQLServer }; mfsqldb.AdminUser = admin; //2015 vp.SQLDatabase = mfsqldb; } vp.FullTextSearchLanguage = version < 11 ? "other" : "chs"; var rj = new RestoreJob { BackupFileFull = templateRootPath, VaultProperties = vp, OverwriteExistingFiles = true }; app.VaultManagementOperations.RestoreVault(rj); vault.Guid = vp.VaultGUID; //return app.LogInToVault(vp.VaultGUID); }
internal static Vault Create(MFilesServerApplication app, MFilesVault vault, string templateRootPath, string impersonationUserName, string impersonationPassword, MFSqlDatabase sqlDb, string vaultIndexRootPath = null, bool fullBackupOrStructure = false) { var vp = new VaultProperties { DisplayName = vault.Name, ExtendedMetadataDrivenPermissions = true, FileDataStorageType = MFFileDataStorage.MFFileDataStorageDisk, MainDataFolder = Path.Combine(@"C:\Program Files\M-Files\Server Vaults", vault.Name), VaultGUID = Guid.NewGuid().ToString() }; if (vp.SeparateLocationForFileData == null) { vp.SeparateLocationForFileData = new AdditionalFolders(); } var af = new AdditionalFolder { Folder = Path.Combine(vault.ServerPath, vault.Name), }; if (!String.IsNullOrEmpty(impersonationUserName) && !String.IsNullOrEmpty(impersonationPassword)) { af.Impersonation = new Impersonation { Account = impersonationUserName, Password = impersonationPassword, ImpersonationType = MFImpersonationType.MFImpersonationTypeSpecificAccount }; } vp.SeparateLocationForFileData.Add(-1, af); var version = app.GetServerVersion().Major; if (sqlDb != null) { var admin = new Impersonation { Account = sqlDb.AdminUserName, Password = sqlDb.AdminPassword, ImpersonationType = sqlDb.SqlserverUser ? MFImpersonationType.MFImpersonationTypeExtAccount : MFImpersonationType.MFImpersonationTypeSpecificAccount }; var mfsqldb = new SQLDatabase { Server = sqlDb.Server, Name = sqlDb.Catelog, Engine = MFDBEngine.MFDBEngineMSSQLServer }; mfsqldb.AdminUser = admin; //2015 vp.SQLDatabase = mfsqldb; } vp.FullTextSearchLanguage = version < 11 ? "other" : "chs"; if (fullBackupOrStructure) { var rj = new RestoreJob { BackupFileFull = templateRootPath, VaultProperties = vp, OverwriteExistingFiles = true }; app.VaultManagementOperations.RestoreVault(rj); vault.Guid = vp.VaultGUID; return(null); } var guid = app.VaultManagementOperations.CreateNewVault(vp); vault.Guid = guid; var import = new ImportContentJob { ActivateAutomaticPermissionsForNewOrChangedDefinitions = true, DisableImportedExternalObjectTypeConnections = true, DisableImportedExternalUserGroups = true, DisableImportedVaultEventHandlers = false, Flags = MFImportContentFlag.MFImportContentFlagNone, IgnoreAutomaticPermissionsDefinedByObjects = false, SourceLocation = Path.Combine(templateRootPath, "Index") }; if (!String.IsNullOrEmpty(impersonationUserName) && !String.IsNullOrEmpty(impersonationPassword)) { import.Impersonation = new Impersonation { Account = impersonationUserName, Password = impersonationPassword, ImpersonationType = MFImpersonationType.MFImpersonationTypeSpecificAccount }; } var newvault = app.LogInToVault(guid); //todo,会有数据超限的问题, 2015貌似没有问题,但更新模板数据时可能会有这个问题 try { newvault.ManagementOperations.ImportContent(import); } catch (Exception ex) { Log.Error("导入模版元数据出错:" + ex.Message, ex); } return(newvault); }
/// <summary> /// Creates a vault /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the (resource group?) cloud service /// containing the job collection. /// </param> /// <param name='vaultName'> /// Required. The name of the vault to create. /// </param> /// <param name='vaultCreationInput'> /// Required. Vault object to be created /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for the Vm group object. /// </returns> public async Task <VaultCreateResponse> BeginCreatingAsync(string resourceGroupName, string vaultName, VaultCreateArgs vaultCreationInput, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (vaultName == null) { throw new ArgumentNullException("vaultName"); } if (vaultCreationInput == null) { throw new ArgumentNullException("vaultCreationInput"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("vaultName", vaultName); tracingParameters.Add("vaultCreationInput", vaultCreationInput); TracingAdapter.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + "vaults"; url = url + "/"; url = url + Uri.EscapeDataString(vaultName); List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=2015-08-15"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json; charset=utf-8"); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject resourceValue = new JObject(); requestDoc = resourceValue; if (vaultCreationInput.Location != null) { resourceValue["location"] = vaultCreationInput.Location; } if (vaultCreationInput.Sku != null) { JObject skuValue = new JObject(); resourceValue["sku"] = skuValue; if (vaultCreationInput.Sku.Name != null) { skuValue["name"] = vaultCreationInput.Sku.Name; } } if (vaultCreationInput.Properties != null) { JObject propertiesValue = new JObject(); resourceValue["properties"] = propertiesValue; if (vaultCreationInput.Properties.ProvisioningState != null) { propertiesValue["provisioningState"] = vaultCreationInput.Properties.ProvisioningState; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result VaultCreateResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK || statusCode == HttpStatusCode.Created || statusCode == HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new VaultCreateResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); result.Id = idInstance; } JToken nameValue = responseDoc["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); result.Name = nameInstance; } JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); result.Type = typeInstance; } JToken locationValue = responseDoc["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); result.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); result.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue2 = responseDoc["properties"]; if (propertiesValue2 != null && propertiesValue2.Type != JTokenType.Null) { VaultProperties propertiesInstance = new VaultProperties(); result.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue2["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); result.ETag = etagInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ETag")) { result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
//Azure Key Vault sample for managing key vaults - // - Create a key vault // - Authorize an application // - Update a key vault // - alter configurations // - change permissions // - Create another key vault // - List key vaults // - Delete a key vault. public static async Task RunSample(TokenCredential credential) { string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID"); Guid tenantId = new Guid(Environment.GetEnvironmentVariable("AZURE_TENANT_ID")); // Please pre-define the Client's Object in Environment Variable settings string objectId = Environment.GetEnvironmentVariable("AZURE_OBJECT_ID"); string vaultName1 = Utilities.RandomResourceName("vault1", 20); string vaultName2 = Utilities.RandomResourceName("vault2", 20); string rgName = Utilities.RandomResourceName("rgNEMV", 24); string region = "eastus"; var keyVaultManagementClient = new KeyVaultManagementClient(subscriptionId, credential); var vaults = keyVaultManagementClient.Vaults; try { await ResourceGroupHelper.CreateOrUpdateResourceGroup(rgName, region); // Create a key vault with empty access policy Utilities.Log("Creating a key vault..."); var vaultProperties = new VaultProperties(tenantId, new Sku(SkuName.Standard)) { AccessPolicies = new[] { new AccessPolicyEntry(tenantId, objectId, new Permissions()) } }; var vaultParameters = new VaultCreateOrUpdateParameters(region, vaultProperties); var rawResult = await vaults.StartCreateOrUpdateAsync(rgName, vaultName1, vaultParameters); var vault1 = (await rawResult.WaitForCompletionAsync()).Value; Utilities.Log("Created key vault"); Utilities.PrintVault(vault1); // Authorize an application Utilities.Log("Authorizing the application associated with the current service principal..."); var permissions = new Permissions { Keys = new KeyPermissions[] { new KeyPermissions("all") }, Secrets = new SecretPermissions[] { new SecretPermissions("get"), new SecretPermissions("list") }, }; var accessPolicyEntry = new AccessPolicyEntry(tenantId, objectId, permissions); var accessPolicyProperties = new VaultAccessPolicyProperties(new[] { accessPolicyEntry }); var accessPolicyParameters = new VaultAccessPolicyParameters(accessPolicyProperties); await vaults.UpdateAccessPolicyAsync(rgName, vaultName1, AccessPolicyUpdateKind.Add, accessPolicyParameters); vault1 = (await vaults.GetAsync(rgName, vaultName1)).Value; Utilities.Log("Updated key vault"); Utilities.PrintVault(vault1); // Update a key vault Utilities.Log("Update a key vault to enable deployments and add permissions to the application..."); permissions = new Permissions { Secrets = new SecretPermissions[] { new SecretPermissions("all") } }; accessPolicyEntry = new AccessPolicyEntry(tenantId, objectId, permissions); var vaultPatchProperties = new VaultPatchProperties { EnabledForDeployment = true, EnabledForTemplateDeployment = true, AccessPolicies = new[] { accessPolicyEntry } }; var vaultPatchParameters = new VaultPatchParameters { Properties = vaultPatchProperties }; await vaults.UpdateAsync(rgName, vaultName1, vaultPatchParameters); vault1 = (await vaults.GetAsync(rgName, vaultName1)).Value; Utilities.Log("Updated key vault"); // Print the network security group Utilities.PrintVault(vault1); // Create another key vault Utilities.Log("Create another key vault"); permissions = new Permissions { Keys = new KeyPermissions[] { new KeyPermissions("list"), new KeyPermissions("get"), new KeyPermissions("decrypt") }, Secrets = new SecretPermissions[] { new SecretPermissions("get") }, }; accessPolicyEntry = new AccessPolicyEntry(tenantId, objectId, permissions); vaultProperties = new VaultProperties(tenantId, new Sku(SkuName.Standard)) { AccessPolicies = new[] { accessPolicyEntry } }; vaultParameters = new VaultCreateOrUpdateParameters(region, vaultProperties); rawResult = await vaults.StartCreateOrUpdateAsync(rgName, vaultName2, vaultParameters); var vault2 = (await rawResult.WaitForCompletionAsync()).Value; Utilities.Log("Created key vault"); // Print the network security group Utilities.PrintVault(vault2); // List key vaults Utilities.Log("Listing key vaults..."); foreach (var vault in (await vaults.ListByResourceGroupAsync(rgName).ToEnumerableAsync())) { Utilities.PrintVault(vault); } // Delete key vaults Utilities.Log("Deleting the key vaults"); await vaults.DeleteAsync(rgName, vaultName1); await vaults.DeleteAsync(rgName, vaultName2); Utilities.Log("Deleted the key vaults"); } finally { try { await ResourceGroupHelper.DeleteResourceGroup(rgName); } catch (NullReferenceException) { Utilities.Log("Did not create any resources in Azure. No clean up is necessary"); } catch (Exception ex) { Utilities.Log(ex); } } }
protected async Task Initialize() { Client = GetArmClient(); DeletedVaultContainer = Client.DefaultSubscription.GetDeletedVaults(); if (Mode == RecordedTestMode.Playback) { this.ObjectId = Recording.GetVariable(ObjectIdKey, string.Empty); } else if (Mode == RecordedTestMode.Record) { var spClient = new RbacManagementClient(TestEnvironment.TenantId, TestEnvironment.Credential).ServicePrincipals; var servicePrincipalList = spClient.ListAsync($"appId eq '{TestEnvironment.ClientId}'").ToEnumerableAsync().Result; foreach (var servicePrincipal in servicePrincipalList) { this.ObjectId = servicePrincipal.ObjectId; Recording.GetVariable(ObjectIdKey, this.ObjectId); break; } } Location = "North Central US"; ResGroupName = Recording.GenerateAssetName("sdktestrg"); var rgResponse = await Client.DefaultSubscription.GetResourceGroups().CreateOrUpdateAsync(ResGroupName, new ResourceGroupData(Location)).ConfigureAwait(false); ResourceGroup = rgResponse.Value; VaultContainer = ResourceGroup.GetVaults(); VaultName = Recording.GenerateAssetName("sdktestvault"); TenantIdGuid = new Guid(TestEnvironment.TenantId); Tags = new Dictionary <string, string> { { "tag1", "value1" }, { "tag2", "value2" }, { "tag3", "value3" } }; var permissions = new Permissions { Keys = { new KeyPermissions("all") }, Secrets = { new SecretPermissions("all") }, Certificates = { new CertificatePermissions("all") }, Storage = { new StoragePermissions("all") }, }; AccessPolicy = new AccessPolicyEntry(TenantIdGuid, ObjectId, permissions); VaultProperties = new VaultProperties(TenantIdGuid, new Sku(SkuFamily.A, SkuName.Standard)); VaultProperties.EnabledForDeployment = true; VaultProperties.EnabledForDiskEncryption = true; VaultProperties.EnabledForTemplateDeployment = true; VaultProperties.EnableSoftDelete = true; VaultProperties.VaultUri = ""; VaultProperties.NetworkAcls = new NetworkRuleSet() { Bypass = "******", DefaultAction = "Allow", IpRules = { new IPRule("1.2.3.4/32"), new IPRule("1.0.0.0/25") } }; VaultProperties.AccessPolicies.Add(AccessPolicy); ManagedHsmContainer = ResourceGroup.GetManagedHsms(); ManagedHsmProperties = new ManagedHsmProperties(); ManagedHsmProperties.InitialAdminObjectIds.Add(ObjectId); ManagedHsmProperties.CreateMode = CreateMode.Default; ManagedHsmProperties.EnablePurgeProtection = false; ManagedHsmProperties.EnableSoftDelete = true; ManagedHsmProperties.NetworkAcls = new MhsmNetworkRuleSet() { Bypass = "******", DefaultAction = "Deny" //Property properties.networkAcls.ipRules is not supported currently and must be set to null. }; ManagedHsmProperties.PublicNetworkAccess = PublicNetworkAccess.Disabled; ManagedHsmProperties.SoftDeleteRetentionInDays = 10; ManagedHsmProperties.TenantId = TenantIdGuid; }
/// <summary> /// Create a new vault /// </summary> /// <param name="parameters">vault creation parameters</param> /// <param name="adClient">the active directory client</param> /// <returns></returns> public PSKeyVault CreateNewVault(VaultCreationOrUpdateParameters parameters, ActiveDirectoryClient adClient = null, PSKeyVaultNetworkRuleSet networkRuleSet = null) { if (parameters == null) { throw new ArgumentNullException("parameters"); } if (string.IsNullOrWhiteSpace(parameters.Name)) { throw new ArgumentNullException("parameters.Name"); } if (string.IsNullOrWhiteSpace(parameters.ResourceGroupName)) { throw new ArgumentNullException("parameters.ResourceGroupName"); } if (string.IsNullOrWhiteSpace(parameters.Location)) { throw new ArgumentNullException("parameters.Location"); } var properties = new VaultProperties(); if (parameters.CreateMode != CreateMode.Recover) { if (string.IsNullOrWhiteSpace(parameters.SkuFamilyName)) { throw new ArgumentNullException("parameters.SkuFamilyName"); } if (parameters.TenantId == Guid.Empty) { throw new ArgumentException("parameters.TenantId"); } if (!string.IsNullOrWhiteSpace(parameters.SkuName)) { if (Enum.TryParse(parameters.SkuName, true, out SkuName skuName)) { properties.Sku = new Sku(skuName); } else { throw new InvalidEnumArgumentException("parameters.SkuName"); } } properties.EnabledForDeployment = parameters.EnabledForDeployment; properties.EnabledForTemplateDeployment = parameters.EnabledForTemplateDeployment; properties.EnabledForDiskEncryption = parameters.EnabledForDiskEncryption; properties.EnableSoftDelete = parameters.EnableSoftDelete; properties.EnablePurgeProtection = parameters.EnablePurgeProtection; properties.EnableRbacAuthorization = parameters.EnableRbacAuthorization; properties.SoftDeleteRetentionInDays = parameters.SoftDeleteRetentionInDays; properties.TenantId = parameters.TenantId; properties.VaultUri = ""; properties.AccessPolicies = (parameters.AccessPolicy != null) ? new[] { parameters.AccessPolicy } : new AccessPolicyEntry[] { }; properties.NetworkAcls = parameters.NetworkAcls; if (networkRuleSet != null) { UpdateVaultNetworkRuleSetProperties(properties, networkRuleSet); } } else { properties.CreateMode = CreateMode.Recover; } var response = KeyVaultManagementClient.Vaults.CreateOrUpdate( resourceGroupName: parameters.ResourceGroupName, vaultName: parameters.Name, parameters: new VaultCreateOrUpdateParameters { Location = parameters.Location, Tags = TagsConversionHelper.CreateTagDictionary(parameters.Tags, validate: true), Properties = properties }); return(new PSKeyVault(response, adClient)); }
internal static VaultData DeserializeVaultData(JsonElement element) { Optional <string> location = default; Optional <IReadOnlyDictionary <string, string> > tags = default; Optional <SystemData> systemData = default; VaultProperties properties = default; ResourceIdentifier id = default; string name = default; ResourceType type = default; foreach (var property in element.EnumerateObject()) { if (property.NameEquals("location")) { location = property.Value.GetString(); continue; } if (property.NameEquals("tags")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } Dictionary <string, string> dictionary = new Dictionary <string, string>(); foreach (var property0 in property.Value.EnumerateObject()) { dictionary.Add(property0.Name, property0.Value.GetString()); } tags = dictionary; continue; } if (property.NameEquals("systemData")) { if (property.Value.ValueKind == JsonValueKind.Null) { property.ThrowNonNullablePropertyIsNull(); continue; } systemData = SystemData.DeserializeSystemData(property.Value); continue; } if (property.NameEquals("properties")) { properties = VaultProperties.DeserializeVaultProperties(property.Value); continue; } if (property.NameEquals("id")) { id = property.Value.GetString(); continue; } if (property.NameEquals("name")) { name = property.Value.GetString(); continue; } if (property.NameEquals("type")) { type = property.Value.GetString(); continue; } } return(new VaultData(id, name, type, location.Value, Optional.ToDictionary(tags), systemData.Value, properties)); }
public override async Task <ActionResponse> ExecuteActionAsync(ActionRequest request) { string azureToken = request.DataStore.GetJson("AzureTokenKV", "access_token"); string refreshToken = request.DataStore.GetJson("AzureTokenKV", "refresh_token"); string crmToken = request.DataStore.GetJson("MsCrmToken", "access_token"); string resourceGroup = request.DataStore.GetValue("SelectedResourceGroup"); string vaultName = request.DataStore.GetValue("VaultName") ?? "bpstv-" + RandomGenerator.GetRandomLowerCaseCharacters(12); string secretName = request.DataStore.GetValue("SecretName") ?? "bpst-mscrm-secret"; string connectionString = request.DataStore.GetAllValues("SqlConnectionString")[0]; string organizationId = request.DataStore.GetValue("OrganizationId"); _subscriptionId = request.DataStore.GetJson("SelectedSubscription", "SubscriptionId"); RetrieveKVToken(refreshToken, request.Info.WebsiteRootUrl, request.DataStore); RetrieveGraphToken(refreshToken, request.Info.WebsiteRootUrl, request.DataStore); SubscriptionCloudCredentials credentials = new TokenCloudCredentials(_subscriptionId, azureToken); // Get user's object ID and tenant ID (in the Azure subscription where the vault is created) string oid = null; int propCount = 0; foreach (var c in new JwtSecurityToken(azureToken).Claims) { switch (c.Type.ToLowerInvariant()) { case "oid": oid = c.Value; propCount++; break; case "tid": _tenantId = c.Value; propCount++; break; } if (propCount >= 2) { break; } } // Get user's tenant ID in the CRM implicit subscription string crmtenantId = null; foreach (var c in new JwtSecurityToken(crmToken).Claims) { if (c.Type.EqualsIgnoreCase("tid")) { crmtenantId = c.Value; break; } } try { TokenCredentials credentialsKv = new TokenCredentials(azureToken); using (KeyVaultManagementClient client = new KeyVaultManagementClient(credentialsKv)) { client.SubscriptionId = _subscriptionId; // Check if a vault already exists var vaults = client.Vaults.ListByResourceGroup(resourceGroup); foreach (var v in client.Vaults.ListByResourceGroup(resourceGroup)) { if (v.Name.EqualsIgnoreCase(vaultName)) { client.Vaults.Delete(resourceGroup, vaultName); break; } } // Create the vault string vaultUrl = null; using (ResourceManagementClient resourceClient = new ResourceManagementClient(credentials)) { // Set properties VaultProperties p = new VaultProperties() { Sku = new Sku(SkuName.Standard), TenantId = new Guid(_tenantId), AccessPolicies = new List <AccessPolicyEntry>() }; // Access policy for the owner AccessPolicyEntry apeOwner = new AccessPolicyEntry(); apeOwner.Permissions = new Permissions(new[] { "get", "create", "delete", "list", "update", "import", "backup", "restore" }, new[] { "all" }, new[] { "all" }); apeOwner.TenantId = p.TenantId; apeOwner.ObjectId = oid; p.AccessPolicies.Add(apeOwner); // Access policy for the CRM exporter AccessPolicyEntry ape = new AccessPolicyEntry(); ape.Permissions = new Permissions(null, new[] { "get" }); ape.TenantId = p.TenantId; ape.ObjectId = GetCrmConnectorObjectID(_graphToken, _tenantId).Result; p.AccessPolicies.Add(ape); VaultCreateOrUpdateParameters vaultParams = new VaultCreateOrUpdateParameters() { Location = resourceClient.ResourceGroups.Get(resourceGroup).ResourceGroup.Location, Properties = p }; Vault vault = client.Vaults.CreateOrUpdate(resourceGroup, vaultName, vaultParams); vaultUrl = vault.Properties.VaultUri; Thread.Sleep(15000); // The vault DNS entry isn't there immediatly } // Create the secret KeyVaultClient kvClient = new KeyVaultClient(new TokenCredentials(_kvToken)); SecretBundle secret = await kvClient.SetSecretAsync(vaultUrl, secretName, connectionString, new Dictionary <string, string>() { { organizationId, crmtenantId } }, null /* Do I need to set a content type? */, new SecretAttributes() { Enabled = true }); request.DataStore.AddToDataStore("KeyVault", secret.Id, DataStoreType.Private); } } catch (Exception) { throw; } //Log kv name request.Logger.LogResource(request.DataStore, vaultName, DeployedResourceType.KeyVault, CreatedBy.BPST, DateTime.UtcNow.ToString("o")); return(new ActionResponse(ActionStatus.Success, JsonUtility.GetEmptyJObject(), true)); }
/// <summary> /// Create a new vault /// </summary> /// <param name="parameters">vault creation parameters</param> /// <param name="adClient">the active directory client</param> /// <returns></returns> public PSKeyVault CreateNewVault(VaultCreationParameters parameters, ActiveDirectoryClient adClient = null) { if (parameters == null) { throw new ArgumentNullException("parameters"); } if (string.IsNullOrWhiteSpace(parameters.VaultName)) { throw new ArgumentNullException("parameters.VaultName"); } if (string.IsNullOrWhiteSpace(parameters.ResourceGroupName)) { throw new ArgumentNullException("parameters.ResourceGroupName"); } if (string.IsNullOrWhiteSpace(parameters.Location)) { throw new ArgumentNullException("parameters.Location"); } var properties = new VaultProperties(); if (parameters.CreateMode != CreateMode.Recover) { if (string.IsNullOrWhiteSpace(parameters.SkuFamilyName)) { throw new ArgumentNullException("parameters.SkuFamilyName"); } if (parameters.TenantId == Guid.Empty) { throw new ArgumentException("parameters.TenantId"); } properties.Sku = new Sku { Name = parameters.SkuName, }; properties.EnabledForDeployment = parameters.EnabledForDeployment; properties.EnabledForTemplateDeployment = parameters.EnabledForTemplateDeployment; properties.EnabledForDiskEncryption = parameters.EnabledForDiskEncryption; properties.EnableSoftDelete = parameters.EnableSoftDelete.HasValue && parameters.EnableSoftDelete.Value ? true : (bool?)null; properties.EnablePurgeProtection = parameters.EnablePurgeProtection.HasValue && parameters.EnablePurgeProtection.Value ? true : (bool?)null; // properties.SoftDeleteRetentionInDays = parameters.SoftDeleteRetentionInDays; properties.TenantId = parameters.TenantId; properties.VaultUri = ""; properties.AccessPolicies = (parameters.AccessPolicy != null) ? new[] { parameters.AccessPolicy } : new AccessPolicyEntry[] { }; properties.NetworkAcls = parameters.NetworkAcls; } else { properties.CreateMode = CreateMode.Recover; } var response = KeyVaultManagementClient.Vaults.CreateOrUpdate( resourceGroupName: parameters.ResourceGroupName, vaultName: parameters.VaultName, parameters: new VaultCreateOrUpdateParameters { Location = parameters.Location, Tags = TagsConversionHelper.CreateTagDictionary(parameters.Tags, validate: true), Properties = properties }); return(new PSKeyVault(response, adClient)); }
/// <summary> /// Get the Vaults. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the (resource group?) cloud service /// containing the vault collection. /// </param> /// <param name='customRequestHeaders'> /// Optional. Request header parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response model for Vault. /// </returns> public async Task <VaultListResponse> GetAsync(string resourceGroupName, CustomRequestHeaders customRequestHeaders, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("customRequestHeaders", customRequestHeaders); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/Subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + Uri.EscapeDataString(this.Client.ResourceNamespace); url = url + "/"; url = url + "vaults"; List <string> queryParameters = new List <string>(); queryParameters.Add("api-version=2015-08-15"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept-Language", customRequestHeaders.Culture); httpRequest.Headers.Add("x-ms-client-request-id", customRequestHeaders.ClientRequestId); httpRequest.Headers.Add("x-ms-version", "2015-01-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result VaultListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new VaultListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken valueArray = responseDoc["value"]; if (valueArray != null && valueArray.Type != JTokenType.Null) { foreach (JToken valueValue in ((JArray)valueArray)) { Vault vaultInstance = new Vault(); result.Vaults.Add(vaultInstance); JToken idValue = valueValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); vaultInstance.Id = idInstance; } JToken nameValue = valueValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); vaultInstance.Name = nameInstance; } JToken typeValue = valueValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { string typeInstance = ((string)typeValue); vaultInstance.Type = typeInstance; } JToken locationValue = valueValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); vaultInstance.Location = locationInstance; } JToken tagsSequenceElement = ((JToken)valueValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); vaultInstance.Tags.Add(tagsKey, tagsValue); } } JToken propertiesValue = valueValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { VaultProperties propertiesInstance = new VaultProperties(); vaultInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { string provisioningStateInstance = ((string)provisioningStateValue); propertiesInstance.ProvisioningState = provisioningStateInstance; } } JToken eTagValue = valueValue["eTag"]; if (eTagValue != null && eTagValue.Type != JTokenType.Null) { string eTagInstance = ((string)eTagValue); vaultInstance.ETag = eTagInstance; } } } } } result.StatusCode = statusCode; if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return(result); } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } }
internal VaultData(ResourceIdentifier id, string name, ResourceType resourceType, SystemData systemData, IDictionary <string, string> tags, AzureLocation location, VaultProperties properties) : base(id, name, resourceType, systemData, tags, location) { Properties = properties; }
static async Task Main(string[] args) { string subscriptionId = Environment.GetEnvironmentVariable("AZURE_SUBSCRIPTION_ID"); Guid tenantId = new Guid(Environment.GetEnvironmentVariable("AZURE_TENANT_ID")); string objectId = Environment.GetEnvironmentVariable("AZURE_OBJECT_ID"); string location = "eastus2"; var credential = new DefaultAzureCredential(); var resourceClient = new ResourcesManagementClient(subscriptionId, credential); var resourceGroups = resourceClient.ResourceGroups; var keyVaultManagementClient = new KeyVaultManagementClient(subscriptionId, credential); var vaults = keyVaultManagementClient.Vaults; // Create Resource Group Console.WriteLine("Creating Resource Group: " + rgName); var resourceGroup = new ResourceGroup(location); await resourceGroups.CreateOrUpdateAsync(rgName, resourceGroup); Console.WriteLine("Created Resource Group: " + rgName); // Prepare creatable KeyVaults var creatableKeyVaults = new Dictionary <string, VaultCreateOrUpdateParameters> { }; for (int i = 1; i <= 10; i++) { string vaultName = "sdk-perf-vault" + i; var vaultProperties = new VaultProperties(tenantId, new Azure.ResourceManager.KeyVault.Models.Sku(SkuName.Standard)) { AccessPolicies = new[] { new AccessPolicyEntry(tenantId, objectId, new Permissions()) } }; var vaultParameters = new VaultCreateOrUpdateParameters(location, vaultProperties); creatableKeyVaults.Add(vaultName, vaultParameters); } // Create KeyVaults var t1 = DateTimeOffset.Now.UtcDateTime; Console.WriteLine("Creating the KeyVaults"); List <Task> TaskList = new List <Task>(); foreach (var item in creatableKeyVaults) { Task task = CreateKeyVaults(vaults, item.Key, item.Value); TaskList.Add(task); } await Task.WhenAll(TaskList.ToArray()); var t2 = DateTimeOffset.Now.UtcDateTime; Console.WriteLine("Created KeyVaults"); Console.WriteLine($"KeyVaults create: took {(t2 - t1).TotalSeconds } seconds to create 10 KeyVaults !!"); // List Console.WriteLine("Listing the KeyVaults 100 times"); t1 = DateTimeOffset.Now.UtcDateTime; List <Task> TaskList2 = new List <Task>(); for (int i = 0; i < 100; i++) { Task task = ListVault(vaults); TaskList2.Add(task); } await Task.WhenAll(TaskList2.ToArray()); t2 = DateTimeOffset.Now.UtcDateTime; Console.WriteLine($"KeyVaults list: took {(t2 - t1).TotalMilliseconds } milliseconds to list 10 KeyVaults 100 times !!"); // Delete ResourceGroup Console.WriteLine("Deleting Resource Group: " + rgName); await(await resourceGroups.StartDeleteAsync(rgName)).WaitForCompletionAsync(); Console.WriteLine("Deleted Resource Group: " + rgName); }
protected async Task Initialize() { Location = AzureLocation.CanadaCentral; Client = GetArmClient(); Subscription = await Client.GetDefaultSubscriptionAsync(); DeletedVaultCollection = Subscription.GetDeletedVaults(); if (Mode == RecordedTestMode.Playback) { this.ObjectId = Recording.GetVariable(ObjectIdKey, string.Empty); } else if (Mode == RecordedTestMode.Record) { // Get ObjectId of Service Principal // [warning] Microsoft.Graph required corresponding api permission, Please make sure the service has these two api permissions as follows. // 1. ServicePrincipalEndpoint.Read.All(TYPE-Application) 2.ServicePrincipalEndpoint.ReadWrite.All(TYPE-Application) var scopes = new[] { "https://graph.microsoft.com/.default" }; var options = new TokenCredentialOptions { AuthorityHost = AzureAuthorityHosts.AzurePublicCloud }; var clientSecretCredential = new ClientSecretCredential(TestEnvironment.TenantId, TestEnvironment.ClientId, TestEnvironment.ClientSecret, options); var graphClient = new GraphServiceClient(clientSecretCredential, scopes); var response = await graphClient.ServicePrincipals.Request().GetAsync(); var result = response.CurrentPage.Where(i => i.AppId == TestEnvironment.ClientId).FirstOrDefault(); this.ObjectId = result.Id; Recording.GetVariable(ObjectIdKey, this.ObjectId); } ResGroupName = Recording.GenerateAssetName("sdktestrg-kv-"); ArmOperation <ResourceGroupResource> rgResponse = await Subscription.GetResourceGroups().CreateOrUpdateAsync(WaitUntil.Completed, ResGroupName, new ResourceGroupData(Location)).ConfigureAwait(false); ResourceGroupResource = rgResponse.Value; VaultCollection = ResourceGroupResource.GetVaults(); VaultName = Recording.GenerateAssetName("sdktest-vault-"); MHSMName = Recording.GenerateAssetName("sdktest-mhsm-"); TenantIdGuid = new Guid(TestEnvironment.TenantId); Tags = new Dictionary <string, string> { { "tag1", "value1" }, { "tag2", "value2" }, { "tag3", "value3" } }; IdentityAccessPermissions permissions = new IdentityAccessPermissions { Keys = { new KeyPermission("all") }, Secrets = { new SecretPermission("all") }, Certificates = { new CertificatePermission("all") }, Storage = { new StoragePermission("all") }, }; AccessPolicy = new VaultAccessPolicy(TenantIdGuid, ObjectId, permissions); VaultProperties = new VaultProperties(TenantIdGuid, new KeyVaultSku(KeyVaultSkuFamily.A, KeyVaultSkuName.Standard)); VaultProperties.EnabledForDeployment = true; VaultProperties.EnabledForDiskEncryption = true; VaultProperties.EnabledForTemplateDeployment = true; VaultProperties.EnableSoftDelete = true; VaultProperties.SoftDeleteRetentionInDays = DefSoftDeleteRetentionInDays; VaultProperties.VaultUri = new Uri("http://vaulturi.com"); VaultProperties.NetworkRuleSet = new VaultNetworkRuleSet() { Bypass = "******", DefaultAction = "Allow", IPRules = { new VaultIPRule("1.2.3.4/32"), new VaultIPRule("1.0.0.0/25") } }; VaultProperties.AccessPolicies.Add(AccessPolicy); ManagedHsmCollection = ResourceGroupResource.GetManagedHsms(); ManagedHsmProperties = new ManagedHsmProperties(); ManagedHsmProperties.InitialAdminObjectIds.Add(ObjectId); ManagedHsmProperties.CreateMode = ManagedHsmCreateMode.Default; ManagedHsmProperties.EnableSoftDelete = true; ManagedHsmProperties.SoftDeleteRetentionInDays = DefSoftDeleteRetentionInDays; ManagedHsmProperties.EnablePurgeProtection = false; ManagedHsmProperties.NetworkRuleSet = new ManagedHsmNetworkRuleSet() { Bypass = "******", DefaultAction = "Deny" //Property properties.networkAcls.ipRules is not supported currently and must be set to null. }; ManagedHsmProperties.PublicNetworkAccess = PublicNetworkAccess.Disabled; ManagedHsmProperties.TenantId = TenantIdGuid; }