/// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource(string resourceId, string apiVersion)
        {
            var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource <PolicyAssignmentProperties>();

            // get incoming object properties if present
            JObject inputMetadata = null;

            if (this.InputObject != null)
            {
                var newProperties = this.InputObject.Properties.ToJToken();
                inputMetadata = newProperties["metadata"] as JObject;
            }

            var parameterMetadata = this.Metadata != null?this.GetObjectFromParameter(this.Metadata, nameof(this.Metadata)) : null;

            PolicyAssignmentEnforcementMode?inputMode = null;

            if (Enum.TryParse(this.InputObject?.Properties?.EnforcementMode?.ToString(), true, out PolicyAssignmentEnforcementMode tempMode1))
            {
                inputMode = tempMode1;
            }

            // Grab the non-compliance messages from the parameter or input object or existing resource
            var nonComplianceMessages = this.NonComplianceMessage?.Where(message => message != null).SelectArray(message => message.ToModel());

            if (nonComplianceMessages == null && this.InputObject?.Properties.NonComplianceMessages != null)
            {
                nonComplianceMessages = this.InputObject.Properties.NonComplianceMessages.Where(message => message != null).SelectArray(message => message.ToModel());
            }
            else if (nonComplianceMessages == null)
            {
                nonComplianceMessages = resource.Properties.NonComplianceMessages;
            }

            var policyAssignmentObject = new PolicyAssignment
            {
                Name     = this.Name ?? this.InputObject?.Name ?? resource.Name,
                Identity = this.AssignIdentity.IsPresent ? new ResourceIdentity {
                    Type = ResourceIdentityType.SystemAssigned
                } : null,
                Location   = this.Location ?? this.InputObject?.Location ?? resource.Location,
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName           = this.DisplayName ?? this.InputObject?.Properties?.DisplayName ?? resource.Properties.DisplayName,
                    Description           = this.Description ?? this.InputObject?.Properties?.Description ?? resource.Properties.Description,
                    Scope                 = resource.Properties.Scope,
                    NotScopes             = this.NotScope ?? this.InputObject?.Properties?.NotScopes ?? resource.Properties.NotScopes,
                    PolicyDefinitionId    = resource.Properties.PolicyDefinitionId,
                    Metadata              = parameterMetadata ?? inputMetadata ?? resource.Properties.Metadata,
                    EnforcementMode       = this.EnforcementMode ?? inputMode ?? resource.Properties.EnforcementMode,
                    NonComplianceMessages = nonComplianceMessages,
                    Parameters            =
                        this.GetParameters(this.PolicyParameter, this.PolicyParameterObject)
                        ?? this.InputObject?.Properties?.Parameters?.ToResourcePropertiesBody() as JObject
                        ?? resource.Properties.Parameters
                }
            };

            return(policyAssignmentObject.ToJToken());
        }
Пример #2
0
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource(string resourceId, string apiVersion)
        {
            var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource();

            var metaDataJson = string.IsNullOrEmpty(this.Metadata) ? resource.Properties["metadata"]?.ToString() : GetObjectFromParameter(this.Metadata).ToString();

            var policyAssignmentObject = new PolicyAssignment
            {
                Name     = this.Name ?? resource.Name,
                Identity = this.AssignIdentity.IsPresent ? new ResourceIdentity {
                    Type = ResourceIdentityType.SystemAssigned
                } : null,
                Location   = this.Location ?? resource.Location,
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName        = this.DisplayName ?? resource.Properties["displayName"]?.ToString(),
                    Description        = this.Description ?? resource.Properties["description"]?.ToString(),
                    Scope              = resource.Properties["scope"].ToString(),
                    NotScopes          = this.NotScope ?? resource.Properties["NotScopes"]?.ToString().Split(','),
                    PolicyDefinitionId = resource.Properties["policyDefinitionId"].ToString(),
                    Metadata           = string.IsNullOrEmpty(this.Metadata) ? null : JObject.Parse(metaDataJson),
                    Parameters         = (JObject)resource.Properties["parameters"]
                }
            };

            return(policyAssignmentObject.ToJToken());
        }
