private async Task ReplaceSchedulingGroupAsync(IMicrosoftGraphClient client, string teamId, string teamsSchedulingGroupId, IList <string> userIds)
        {
            // to ensure that we minimise concurrency issues, we should ensure we have populated
            // the members cache first
            var teamMembers = await GetMemberIdsAsync(client, teamId);

            var group = await client.GetSchedulingGroupAsync(teamId, teamsSchedulingGroupId);

            var usersToAdd = userIds.Except(group.UserIds).ToList();

            if (usersToAdd.Count > 0)
            {
                // ensure that all users are actually in the Team and remove any that aren't
                RemoveInvalidUsers(usersToAdd, teamMembers);
                if (usersToAdd.Count == 0)
                {
                    return;
                }

                if (group.UserIds == null)
                {
                    group.UserIds = userIds;
                }
                else
                {
                    ((List <string>)group.UserIds).AddRange(usersToAdd);
                }

                await client.ReplaceSchedulingGroupAsync(group, group.Etag, teamId, teamsSchedulingGroupId);
            }
        }
        public PSKeyVault(Vault vault, IMicrosoftGraphClient graphClient)
        {
            var vaultTenantDisplayName = ModelExtensions.GetDisplayNameForTenant(vault.Properties.TenantId, graphClient);

            VaultName         = vault.Name;
            Location          = vault.Location;
            ResourceId        = vault.Id;
            ResourceGroupName = (new ResourceIdentifier(vault.Id)).ResourceGroupName;
            Tags                         = TagsConversionHelper.CreateTagHashtable(vault.Tags);
            Sku                          = vault.Properties.Sku.Name.ToString();
            TenantId                     = vault.Properties.TenantId;
            TenantName                   = vaultTenantDisplayName;
            VaultUri                     = vault.Properties.VaultUri;
            EnabledForDeployment         = vault.Properties.EnabledForDeployment ?? false;
            EnabledForTemplateDeployment = vault.Properties.EnabledForTemplateDeployment;
            EnabledForDiskEncryption     = vault.Properties.EnabledForDiskEncryption;
            EnableSoftDelete             = vault.Properties.EnableSoftDelete;
            EnablePurgeProtection        = vault.Properties.EnablePurgeProtection;
            EnableRbacAuthorization      = vault.Properties.EnableRbacAuthorization;
            PublicNetworkAccess          = vault.Properties.PublicNetworkAccess;
            SoftDeleteRetentionInDays    = vault.Properties.SoftDeleteRetentionInDays;
            AccessPolicies               = vault.Properties.AccessPolicies.Select(s => new PSKeyVaultAccessPolicy(s, graphClient)).ToArray();
            NetworkAcls                  = InitNetworkRuleSet(vault.Properties);
            OriginalVault                = vault;
        }
        /// <summary>
        /// Get an existing vault. Returns null if vault is not found.
        /// </summary>
        /// <param name="vaultName">vault name</param>
        /// <param name="resourceGroupName">resource group name</param>
        /// <param name="graphClient">the active directory client</param>
        /// <returns>the retrieved vault</returns>
        public PSKeyVault GetVault(string vaultName, string resourceGroupName, IMicrosoftGraphClient graphClient = null)
        {
            if (string.IsNullOrWhiteSpace(vaultName))
            {
                throw new ArgumentNullException("vaultName");
            }
            if (string.IsNullOrWhiteSpace(resourceGroupName))
            {
                throw new ArgumentNullException("resourceGroupName");
            }

            try
            {
                var response = KeyVaultManagementClient.Vaults.Get(resourceGroupName, vaultName);

                return(new PSKeyVault(response, graphClient));
            }
            catch (CloudException ce)
            {
                if (ce.Response.StatusCode == HttpStatusCode.NotFound)
                {
                    return(null);
                }
                throw;
            }
        }
 public static async Task <ShiftCollectionResponse> ListShiftsNextPageAsync(this IMicrosoftGraphClient operations, string url, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.ListNextPageWithHttpMessagesAsync <ShiftCollectionResponse>(url, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Beispiel #5
0
        private async Task ReplaceSchedulingGroupAsync(IMicrosoftGraphClient client, string teamId, string teamsSchedulingGroupId, IList <string> userIds)
        {
            var teamMembers = await _cacheService.GetKeyAsync <List <string> >(ApplicationConstants.TableNameEmployeeLists, teamId).ConfigureAwait(false);

            var group = await client.GetSchedulingGroupAsync(teamId, teamsSchedulingGroupId).ConfigureAwait(false);

            var usersToAdd = userIds.Except(group.UserIds).ToList();

            if (usersToAdd.Count > 0)
            {
                // ensure that all users are actually in the Team and remove any that aren't
                RemoveInvalidUsers(usersToAdd, teamMembers);
                if (usersToAdd.Count == 0)
                {
                    return;
                }

                if (group.UserIds == null)
                {
                    group.UserIds = userIds;
                }
                else
                {
                    ((List <string>)group.UserIds).AddRange(usersToAdd);
                }

                await client.ReplaceSchedulingGroupAsync(group, group.Etag, teamId, teamsSchedulingGroupId).ConfigureAwait(false);
            }
        }
        private async Task <List <string> > GetMemberIdsAsync(IMicrosoftGraphClient client, string teamId)
        {
            await LoadMembersAsync(client, teamId);

            return(_teamMembers[teamId]
                   .Select(m => m.Value.DestinationId)
                   .ToList());
        }
Beispiel #7
0
 public static string GetDisplayNameForTenant(Guid id, IMicrosoftGraphClient graphClient)
 {
     if (id == null)
     {
         return(string.Empty);
     }
     return(id.ToString());
 }
Beispiel #8
0
        public static IEnumerable <MicrosoftGraphUser> FilterUsers(this IMicrosoftGraphClient client, MicrosoftObjectFilterOptions options)
        {
            if (!string.IsNullOrEmpty(options.Id))
            {
                try
                {
                    MicrosoftGraphUser user = client.Users.GetUser(options.Id);
                    if (user != null)
                    {
                        return(new List <MicrosoftGraphUser> {
                            user
                        });
                    }
                }
                catch { /* The group does not exist, ignore the exception */ }
            }
            else if (!string.IsNullOrEmpty(options.UPN) || !string.IsNullOrEmpty(options.Mail))
            {
                IList <MicrosoftGraphUser> result = null;
                try
                {
                    string upnOrMail  = options.UPN ?? options.Mail;
                    var    odataQuery = new ODataQuery <MicrosoftGraphUser>();
                    if (!string.IsNullOrEmpty(options.UPN))
                    {
                        odataQuery.SetFilter(u => u.UserPrincipalName == upnOrMail);
                    }
                    else
                    {
                        odataQuery.SetFilter(u => u.Mail == upnOrMail);
                    }
                    result = client.Users.ListUser(filter: FormatFilterString(odataQuery)).Value;
                }
                catch { /* The user does not exist, ignore the exception. */ }

                if (result != null)
                {
                    return(result.Select(u => u));
                }
            }
            else
            {
                ODataQuery <MicrosoftGraphUser> odataQuery = null;
                if (!string.IsNullOrEmpty(options.SearchString) && options.SearchString.EndsWith("*"))
                {
                    options.SearchString = options.SearchString.TrimEnd('*');
                    odataQuery           = new ODataQuery <MicrosoftGraphUser>(u => u.DisplayName.StartsWith(options.SearchString));
                }
                else
                {
                    odataQuery = new ODataQuery <MicrosoftGraphUser>(u => u.DisplayName == options.SearchString);
                }

                return(client.Users.ListUser(filter: FormatFilterString(odataQuery)).Value);
            }

            return(new List <MicrosoftGraphUser>());
        }
        private async Task RemoveUsersFromSchedulingGroupAsync(IMicrosoftGraphClient client, string teamId, string schedulingGroupId)
        {
            var group = await client.GetSchedulingGroupAsync(teamId, schedulingGroupId);

            group.UserIds?.Clear();
            var response = await client.ReplaceSchedulingGroupAsync(group, group.Etag, teamId, group.Id);

            response.ThrowIfError();
        }
 public TimeTriggerFunctions(IHttpClientFactory httpClientFactory, IMicrosoftGraphClient microsoftGraphClient,
                             IInvestecOpenBankingClient
                             investecOpenBankingClient)
 {
     _httpClient                = httpClientFactory.CreateClient();
     _microsoftGraphClient      = microsoftGraphClient;
     _investecOpenBankingClient = investecOpenBankingClient;
     _sharePointGroupId         = Environment.GetEnvironmentVariable("SharePointGroupId");
 }
Beispiel #11
0
        private async Task <string> GetSchedulingGroupIdByNameAsync(IMicrosoftGraphClient client, string teamId, string groupName)
        {
            // update the cache with the most current set of groups from teams
            var schedulingGroups = await RefreshCachedSchedulingGroupsAsync(client, teamId).ConfigureAwait(false);

            var group = schedulingGroups.Find(g => g.Name.Equals(groupName, StringComparison.OrdinalIgnoreCase));

            return(group?.Id);
        }
Beispiel #12
0
        /// <summary>
        /// Gets the scheduling groups dictionary from cache if it is present there, otherwise gets
        /// the list from Teams
        /// </summary>
        /// <param name="client">The client used to communicate with Teams</param>
        /// <param name="teamId">The id of the team to get the scheduling groups for.</param>
        /// <returns></returns>
        private async Task <List <SchedulingGroupModel> > GetSchedulingGroupsAsync(IMicrosoftGraphClient client, string teamId)
        {
            // firstly get the scheduling groups from cache
            var schedulingGroups = await _cacheService.GetKeyAsync <List <SchedulingGroupModel> >(ApplicationConstants.TableNameGroupLists, teamId).ConfigureAwait(false);

            if (schedulingGroups == null || schedulingGroups.Count == 0)
            {
                schedulingGroups = await RefreshCachedSchedulingGroupsAsync(client, teamId).ConfigureAwait(false);
            }

            return(schedulingGroups);
        }
Beispiel #13
0
 public PSKeyVaultAccessPolicy(KeyVaultManagement.Models.AccessPolicyEntry s, IMicrosoftGraphClient graphClient)
 {
     ObjectId                  = s.ObjectId;
     DisplayName               = ModelExtensions.GetDisplayNameForADObject(s.ObjectId, graphClient);
     ApplicationId             = s.ApplicationId;
     TenantId                  = s.TenantId;
     TenantName                = s.TenantId.ToString();
     PermissionsToSecrets      = s.Permissions.Secrets == null ? new List <string>() : new List <string>(s.Permissions.Secrets);
     PermissionsToKeys         = s.Permissions.Keys == null ? new List <string>() : new List <string>(s.Permissions.Keys);
     PermissionsToCertificates = s.Permissions.Certificates == null ? new List <string>() : new List <string>(s.Permissions.Certificates);
     PermissionsToStorage      = s.Permissions.Storage == null ? new List <string>() : new List <string>(s.Permissions.Storage);
 }
Beispiel #14
0
        public static (string, string) GetDetailsFromADObjectId(string objectId, IMicrosoftGraphClient graphClient)
        {
            var displayName = "";
            var upnOrSpn    = "";
            var objectType  = "Unknown";

            if (graphClient == null || string.IsNullOrWhiteSpace(objectId))
            {
                return(displayName, objectType);
            }

            try
            {
                var obj = graphClient.DirectoryObjects.GetDirectoryObject(objectId);
                if (obj != null)
                {
                    if (obj.Odatatype.Equals("#microsoft.graph.user", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var user = graphClient.Users.GetUser(objectId);
                        displayName = user.DisplayName;
                        upnOrSpn    = user.UserPrincipalName;
                        objectType  = "User";
                    }
                    else if (obj.Odatatype.Equals("#microsoft.graph.serviceprincipal", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var servicePrincipal = graphClient.ServicePrincipals.GetServicePrincipal(objectId);
                        displayName = servicePrincipal.DisplayName;
                        upnOrSpn    = servicePrincipal.ServicePrincipalNames.FirstOrDefault();
                        objectType  = "Service Principal";
                    }
                    else if (obj.Odatatype.Equals("#microsoft.graph.group", StringComparison.InvariantCultureIgnoreCase))
                    {
                        var group = graphClient.Groups.GetGroup(objectId);
                        displayName = group.DisplayName;
                        objectType  = "Group";
                    }
                }
            }
            catch
            {
                // Error occurred. Don't get the friendly name
            }

            return(
                displayName + (!string.IsNullOrWhiteSpace(upnOrSpn) ? (" (" + upnOrSpn + ")") : ""),
                objectType
                );
        }
Beispiel #15
0
 public MicrosoftAuthenticationController(
     MicrosoftGraphConfiguration configuration,
     IMicrosoftGraphClient microsoftGraphClient,
     IJwtService jwtService,
     IMapper mapper,
     IRngUtil rngUtil,
     ISocialMediaUserLinkService socialMediaUserLinkService
     )
 {
     _configuration        = configuration;
     _microsoftGraphClient = microsoftGraphClient;
     _jwtService           = jwtService;
     _mapper  = mapper;
     _rngUtil = rngUtil;
     _socialMediaUserLinkService = socialMediaUserLinkService;
 }
        private async Task LoadMembersAsync(IMicrosoftGraphClient client, string teamId)
        {
            if (!_teamMembers.ContainsKey(teamId))
            {
                // get the list of members of the team from teams - 999 is the maximum that can be returned in a single call
                var response = await client.GetMembersAsync(teamId, "id,displayName,userPrincipalName", 999);

                var employees = response.Value
                                .Select(m => new EmployeeModel
                {
                    DestinationId = m.Id,
                    DisplayName   = m.DisplayName,
                    LoginName     = m.UserPrincipalName
                });

                _teamMembers.GetValueOrCreate(teamId)
                .AddRange(employees, e => e.LoginName);
            }
        }
Beispiel #17
0
        public static IEnumerable <MicrosoftGraphGroup> FilterGroups(this IMicrosoftGraphClient client, MicrosoftObjectFilterOptions options)
        {
            if (!string.IsNullOrEmpty(options.Id))
            {
                try
                {
                    // use GetObjectsByObjectId to handle Redirects in the CSP scenario
                    MicrosoftGraphGroup group = client.Groups.GetGroup(options.Id);
                    if (group != null)
                    {
                        return(new List <MicrosoftGraphGroup> {
                            group
                        });
                    }
                }
                catch { /* The group does not exist, ignore the exception */ }
            }
            else
            {
                ODataQuery <MicrosoftGraphGroup> odataQuery = null;
                if (options.Mail != null)
                {
                    odataQuery = new ODataQuery <MicrosoftGraphGroup>(g => g.Mail == options.Mail);
                }
                else
                {
                    if (!string.IsNullOrEmpty(options.SearchString) && options.SearchString.EndsWith("*"))
                    {
                        options.SearchString = options.SearchString.TrimEnd('*');
                        odataQuery           = new ODataQuery <MicrosoftGraphGroup>(g => g.DisplayName.StartsWith(options.SearchString));
                    }
                    else
                    {
                        odataQuery = new ODataQuery <MicrosoftGraphGroup>(g => g.DisplayName == options.SearchString);
                    }
                }

                return(client.Groups.ListGroup(filter: FormatFilterString(odataQuery)).Value);
            }

            return(new List <MicrosoftGraphGroup>());
        }
Beispiel #18
0
        /// <summary>
        /// Update an existing vault. Only EnablePurgeProtection, EnableRbacAuthorization and Tags can be updated currently.
        /// </summary>
        /// <param name="existingVault">the existing vault</param>
        /// <param name="updatedParamater">updated paramater</param>
        /// <param name="graphClient">the active directory client</param>
        /// <returns>the updated vault</returns>
        public PSKeyVault UpdateVault(
            PSKeyVault existingVault,
            VaultCreationOrUpdateParameters updatedParamater,
            IMicrosoftGraphClient graphClient = 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
            var properties = existingVault.OriginalVault.Properties;

            if (!(properties.EnablePurgeProtection.HasValue && properties.EnablePurgeProtection.Value) &&
                updatedParamater.EnablePurgeProtection.HasValue &&
                updatedParamater.EnablePurgeProtection.Value)
            {
                properties.EnablePurgeProtection = updatedParamater.EnablePurgeProtection;
            }

            properties.EnableRbacAuthorization = updatedParamater.EnableRbacAuthorization;
            properties.PublicNetworkAccess     = string.IsNullOrEmpty(updatedParamater.PublicNetworkAccess)?
                                                 existingVault.PublicNetworkAccess : updatedParamater.PublicNetworkAccess;

            var response = KeyVaultManagementClient.Vaults.CreateOrUpdate(
                resourceGroupName: existingVault.ResourceGroupName,
                vaultName: existingVault.VaultName,
                parameters: new VaultCreateOrUpdateParameters
            {
                Location   = existingVault.Location,
                Properties = properties,
                Tags       = TagsConversionHelper.CreateTagDictionary(updatedParamater.Tags, validate: true)
            }
                );

            return(new PSKeyVault(response, graphClient));
        }
        private List <PSManagedHsm> ListManagedHsmsBySubscription(IMicrosoftGraphClient graphClient = null)
        {
            List <PSManagedHsm> managedHsms = new List <PSManagedHsm>();
            IPage <ManagedHsm>  response    = KeyVaultManagementClient.ManagedHsms.ListBySubscriptionAsync().GetAwaiter().GetResult();

            foreach (var managedHsm in response)
            {
                managedHsms.Add(new PSManagedHsm(managedHsm, graphClient));
            }

            while (response?.NextPageLink != null)
            {
                response = KeyVaultManagementClient.ManagedHsms.ListBySubscriptionNextAsync(response.NextPageLink).GetAwaiter().GetResult();

                foreach (var managedHsm in response)
                {
                    managedHsms.Add(new PSManagedHsm(managedHsm, graphClient));
                }
            }

            return(managedHsms);
        }
        private async Task <string> GetSchedulingGroupIdByNameAsync(IMicrosoftGraphClient client, string teamId, string groupName)
        {
            // check the cached active groups first
            var groups = await GetSchedulingGroupsAsync(client, teamId);

            if (groups.ContainsKey(groupName))
            {
                return(groups[groupName]);
            }

            var response = await client.ListSchedulingGroupsAsync(teamId);

            var group = response.Value.Where(g => g.IsActive && g.DisplayName.Equals(groupName, StringComparison.OrdinalIgnoreCase)).OrderByDescending(g => g.CreatedDateTime).FirstOrDefault();

            if (group != null)
            {
                // we have found the group in teams, so update the cache while we are here
                groups[groupName] = group.Id;
                return(group.Id);
            }

            return(null);
        }
Beispiel #21
0
        public PSManagedHsm(ManagedHsm managedHsm, IMicrosoftGraphClient graphClient)
        {
            // PSKeyVaultIdentityItem's properties
            ResourceId        = managedHsm.Id;
            VaultName         = managedHsm.Name;
            ResourceGroupName = (new ResourceIdentifier(managedHsm.Id)).ResourceGroupName;
            Location          = managedHsm.Location;
            Tags = TagsConversionHelper.CreateTagHashtable(managedHsm.Tags);

            // PSManagedHsm's properties, hides type
            Name                      = managedHsm.Name;
            Sku                       = managedHsm.Sku.Name.ToString();
            TenantId                  = managedHsm.Properties.TenantId.Value;
            TenantName                = ModelExtensions.GetDisplayNameForTenant(TenantId, graphClient);
            InitialAdminObjectIds     = managedHsm.Properties.InitialAdminObjectIds.ToArray <string>();
            HsmUri                    = managedHsm.Properties.HsmUri;
            EnablePurgeProtection     = managedHsm.Properties.EnablePurgeProtection;
            EnableSoftDelete          = managedHsm.Properties.EnableSoftDelete;
            SoftDeleteRetentionInDays = managedHsm.Properties.SoftDeleteRetentionInDays;
            StatusMessage             = managedHsm.Properties.StatusMessage;
            ProvisioningState         = managedHsm.Properties.ProvisioningState;
            OriginalManagedHsm        = managedHsm;
        }
        /// <summary>
        /// Update an existing Managed HSM.
        /// </summary>
        /// <param name="existingManagedHsm">existing Managed HSM</param>
        /// <param name="parameters">HSM update parameters</param>
        /// <param name="graphClient">the active directory client</param>
        /// <returns>the updated Managed HSM</returns>
        public PSManagedHsm UpdateManagedHsm(PSManagedHsm existingManagedHsm, VaultCreationOrUpdateParameters parameters, IMicrosoftGraphClient graphClient = null)
        {
            if (existingManagedHsm == null)
            {
                throw new ArgumentNullException("existingManagedHsm");
            }
            if (existingManagedHsm.OriginalManagedHsm == null)
            {
                throw new ArgumentNullException("existingManagedHsm.OriginalManagedHsm");
            }

            //Update the vault properties in the object received from server
            var properties = existingManagedHsm.OriginalManagedHsm.Properties;

            properties.EnablePurgeProtection = parameters.EnablePurgeProtection;

            var response = KeyVaultManagementClient.ManagedHsms.Update(
                resourceGroupName: existingManagedHsm.ResourceGroupName,
                name: existingManagedHsm.Name,
                parameters: new ManagedHsm
            {
                Location = existingManagedHsm.Location,
                Sku      = new ManagedHsmSku
                {
                    Name = (ManagedHsmSkuName)Enum.Parse(typeof(ManagedHsmSkuName), existingManagedHsm.Sku)
                },
                Tags       = TagsConversionHelper.CreateTagDictionary(parameters.Tags, validate: true),
                Properties = properties
            });

            return(new PSManagedHsm(response, graphClient));
        }
        /// <summary>
        /// Create a new vault
        /// </summary>
        /// <param name="parameters">vault creation parameters</param>
        /// <param name="graphClient">the active directory client</param>
        /// <returns></returns>
        public PSKeyVault CreateNewVault(VaultCreationOrUpdateParameters parameters, IMicrosoftGraphClient graphClient = 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, graphClient));
        }
 /// <summary>
 /// List all existing Managed HSMs.
 /// </summary>
 /// <param name="resourceGroupName">resource group name</param>
 /// <param name="graphClient">the active directory client</param>
 /// <returns>the retrieved Managed HSM</returns>
 public List <PSManagedHsm> ListManagedHsms(string resourceGroupName, IMicrosoftGraphClient graphClient = null)
 {
     return(resourceGroupName == null?ListManagedHsmsBySubscription(graphClient) :
                ListManagedHsmsByResourceGroup(resourceGroupName, graphClient));
 }
        /// <summary>
        /// Get an existing managed HSM. Returns null if managed HSM is not found.
        /// </summary>
        /// <param name="managedHsmName">managed HSM name</param>
        /// <param name="resourceGroupName">resource group name</param>
        /// <param name="graphClient">the active directory client</param>
        /// <returns>the retrieved Managed HSM</returns>
        public PSManagedHsm GetManagedHsm(string managedHsmName, string resourceGroupName, IMicrosoftGraphClient graphClient = null)
        {
            if (string.IsNullOrWhiteSpace(managedHsmName))
            {
                throw new ArgumentNullException("vaultName");
            }
            if (string.IsNullOrWhiteSpace(resourceGroupName))
            {
                throw new ArgumentNullException("resourceGroupName");
            }

            try
            {
                var response = KeyVaultManagementClient.ManagedHsms.Get(resourceGroupName, managedHsmName);

                return(new PSManagedHsm(response, graphClient));
            }
            catch (ManagedHsmErrorException ce) when(ce.IsNotFoundException())
            {
                return(null);
            }
        }
        /// <summary>
        /// Create a Managed HSM pool
        /// </summary>
        /// <param name="parameters">vault creation parameters</param>
        /// <param name="graphClient">the active directory client</param>
        /// <returns></returns>
        public PSManagedHsm CreateNewManagedHsm(VaultCreationOrUpdateParameters parameters, IMicrosoftGraphClient graphClient = 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");
            }
            if (parameters.Administrator.Length == 0)
            {
                throw new ArgumentNullException("parameters.Administrator");
            }

            var properties    = new ManagedHsmProperties();
            var managedHsmSku = new ManagedHsmSku();

            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 ManagedHsmSkuName skuName))
                    {
                        managedHsmSku.Name = skuName;
                    }
                    else
                    {
                        throw new InvalidEnumArgumentException("parameters.SkuName");
                    }
                }
                properties.TenantId = parameters.TenantId;
                properties.InitialAdminObjectIds     = parameters.Administrator;
                properties.EnableSoftDelete          = parameters.EnableSoftDelete;
                properties.SoftDeleteRetentionInDays = parameters.SoftDeleteRetentionInDays;
                properties.EnablePurgeProtection     = parameters.EnablePurgeProtection;
            }
            else
            {
                properties.CreateMode = CreateMode.Recover;
            }

            var response = KeyVaultManagementClient.ManagedHsms.CreateOrUpdate(
                resourceGroupName: parameters.ResourceGroupName,
                name: parameters.Name,
                parameters: new ManagedHsm
            {
                Location   = parameters.Location,
                Sku        = managedHsmSku,
                Tags       = TagsConversionHelper.CreateTagDictionary(parameters.Tags, validate: true),
                Properties = properties
            });

            return(new PSManagedHsm(response, graphClient));
        }