Пример #3
0
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource(string resourceId, string apiVersion)
        {
            var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource();

            var policyAssignmentObject = new PolicyAssignment
            {
                Name = this.Name ?? ResourceIdUtility.GetResourceName(this.Id),
                Sku  = this.Sku != null
                    ? this.Sku.ToDictionary(addValueLayer : false).ToJson().FromJson <PolicySku>()
                    : (resource.Sku == null ? new PolicySku
                {
                    Name = "A0", Tier = "Free"
                }

                                                                                           : resource.Sku.ToJson().FromJson <PolicySku>()),
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName = this.DisplayName ?? (resource.Properties["displayName"] != null
                        ? resource.Properties["displayName"].ToString()
                        : null),
                    Description = this.Description ?? (resource.Properties["description"] != null
                        ? resource.Properties["description"].ToString()
                        : null),
                    Scope              = resource.Properties["scope"].ToString(),
                    NotScopes          = this.NotScope ?? (resource.Properties["NotScopes"] == null ? null : resource.Properties["NotScopes"].ToString().Split(',')),
                    PolicyDefinitionId = resource.Properties["policyDefinitionId"].ToString()
                }
            };

            return(policyAssignmentObject.ToJToken());
        }
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource()
        {
            var policyassignmentObject = new PolicyAssignment
            {
                Name     = this.Name,
                Identity = this.AssignIdentity.IsPresent ? new ResourceIdentity {
                    Type = ResourceIdentityType.SystemAssigned
                } : null,
                Location   = this.Location,
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName     = this.DisplayName ?? null,
                    Description     = this.Description ?? null,
                    Scope           = this.Scope,
                    NotScopes       = this.NotScope ?? null,
                    Metadata        = this.Metadata == null ? null : this.GetObjectFromParameter(this.Metadata, nameof(this.Metadata)),
                    EnforcementMode = EnforcementMode ?? PolicyAssignmentEnforcementMode.Default,
                    Parameters      = this.GetParameters(this.PolicyParameter, this.PolicyParameterObject)
                }
            };

            if (this.PolicyDefinition != null)
            {
                policyassignmentObject.Properties.PolicyDefinitionId = this.PolicyDefinition.Properties["policyDefinitionId"].Value.ToString();
            }
            else if (this.PolicySetDefinition != null)
            {
                policyassignmentObject.Properties.PolicyDefinitionId = this.PolicySetDefinition.Properties["policySetDefinitionId"].Value.ToString();
            }

            return(policyassignmentObject.ToJToken());
        }
Пример #5
0
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource()
        {
            var policyassignmentObject = new PolicyAssignment
            {
                Name = this.Name,
                Sku  = this.Sku == null? new PolicySku {
                    Name = "A0", Tier = "Free"
                } : this.Sku.ToDictionary(addValueLayer: false).ToJson().FromJson <PolicySku>(),
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName = this.DisplayName ?? null,
                    Description = this.Description ?? null,
                    Scope       = this.Scope,
                    NotScopes   = this.NotScope ?? null,
                    Parameters  = this.GetParameters()
                }
            };

            if (this.PolicyDefinition != null)
            {
                policyassignmentObject.Properties.PolicyDefinitionId = this.PolicyDefinition.Properties["policyDefinitionId"].Value.ToString();
            }
            else if (this.PolicySetDefinition != null)
            {
                policyassignmentObject.Properties.PolicyDefinitionId = this.PolicySetDefinition.Properties["policySetDefinitionId"].Value.ToString();
            }

            return(policyassignmentObject.ToJToken());
        }
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource()
        {
            var policyassignmentObject = new PolicyAssignment
            {
                Name     = this.Name,
                Sku      = Sku?.ToDictionary(addValueLayer: false).ToJson().FromJson <PolicySku>(), // only store Sku if it was provided by user
                Identity = this.AssignIdentity.IsPresent ? new ResourceIdentity {
                    Type = ResourceIdentityType.SystemAssigned
                } : null,
                Location   = this.Location,
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName = this.DisplayName ?? null,
                    Description = this.Description ?? null,
                    Scope       = this.Scope,
                    NotScopes   = this.NotScope ?? null,
                    Metadata    = this.Metadata == null ? null : JObject.Parse(this.GetObjectFromParameter(this.Metadata).ToString()),
                    Parameters  = this.GetParameters()
                }
            };

            if (this.PolicyDefinition != null)
            {
                policyassignmentObject.Properties.PolicyDefinitionId = this.PolicyDefinition.Properties["policyDefinitionId"].Value.ToString();
            }
            else if (this.PolicySetDefinition != null)
            {
                policyassignmentObject.Properties.PolicyDefinitionId = this.PolicySetDefinition.Properties["policySetDefinitionId"].Value.ToString();
            }

            return(policyassignmentObject.ToJToken());
        }
Пример #7
0
        public async Task List()
        {
            Subscription subscription = await Client.GetDefaultSubscriptionAsync();

            string        rgName = Recording.GenerateAssetName("testRg-");
            ResourceGroup rg     = await CreateResourceGroup(subscription, rgName);

            string           policyAssignmentName = Recording.GenerateAssetName("polAssign-");
            PolicyAssignment policyAssignment     = await CreatePolicyAssignment(rg, policyAssignmentName);

            string policyExemptionName1 = Recording.GenerateAssetName("polExemp-");
            string policyExemptionName2 = Recording.GenerateAssetName("polExemp-");

            _ = await CreatePolicyExemption(rg, policyAssignment, policyExemptionName1);

            _ = await CreatePolicyExemption(rg, policyAssignment, policyExemptionName2);

            int    count  = 0;
            string filter = $"policyAssignmentId eq '{policyAssignment.Id}'";

            await foreach (var policyExemption in rg.GetPolicyExemptions().GetAllAsync(filter))
            {
                count++;
            }
            Assert.AreEqual(count, 2);
        }
Пример #8
0
        public void PolicyRestrictions_ResourceGroupScope()
        {
            const string ResourceGroupName = "checkRestrictSdkTests";

            using (var context = MockContext.Start(this.GetType()))
            {
                // Create a resource group
                var armClient         = context.GetServiceClient <ResourceManagementClient>();
                var armResourceTypes  = armClient.ProviderResourceTypes.List("Microsoft.Resources");
                var resourceGroupType = armResourceTypes.Value.First(resourceType => resourceType.ResourceType.Equals("resourceGroups", StringComparison.OrdinalIgnoreCase));
                armClient.ResourceGroups.CreateOrUpdate(ResourceGroupName, new ResourceGroup(location: resourceGroupType.Locations[0]));

                // Add a policy assignment (allowed storage account SKUs) that can be used to validate checkPolicyRestrictions
                var armPolicyClient        = context.GetServiceClient <PolicyClient>();
                var policyAssignmentParams = new PolicyAssignment
                {
                    PolicyDefinitionId = "/providers/Microsoft.Authorization/policyDefinitions/7433c107-6db4-4ad1-b57a-a76dce0154a1",
                    Parameters         = new Dictionary <string, ParameterValuesValue> {
                        ["effect"] = new ParameterValuesValue("Deny"), ["listOfAllowedSKUs"] = new ParameterValuesValue(new[] { "Standard_LRS" })
                    }
                };

                var scope = $"/subscriptions/{armPolicyClient.SubscriptionId}/resourceGroups/{ResourceGroupName}";
                armPolicyClient.PolicyAssignments.Create(scope: scope, policyAssignmentName: "checkRestrictSdkTest", parameters: policyAssignmentParams);

                // Send a check restrictions request with a potential list of SKUs, two will be denied
                var checkRestrictionsParams = new CheckRestrictionsRequest
                {
                    ResourceDetails = new CheckRestrictionsResourceDetails
                    {
                        ApiVersion      = "2021-04-01",
                        ResourceContent = new JObject(new JProperty("type", "Microsoft.Storage/storageAccounts"))
                    },
                    PendingFields = new[]
                    {
                        new PendingField
                        {
                            Field  = "Microsoft.Storage/storageAccounts/sku.name",
                            Values = new[] { "Standard_ZRS", "Premium_LRS", "Standard_LRS" }
                        }
                    }
                };

                var policyRestrictionsClient = context.GetServiceClient <PolicyInsightsClient>();
                var checkRestrictionsResult  = policyRestrictionsClient.PolicyRestrictions.CheckAtResourceGroupScope(subscriptionId: armPolicyClient.SubscriptionId, resourceGroupName: ResourceGroupName, parameters: checkRestrictionsParams);

                Assert.Equal(0, checkRestrictionsResult.ContentEvaluationResult.PolicyEvaluations.Count);
                Assert.Equal(1, checkRestrictionsResult.FieldRestrictions.Count);
                var fieldRestriction = checkRestrictionsResult.FieldRestrictions[0];
                Assert.Equal("Microsoft.Storage/storageAccounts/sku.name", fieldRestriction.Field);
                Assert.Equal(1, fieldRestriction.Restrictions.Count);
                Assert.Equal("Deny", fieldRestriction.Restrictions[0].Result);
                Assert.Equal(2, fieldRestriction.Restrictions[0].Values.Count);
                Assert.Equal(new[] { "Standard_ZRS", "Premium_LRS" }, fieldRestriction.Restrictions[0].Values, StringComparer.OrdinalIgnoreCase);

                armClient.ResourceGroups.Delete(ResourceGroupName);
            }
        }