Beispiel #27
0
        /// <summary>
        /// Update an existing Managed HSM.
        /// </summary>
        /// <param name="existingManagedHsm">existing Managed HSM</param>
        /// <param name="parameters">HSM update parameters</param>
        /// <param name="graphClient">the active directory client</param>
        /// <returns>the updated Managed HSM</returns>
        public PSManagedHsm UpdateManagedHsm(PSManagedHsm existingManagedHsm, VaultCreationOrUpdateParameters parameters, IMicrosoftGraphClient graphClient = null)
        {
            if (existingManagedHsm == null)
            {
                throw new ArgumentNullException("existingManagedHsm");
            }
            if (existingManagedHsm.OriginalManagedHsm == null)
            {
                throw new ArgumentNullException("existingManagedHsm.OriginalManagedHsm");
            }

            //Update the vault properties in the object received from server
            var properties = existingManagedHsm.OriginalManagedHsm.Properties;

            properties.EnablePurgeProtection = parameters.EnablePurgeProtection;
            if (!string.IsNullOrEmpty(parameters.PublicNetworkAccess))
            {
                properties.PublicNetworkAccess       = parameters.PublicNetworkAccess;
                properties.NetworkAcls.DefaultAction = PublicNetworkAccess.Enabled.ToString().Equals(parameters.PublicNetworkAccess) ?
                                                       NetworkRuleAction.Allow.ToString() : NetworkRuleAction.Deny.ToString();
            }
            var response = KeyVaultManagementClient.ManagedHsms.Update(
                resourceGroupName: existingManagedHsm.ResourceGroupName,
                name: existingManagedHsm.Name,
                parameters: new ManagedHsm
            {
                Location = existingManagedHsm.Location,
                Sku      = new ManagedHsmSku
                {
                    Name = (ManagedHsmSkuName)Enum.Parse(typeof(ManagedHsmSkuName), existingManagedHsm.Sku)
                },
                Tags       = TagsConversionHelper.CreateTagDictionary(parameters.Tags, validate: true),
                Properties = properties
            });

            return(new PSManagedHsm(response, graphClient));
        }