Пример #9
0
        public async Task CreateOrUpdateAtSubscription()
        {
            Subscription subscription = await Client.GetDefaultSubscriptionAsync();

            string           policyAssignmentName = Recording.GenerateAssetName("polAssign-");
            PolicyAssignment policyAssignment     = await CreatePolicyAssignment(subscription, policyAssignmentName);

            Assert.AreEqual(policyAssignmentName, policyAssignment.Data.Name);
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await subscription.GetPolicyAssignments().CreateOrUpdateAsync(true, null, policyAssignment.Data));
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await subscription.GetPolicyAssignments().CreateOrUpdateAsync(true, policyAssignmentName, null));
        }
Пример #10
0
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource(string resourceId, string apiVersion)
        {
            var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource();

            // get incoming object properties if present
            JObject inputMetadata = null;

            if (this.InputObject != null)
            {
                var newProperties = this.InputObject.Properties.ToJToken();
                inputMetadata = newProperties["metadata"] as JObject;
            }

            var parameterMetadata = this.Metadata != null?this.GetObjectFromParameter(this.Metadata, nameof(this.Metadata)) : null;

            PolicyAssignmentEnforcementMode?existingMode = null;

            if (Enum.TryParse(resource.Properties["enforcementMode"]?.ToString(), true, out PolicyAssignmentEnforcementMode tempMode))
            {
                existingMode = tempMode;
            }

            PolicyAssignmentEnforcementMode?inputMode = null;

            if (Enum.TryParse(this.InputObject?.Properties?.EnforcementMode?.ToString(), true, out PolicyAssignmentEnforcementMode tempMode1))
            {
                inputMode = tempMode1;
            }

            var policyAssignmentObject = new PolicyAssignment
            {
                Name     = this.Name ?? this?.InputObject?.Name ?? resource.Name,
                Identity = this.AssignIdentity.IsPresent ? new ResourceIdentity {
                    Type = ResourceIdentityType.SystemAssigned
                } : null,
                Location   = this.Location ?? this.InputObject?.Location ?? resource.Location,
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName        = this.DisplayName ?? this?.InputObject?.Properties?.DisplayName ?? resource.Properties["displayName"]?.ToString(),
                    Description        = this.Description ?? this?.InputObject?.Properties?.Description ?? resource.Properties["description"]?.ToString(),
                    Scope              = resource.Properties["scope"]?.ToString(),
                    NotScopes          = this.NotScope ?? this?.InputObject?.Properties?.NotScopes ?? resource.Properties["NotScopes"]?.ToString()?.Split(','),
                    PolicyDefinitionId = resource.Properties["policyDefinitionId"]?.ToString(),
                    Metadata           = parameterMetadata ?? inputMetadata ?? resource.Properties["metadata"] as JObject,
                    EnforcementMode    = this.EnforcementMode ?? inputMode ?? existingMode,
                    Parameters         =
                        this.GetParameters(this.PolicyParameter, this.PolicyParameterObject)
                        ?? this.InputObject?.Properties?.Parameters?.ToResourcePropertiesBody() as JObject
                        ?? resource.Properties["parameters"] as JObject
                }
            };

            return(policyAssignmentObject.ToJToken());
        }
Пример #11
0
        public async Task CreateOrUpdateAtMgmtGroup()
        {
            //This test uses a pre-created management group.
            ManagementGroup mgmtGroup = await GetCreatedManagementGroup();

            string           policyAssignmentName = Recording.GenerateAssetName("polAssign-");
            PolicyAssignment policyAssignment     = await CreatePolicyAssignment(mgmtGroup, policyAssignmentName);

            Assert.AreEqual(policyAssignmentName, policyAssignment.Data.Name);
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await mgmtGroup.GetPolicyAssignments().CreateOrUpdateAsync(true, null, policyAssignment.Data));
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await mgmtGroup.GetPolicyAssignments().CreateOrUpdateAsync(true, policyAssignmentName, null));
        }
Пример #12
0
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource()
        {
            if (this.AssignIdentity != null && this.AssignIdentity.IsPresent)
            {
                this.IdentityType = ManagedIdentityType.SystemAssigned;
            }

            ResourceIdentity identityObject = this.IdentityType != null ?
                                              (this.IdentityType == ManagedIdentityType.UserAssigned ?
                                               new ResourceIdentity
            {
                Type = IdentityType.ToString(),
                UserAssignedIdentities = new Dictionary <string, UserAssignedIdentityResource>
                {
                    { this.IdentityId, new UserAssignedIdentityResource {
                      } }
                }
            } :
                                               new ResourceIdentity {
                Type = IdentityType.ToString()
            }
                                              ) : null;

            var policyassignmentObject = new PolicyAssignment
            {
                Name       = this.Name,
                Identity   = identityObject,
                Location   = this.Location,
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName           = this.DisplayName ?? null,
                    Description           = this.Description ?? null,
                    Scope                 = this.Scope,
                    NotScopes             = this.NotScope ?? null,
                    Metadata              = this.Metadata == null ? null : this.GetObjectFromParameter(this.Metadata, nameof(this.Metadata)),
                    EnforcementMode       = EnforcementMode ?? PolicyAssignmentEnforcementMode.Default,
                    Parameters            = this.GetParameters(this.PolicyParameter, this.PolicyParameterObject),
                    NonComplianceMessages = this.NonComplianceMessage?.Where(message => message != null).SelectArray(message => message.ToModel())
                }
            };

            if (this.PolicyDefinition != null)
            {
                policyassignmentObject.Properties.PolicyDefinitionId = this.PolicyDefinition.PolicyDefinitionId;
            }
            else if (this.PolicySetDefinition != null)
            {
                policyassignmentObject.Properties.PolicyDefinitionId = this.PolicySetDefinition.PolicySetDefinitionId;
            }

            return(policyassignmentObject.ToJToken());
        }
        public async Task Delete()
        {
            Subscription subscription = await Client.GetDefaultSubscriptionAsync();

            string           policyAssignmentName = Recording.GenerateAssetName("polAssign-");
            PolicyAssignment policyAssignment     = await CreatePolicyAssignment(subscription, policyAssignmentName);

            await policyAssignment.DeleteAsync(true);

            var ex = Assert.ThrowsAsync <RequestFailedException>(async() => await policyAssignment.GetAsync());

            Assert.AreEqual(404, ex.Status);
        }
Пример #14
0
        public async Task CreateOrUpdateAtResourceGroup()
        {
            Subscription subscription = await Client.GetDefaultSubscriptionAsync();

            string        rgName = Recording.GenerateAssetName("testRg-");
            ResourceGroup rg     = await CreateResourceGroup(subscription, rgName);

            string           policyAssignmentName = Recording.GenerateAssetName("polAssign-");
            PolicyAssignment policyAssignment     = await CreatePolicyAssignment(rg, policyAssignmentName);

            Assert.AreEqual(policyAssignmentName, policyAssignment.Data.Name);
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await rg.GetPolicyAssignments().CreateOrUpdateAsync(WaitUntil.Completed, null, policyAssignment.Data));
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await rg.GetPolicyAssignments().CreateOrUpdateAsync(WaitUntil.Completed, policyAssignmentName, null));
        }