Beispiel #28
0
 public static string GetDisplayNameForADObject(string objectId, IMicrosoftGraphClient graphClient) =>
 GetDetailsFromADObjectId(objectId, graphClient).Item1;
 public static TimeOffCollectionResponse ListTimeOffNextPage(this IMicrosoftGraphClient operations, string url)
 {
     return(operations.ListTimeOffNextPageAsync(url).GetAwaiter().GetResult());
 }
        /// <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="updatedNetworkAcls">updated network rule set</param>
        /// <param name="graphClient">the active directory client</param>
        /// <returns>the updated vault</returns>
        public PSKeyVault UpdateVault(
            PSKeyVault existingVault,
            PSKeyVaultAccessPolicy[] updatedPolicies,
            bool?updatedEnabledForDeployment,
            bool?updatedEnabledForTemplateDeployment,
            bool?updatedEnabledForDiskEncryption,
            bool?updatedSoftDeleteSwitch,
            bool?updatedPurgeProtectionSwitch,
            bool?updatedRbacAuthorization,
            int?softDeleteRetentionInDays,
            PSKeyVaultNetworkRuleSet updatedNetworkAcls,
            IMicrosoftGraphClient graphClient = 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
            var properties = existingVault.OriginalVault.Properties;

            properties.EnabledForDeployment         = updatedEnabledForDeployment;
            properties.EnabledForTemplateDeployment = updatedEnabledForTemplateDeployment;
            properties.EnabledForDiskEncryption     = updatedEnabledForDiskEncryption;
            properties.SoftDeleteRetentionInDays    = softDeleteRetentionInDays;

            // soft delete flags can only be applied if they enable their respective behaviors
            // and if different from the current corresponding properties on the vault.
            if (!(properties.EnableSoftDelete.HasValue && properties.EnableSoftDelete.Value) &&
                updatedSoftDeleteSwitch.HasValue &&
                updatedSoftDeleteSwitch.Value)
            {
                properties.EnableSoftDelete = updatedSoftDeleteSwitch;
            }

            if (!(properties.EnablePurgeProtection.HasValue && properties.EnablePurgeProtection.Value) &&
                updatedPurgeProtectionSwitch.HasValue &&
                updatedPurgeProtectionSwitch.Value)
            {
                properties.EnablePurgeProtection = updatedPurgeProtectionSwitch;
            }

            // Update EnableRbacAuthorization when specified, otherwise stay current value
            properties.EnableRbacAuthorization = updatedRbacAuthorization;

            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();

            UpdateVaultNetworkRuleSetProperties(properties, updatedNetworkAcls);

            var response = 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, graphClient));
        }