Пример #15
0
        public async Task Get()
        {
            Subscription subscription = await Client.GetDefaultSubscriptionAsync();

            string        rgName = Recording.GenerateAssetName("testRg-");
            ResourceGroup rg     = await CreateResourceGroup(subscription, rgName);

            string           policyAssignmentName = Recording.GenerateAssetName("polAssign-");
            PolicyAssignment policyAssignment     = await CreatePolicyAssignment(rg, policyAssignmentName);

            PolicyAssignment getPolicyAssignment = await rg.GetPolicyAssignments().GetAsync(policyAssignmentName);

            AssertValidPolicyAssignment(policyAssignment, getPolicyAssignment);
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await rg.GetPolicyAssignments().GetAsync(null));
        }
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource()
        {
            var policyassignmentObject = new PolicyAssignment
            {
                Name       = this.Name,
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName        = this.DisplayName ?? null,
                    PolicyDefinitionId = this.PolicyDefinition.Properties["policyDefinitionId"].Value.ToString(),
                    Scope = this.Scope
                }
            };

            return(policyassignmentObject.ToJToken());
        }
Пример #17
0
        public async Task CreateOrUpdateAtResource()
        {
            Subscription subscription = await Client.GetDefaultSubscriptionAsync();

            string        rgName = Recording.GenerateAssetName("testRg-");
            ResourceGroup rg     = await CreateResourceGroup(subscription, rgName);

            string          vnName = Recording.GenerateAssetName("testVn-");
            GenericResource vn     = await CreateGenericVirtualNetwork(subscription, rg, vnName);

            string           policyAssignmentName = Recording.GenerateAssetName("polAssign-");
            PolicyAssignment policyAssignment     = await CreatePolicyAssignment(vn, policyAssignmentName);

            Assert.AreEqual(policyAssignmentName, policyAssignment.Data.Name);
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await vn.GetPolicyAssignments().CreateOrUpdateAsync(true, null, policyAssignment.Data));
            Assert.ThrowsAsync <ArgumentNullException>(async() => _ = await vn.GetPolicyAssignments().CreateOrUpdateAsync(true, policyAssignmentName, null));
        }
Пример #18
0
        public async Task Delete()
        {
            Subscription subscription = await Client.GetDefaultSubscriptionAsync();

            string        rgName = Recording.GenerateAssetName("testRg-");
            ResourceGroup rg     = await CreateResourceGroup(subscription, rgName);

            string           policyAssignmentName = Recording.GenerateAssetName("polAssign-");
            PolicyAssignment policyAssignment     = await CreatePolicyAssignment(rg, policyAssignmentName);

            string          policyExemptionName = Recording.GenerateAssetName("polExemp-");
            PolicyExemption policyExemption     = await CreatePolicyExemption(rg, policyAssignment, policyExemptionName);

            await policyExemption.DeleteAsync(true);

            var ex = Assert.ThrowsAsync <RequestFailedException>(async() => await policyExemption.GetAsync());

            Assert.AreEqual(404, ex.Status);
        }
Пример #19
0
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource(string resourceId, string apiVersion)
        {
            var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource();

            var policyAssignmentObject = new PolicyAssignment
            {
                Name       = this.Name ?? ResourceIdUtility.GetResourceName(this.Id),
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName = this.DisplayName ?? (resource.Properties["displayName"] != null
                        ? resource.Properties["displayName"].ToString()
                        : null),
                    Scope = resource.Properties["scope"].ToString(),
                    PolicyDefinitionId = resource.Properties["policyDefinitionId"].ToString()
                }
            };

            return(policyAssignmentObject.ToJToken());
        }
Пример #20
0
        public void TestDuplicateHashSet()
        {
            var sourceA = new AccessPolicy("id", new NumberOfLockings(1, 2), Enumerable.Empty <TimePeriodDefinition>());
            var sourceB = new AccessPolicy("id", new NumberOfLockings(1, 2), Enumerable.Empty <TimePeriodDefinition>());

            var key   = new Key("idKey", "key", "appId", "Hugo");
            var @lock = new Lock("idLock", "lock", "appId", "Tor West");

            var eitherA = new Either <LockAssignment, KeyAssignment>(new KeyAssignment(key, new[] { @lock }));
            var eitherB = new Either <LockAssignment, KeyAssignment>(new KeyAssignment(key, new[] { @lock }));

            Assert.Equal(eitherA, eitherB);

            var assignA = new PolicyAssignment(sourceA,
                                               new Either <LockAssignment, KeyAssignment>(new KeyAssignment(key, new[] { @lock })));
            var assignB = new PolicyAssignment(sourceA,
                                               new Either <LockAssignment, KeyAssignment>(new KeyAssignment(key, new[] { @lock })));

            var setAssignments = ImmutableHashSet <PolicyAssignment> .Empty.Add(assignA).Add(assignB);

            Assert.NotEmpty(setAssignments);
        }
Пример #21
0
        /// <summary>
        /// Assigns the initiative
        /// </summary>
        /// <param name="initiativeName"></param>
        /// <param name="scope"></param>
        /// <param name="assignmentName"></param>
        /// <returns></returns>
        public async Task <PolicyAssignment> AssignInitiative(string initiativeName, string projectCode, string scope, string assignmentName, Tags tags)
        {
            var serviceCredentials = await _authenticationHelper.GetServiceClientCredentials(ApplicationConstants.RESOURCE_URI.MANAGEMENT);

            PolicyClient client = new PolicyClient(serviceCredentials);

            string subscriptionid = _appSettings.Subscriptionid;

            client.SubscriptionId = subscriptionid;

            PolicyAssignment existingAssignment = null;

            try
            {
                existingAssignment = await client.PolicyAssignments.GetAsync(scope, assignmentName);
            }
            catch (ErrorResponseException) { }

            if (existingAssignment != null)
            {
                await client.PolicyAssignments.DeleteAsync(scope, assignmentName);
            }

            var initiativeParameters = GetInitiativeParameters(tags, projectCode);

            var json = JsonConvert.SerializeObject(initiativeParameters);

            var parameters = JObject.Parse(json);

            PolicySetDefinition initiative = await client.PolicySetDefinitions.GetAsync(initiativeName);

            PolicyAssignment assignment = new PolicyAssignment();

            assignment.PolicyDefinitionId = initiative.Id;

            assignment.Parameters = parameters;

            return(await client.PolicyAssignments.CreateAsync(scope, assignmentName, assignment));
        }
Пример #22
0
 private void AssertValidPolicyAssignment(PolicyAssignment model, PolicyAssignment getResult)
 {
     Assert.AreEqual(model.Data.Name, getResult.Data.Name);
     Assert.AreEqual(model.Data.Id, getResult.Data.Id);
     Assert.AreEqual(model.Data.Type, getResult.Data.Type);
     Assert.AreEqual(model.Data.Location, getResult.Data.Location);
     Assert.AreEqual(model.Data.Identity, getResult.Data.Identity);
     Assert.AreEqual(model.Data.DisplayName, getResult.Data.DisplayName);
     Assert.AreEqual(model.Data.PolicyDefinitionId, getResult.Data.PolicyDefinitionId);
     Assert.AreEqual(model.Data.Scope, getResult.Data.Scope);
     Assert.AreEqual(model.Data.NotScopes, getResult.Data.NotScopes);
     if (model.Data.Parameters != null || getResult.Data.Parameters != null)
     {
         Assert.NotNull(model.Data.Parameters);
         Assert.NotNull(getResult.Data.Parameters);
         Assert.AreEqual(model.Data.Parameters.Count, getResult.Data.Parameters.Count);
         foreach (KeyValuePair <string, ParameterValuesValue> kv in model.Data.Parameters)
         {
             Assert.True(getResult.Data.Parameters.ContainsKey(kv.Key));
             Assert.AreEqual(kv.Value.Value, getResult.Data.Parameters[kv.Key]);
         }
     }
     Assert.AreEqual(model.Data.Description, getResult.Data.Description);
     Assert.AreEqual(model.Data.Metadata, getResult.Data.Metadata);
     Assert.AreEqual(model.Data.EnforcementMode, getResult.Data.EnforcementMode);
     if (model.Data.NonComplianceMessages != null || getResult.Data.NonComplianceMessages != null)
     {
         Assert.NotNull(model.Data.NonComplianceMessages);
         Assert.NotNull(getResult.Data.NonComplianceMessages);
         Assert.AreEqual(model.Data.NonComplianceMessages.Count, getResult.Data.NonComplianceMessages.Count);
         for (int i = 0; i < model.Data.NonComplianceMessages.Count; ++i)
         {
             Assert.AreEqual(model.Data.NonComplianceMessages[i].Message, getResult.Data.NonComplianceMessages[i].Message);
             Assert.AreEqual(model.Data.NonComplianceMessages[i].PolicyDefinitionReferenceId, getResult.Data.NonComplianceMessages[i].PolicyDefinitionReferenceId);
         }
     }
 }
Пример #23
0
        /// <summary>
        /// Constructs the resource
        /// </summary>
        private JToken GetResource(string resourceId, string apiVersion)
        {
            var resource = this.GetExistingResource(resourceId, apiVersion).Result.ToResource();

            var metaDataJson = string.IsNullOrEmpty(this.Metadata) ? resource.Properties["metadata"]?.ToString() : GetObjectFromParameter(this.Metadata).ToString();

            var policyAssignmentObject = new PolicyAssignment
            {
                Name       = this.Name ?? resource.Name,
                Sku        = Sku?.ToDictionary(addValueLayer: false).ToJson().FromJson <PolicySku>(), // only store Sku if it was provided by user
                Properties = new PolicyAssignmentProperties
                {
                    DisplayName        = this.DisplayName ?? resource.Properties["displayName"]?.ToString(),
                    Description        = this.Description ?? resource.Properties["description"]?.ToString(),
                    Scope              = resource.Properties["scope"].ToString(),
                    NotScopes          = this.NotScope ?? resource.Properties["NotScopes"]?.ToString().Split(','),
                    PolicyDefinitionId = resource.Properties["policyDefinitionId"].ToString(),
                    Metadata           = string.IsNullOrEmpty(this.Metadata) ? null : JObject.Parse(metaDataJson),
                    Parameters         = (JObject)resource.Properties["parameters"]
                }
            };

            return(policyAssignmentObject.ToJToken());
        }
 public virtual PolicyAssignment GetPolicyAssignment(ResourceIdentifier id)
 {
     PolicyAssignment.ValidateResourceId(id);
     return(new PolicyAssignment(this, id));
 }
Пример #25
0
 /// <summary>
 /// Create policy assignment.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='scope'>
 /// Scope of the policy assignment.
 /// </param>
 /// <param name='policyAssignmentName'>
 /// Policy assignment name.
 /// </param>
 /// <param name='parameters'>
 /// Policy assignment.
 /// </param>
 public static PolicyAssignment Create(this IPolicyAssignmentsOperations operations, string scope, string policyAssignmentName, PolicyAssignment parameters)
 {
     return(Task.Factory.StartNew(s => ((IPolicyAssignmentsOperations)s).CreateAsync(scope, policyAssignmentName, parameters), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult());
 }
Пример #26
0
 /// <summary>
 /// Create policy assignment by Id.
 /// </summary>
 /// <param name='operations'>
 /// The operations group for this extension method.
 /// </param>
 /// <param name='policyAssignmentId'>
 /// Policy assignment Id
 /// </param>
 /// <param name='parameters'>
 /// Policy assignment.
 /// </param>
 /// <param name='cancellationToken'>
 /// The cancellation token.
 /// </param>
 public static async Task <PolicyAssignment> CreateByIdAsync(this IPolicyAssignmentsOperations operations, string policyAssignmentId, PolicyAssignment parameters, CancellationToken cancellationToken = default(CancellationToken))
 {
     using (var _result = await operations.CreateByIdWithHttpMessagesAsync(policyAssignmentId, parameters, null, cancellationToken).ConfigureAwait(false))
     {
         return(_result.Body);
     }
 }
Пример #27
0
 private string DefinedAssignment(PolicyAssignment assignment)
 => $"A{assignment.Target.Match(_ => 'L', _ => 'K')}R,{assignment.Target.Match(l => l.Master.Id, k => k.Master.Id)},OK";
Пример #28
0
        protected async Task <PolicyExemption> CreatePolicyExemption(ArmResource armResource, PolicyAssignment policyAssignment, string policyExemptionName)
        {
            PolicyExemptionData            input = new PolicyExemptionData(policyAssignment.Id, new ExemptionCategory("Waiver"));
            ArmOperation <PolicyExemption> lro   = await armResource.GetPolicyExemptions().CreateOrUpdateAsync(WaitUntil.Completed, policyExemptionName, input);

            return(lro.Value);
        }