// note: tests show that it only applies to Silverlight policy (seems to work with Flash)
        // and only if we're not granting full access (i.e. '/' with all subpaths)
        // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=466043
        private bool CheckOriginalPath(Uri uri)
        {
            // Path Restriction for cross-domain requests
            // http://msdn.microsoft.com/en-us/library/cc838250(VS.95).aspx
            string original = uri.OriginalString;
            // applies to the *path* only (not the query part)
            int query = original.IndexOf('?');

            if (query != -1)
            {
                original = original.Substring(0, query);
            }

            if (original.Contains('%') || original.Contains("./") || original.Contains(".."))
            {
                // special case when no path restriction applies - i.e. the above characters are accepted by SL
                if (AccessPolicyList.Count != 1)
                {
                    return(false);
                }
                AccessPolicy policy = AccessPolicyList [0];
                if (policy.GrantedResources.Count != 1)
                {
                    return(false);
                }
                GrantTo gt = policy.GrantedResources [0];
                if (gt.Resources.Count != 1)
                {
                    return(false);
                }
                Resource r = gt.Resources [0];
                return(r.IncludeSubpaths && (r.Path == "/"));
            }
            return(true);
        }
        private void policiesList_DoubleClick(object sender, System.EventArgs e)
        {
            AccessPolicy policy = (AccessPolicy)policiesList.SelectedItem;

            if (policy != null)
            {
                AddPolicyForm form = new AddPolicyForm();
                form.SetModify(policy.Name, policy.Document);

                DialogResult result = form.ShowDialog(this);
                if (result != DialogResult.Cancel)
                {
                    policy.Name     = form.PolicyName;
                    policy.Document = form.PolicyDoc;

                    bool success = policyDAO.UpdatePolicy(policy.Id, policy.Document, policy.Name);
                    if (success)
                    {
                        RefreshPolicyLists();
                    }
                    else
                    {
                        Error("Could not update policy.");
                    }
                }
            }
        }
        static void ReadGrantToElement(XmlReader reader, AccessPolicy policy)
        {
            var  v     = new GrantTo();
            bool valid = true;

            if (reader.HasAttributes || reader.IsEmptyElement)
            {
                reader.Skip();
                return;
            }

            reader.ReadStartElement("grant-to", String.Empty);
            for (reader.MoveToContent(); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent())
            {
                if (reader.NodeType != XmlNodeType.Element)
                {
                    throw new XmlException(String.Format("Unexpected grant-to content: {0}", reader.NodeType));
                }
                if (!String.IsNullOrEmpty(reader.NamespaceURI))
                {
                    reader.Skip();
                    continue;
                }

                switch (reader.LocalName)
                {
                case "resource":
                    var r = CreateResource(reader);
                    if (r == null)
                    {
                        valid = false;
                    }
                    else
                    {
                        v.Resources.Add(r);
                    }
                    break;

                case "socket-resource":
                    // ignore everything that is not TCP
                    if (reader.GetAttribute("protocol") != "tcp")
                    {
                        break;
                    }
                    // we can merge them all together inside a policy
                    policy.PortMask |= ParsePorts(reader.GetAttribute("port"));
                    break;

                default:
                    valid = false;
                    break;
                }
                reader.Skip();
            }
            if (valid)
            {
                policy.GrantedResources.Add(v);
            }
            reader.ReadEndElement();
        }
        private void newPolicyButton_Click(object sender, System.EventArgs evt)
        {
            AddPolicyForm form   = new AddPolicyForm();
            DialogResult  result = form.ShowDialog(this);

            if (result != DialogResult.Cancel)
            {
                // "backup" the current clipboard contents
                object o = Clipboard.GetDataObject();
                Clipboard.SetDataObject(form.PolicyDoc, false);
                AccessPolicy policy = policyDAO.AddNewPolicy(form.PolicyName, form.PolicyDoc);
                if (policy != null)
                {
                    RefreshPolicyLists();
                    try
                    {
                        if (o != null)
                        {
                            Clipboard.SetDataObject(o, true);
                        }
                    }
                    catch (Exception /*e*/) {
                        // oh well
                    }
                }
                else
                {
                    Error("Could not create new policy. Your policy document was copied to the clipboard.");
                }
            }
        }
示例#5
0
        public async stt::Task GetAccessPolicyRequestObjectAsync()
        {
            moq::Mock <AccessContextManager.AccessContextManagerClient> mockGrpcClient = new moq::Mock <AccessContextManager.AccessContextManagerClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            GetAccessPolicyRequest request = new GetAccessPolicyRequest
            {
                AccessPolicyName = AccessPolicyName.FromAccessPolicy("[ACCESS_POLICY]"),
            };
            AccessPolicy expectedResponse = new AccessPolicy
            {
                AccessPolicyName = AccessPolicyName.FromAccessPolicy("[ACCESS_POLICY]"),
                Parent           = "parent7858e4d0",
                Title            = "title17dbd3d5",
                CreateTime       = new wkt::Timestamp(),
                UpdateTime       = new wkt::Timestamp(),
                Etag             = "etage8ad7218",
            };

            mockGrpcClient.Setup(x => x.GetAccessPolicyAsync(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall <AccessPolicy>(stt::Task.FromResult(expectedResponse), null, null, null, null));
            AccessContextManagerClient client = new AccessContextManagerClientImpl(mockGrpcClient.Object, null);
            AccessPolicy responseCallSettings = await client.GetAccessPolicyAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None));

            xunit::Assert.Same(expectedResponse, responseCallSettings);
            AccessPolicy responseCancellationToken = await client.GetAccessPolicyAsync(request, st::CancellationToken.None);

            xunit::Assert.Same(expectedResponse, responseCancellationToken);
            mockGrpcClient.VerifyAll();
        }
        private void newCategoryButton_Click(object sender, System.EventArgs e)
        {
            AccessPolicy[] policies = new AccessPolicy[policiesList.Items.Count];
            policiesList.Items.CopyTo(policies, 0);

            AddCategoryForm form = new AddCategoryForm(policies);


            DialogResult result = form.ShowDialog(this);

            if (result != DialogResult.Cancel)
            {
                Category cat = new Category();
                cat.Name     = form.CategoryName;
                cat.PolicyID = form.SelectedPolicy.Id;

                bool success = categoryDAO.AddCategory(cat);
                if (success)
                {
                    categoriesList.Items.Add(cat);
                }
                else
                {
                    Error("Could not create new category.");
                }
            }
        }
示例#7
0
        public void GetAccessPolicy()
        {
            moq::Mock <AccessContextManager.AccessContextManagerClient> mockGrpcClient = new moq::Mock <AccessContextManager.AccessContextManagerClient>(moq::MockBehavior.Strict);

            mockGrpcClient.Setup(x => x.CreateOperationsClient()).Returns(new moq::Mock <lro::Operations.OperationsClient>().Object);
            GetAccessPolicyRequest request = new GetAccessPolicyRequest
            {
                AccessPolicyName = AccessPolicyName.FromAccessPolicy("[ACCESS_POLICY]"),
            };
            AccessPolicy expectedResponse = new AccessPolicy
            {
                AccessPolicyName = AccessPolicyName.FromAccessPolicy("[ACCESS_POLICY]"),
                Parent           = "parent7858e4d0",
                Title            = "title17dbd3d5",
                CreateTime       = new wkt::Timestamp(),
                UpdateTime       = new wkt::Timestamp(),
                Etag             = "etage8ad7218",
            };

            mockGrpcClient.Setup(x => x.GetAccessPolicy(request, moq::It.IsAny <grpccore::CallOptions>())).Returns(expectedResponse);
            AccessContextManagerClient client = new AccessContextManagerClientImpl(mockGrpcClient.Object, null);
            AccessPolicy response             = client.GetAccessPolicy(request.Name);

            xunit::Assert.Same(expectedResponse, response);
            mockGrpcClient.VerifyAll();
        }
示例#8
0
        public static string CreateAccessProfileA11(this IAccessRulesService s, out AccessProfile accessProfile, IEnumerable <Schedule> fullSchedulesList, IEnumerable <AccessPointInfo> fullAccessPointList, string token = "")
        {
            AccessPolicy accessPolicy = null;

            if (fullAccessPointList.Any() && fullSchedulesList.Any())
            {
                accessPolicy = new AccessPolicy()
                {
                    ScheduleToken = fullSchedulesList.First().token,
                    Entity        = fullAccessPointList.First().token,
                    EntityType    = null,
                    Extension     = null
                }
            }
            ;

            var newAccessProfile = new AccessProfile()
            {
                token        = token,
                Name         = "Test Access Profile",
                Description  = "Test Description",
                Extension    = null,
                AccessPolicy = (null != accessPolicy ? new [] { accessPolicy } : null)
            };

            var r = s.CreateAccessProfile(accessProfile = newAccessProfile);

            accessProfile.token = r;
            return(r);
        }
    }
        private void categoriesList_DoubleClick(object sender, System.EventArgs e)
        {
            Category cat          = (Category)categoriesList.SelectedItem;
            string   originalName = cat.Name;

            if (cat != null)
            {
                AccessPolicy[] policies = new AccessPolicy[policiesList.Items.Count];
                policiesList.Items.CopyTo(policies, 0);
                AddCategoryForm form = new AddCategoryForm(policies);

                form.SetModify(cat.Name, (AccessPolicy)policyTable[cat.PolicyID]);

                DialogResult result = form.ShowDialog(this);
                if (result != DialogResult.Cancel)
                {
                    cat.Name     = form.CategoryName;
                    cat.PolicyID = form.SelectedPolicy.Id;

                    bool success = categoryDAO.UpdateCategory(originalName, cat.Name, cat.PolicyID);
                    if (success)
                    {
                        RefreshCategoryList();
                    }
                    else
                    {
                        Error("Could not update category.");
                    }
                }
            }
        }
示例#10
0
文件: XUtils.cs 项目: AlexTagun/Xelon
    public static T_Type getComponent <T_Type>(GameObject inGameObject,
                                               AccessPolicy inComponentAccessPolicy = AccessPolicy.JustFind)
        where T_Type : Component
    {
        T_Type theComponent = inGameObject.GetComponent <T_Type>();

        if (theComponent)
        {
            check(AccessPolicy.ShouldBeCreated != inComponentAccessPolicy);
        }
        else
        {
            switch (inComponentAccessPolicy)
            {
            case AccessPolicy.CreateIfNo:
            case AccessPolicy.ShouldBeCreated:
                theComponent = inGameObject.AddComponent <T_Type>();
                break;

            case AccessPolicy.ShouldExist:
                check(false);
                break;
            }
        }

        return(theComponent);
    }
示例#11
0
        public void SetModify(string categoryName, AccessPolicy selectedPolicy)
        {
            nameText.Text           = categoryName;
            policyList.SelectedItem = selectedPolicy;

            this.Text      = "Modify Category";
            addButton.Text = "Modify";
        }
        public static async Task SaveAsync(AppUser appUser, int officeId, int userId, List <AccessPolicyInfo> model)
        {
            if (!appUser.IsAdministrator)
            {
                return;
            }

            await AccessPolicy.SavePolicyAsync(appUser.Tenant, officeId, userId, model).ConfigureAwait(false);
        }
示例#13
0
        public async void UPLOAD()
        {
            String client_secret_path = @"C:\RACC\json\user.json"; // here you put the path to your .json client secret file, generated in your Google Developer Account
            String username           = "******";                  // youtube account login username


            UserCredential credential;

            using (var stream = new FileStream(client_secret_path, FileMode.Open, FileAccess.Read))
            {
                credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
                    GoogleClientSecrets.Load(stream).Secrets,
                    new[] { YouTubeService.Scope.Youtube, YouTubeService.Scope.YoutubeUpload },
                    username,
                    CancellationToken.None,
                    new FileDataStore(this.GetType().ToString())
                    );
            }

            var youtubeService = new YouTubeService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName       = this.GetType().ToString()
            });

            // first, we get the video we want to update
            var my_video_request = youtubeService.Videos.List("snippet, status");

            my_video_request.Id         = "9P9jLuwXSP0"; // the Youtube video id of the video you want to update
            my_video_request.MaxResults = 1;
            var my_video_response = await my_video_request.ExecuteAsync();

            var video = my_video_response.Items[0];

            // then we change it's attributes
            string        title       = "New title";
            string        description = "New description";
            List <String> keywords    = new List <String>();

            video.Snippet.Title       = title;
            video.Snippet.Description = description;
            // đang truyền tham số kiếm tiền bị sai
            AccessPolicy access = new AccessPolicy();

            access.Allowed = true;
            access.ETag    = "If-None-Match";


            // video.MonetizationDetails = new VideoMonetizationDetails { Access = new AccessPolicy { Allowed = true } };
            video.MonetizationDetails = new VideoMonetizationDetails();
            video.Snippet.Tags        = new System.Collections.Generic.List <String>();

            // and tell the changes we want to youtube
            var my_update_request = youtubeService.Videos.Update(video, "snippet, status");

            my_update_request.Execute();
        }
        public static void Save(int officeId, int userId, List <AccessPolicyInfo> model)
        {
            if (!AppUsers.GetCurrent().IsAdministrator)
            {
                return;
            }

            AccessPolicy.SavePolicy(officeId, userId, model);
        }
        private void policiesList_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            AccessPolicy policy = (AccessPolicy)policiesList.SelectedItem;

            if (policy != null)
            {
                policyIDText.Text = policy.Id;
                policyText.Text   = policy.Document;
            }
        }
示例#16
0
        public NamespacePolicy Type(string name, AccessPolicy accessPolicy, Action <TypePolicy> setup = null)
        {
            var rule = new TypePolicy(name, accessPolicy);

            this.types[name] = rule;

            setup?.Invoke(rule);

            return(this);
        }
        public void TestEquality()
        {
            TimePeriodDefinition timePeriodDefinitionA = "20181231T230000Z/63072000";
            TimePeriodDefinition timePeriodDefinitionB = "20181231T230000Z/63072000";
            AccessPolicy         entityA = new AccessPolicy("000002oe1g25o", new NumberOfLockings(12, 45), new [] { timePeriodDefinitionA });
            AccessPolicy         entityB = new AccessPolicy("000002oe1g25o", new NumberOfLockings(12, 45), new [] { timePeriodDefinitionB });

            Assert.Equal(entityA, entityB);
            Assert.Equal(entityA.GetHashCode(), entityB.GetHashCode());
        }
        public void TestCreation()
        {
            TimePeriodDefinition timePeriodDefinition = "20181231T230000Z/63072000";
            AccessPolicy         entity = new AccessPolicy("000002oe1g25o", new NumberOfLockings(12, 45), new [] { timePeriodDefinition });

            Assert.Equal("000002oe1g25o", entity.Id);
            Assert.Equal(12, entity.NumberOfLockings.Minimum);
            Assert.Equal(45, entity.NumberOfLockings.Maximum);
            Assert.Equal(63072000, entity.TimePeriodDefinitions.First().Duration);
        }
        public LockSystemTest()
        {
            TimePeriodDefinition timePeriodDefinition = "20190211T080000Z/28800/DW(Mo+Tu+We+Th+Fr)/20190329T160000Z";
            AccessPolicy         accessPolicy         = new AccessPolicy("000002oe1g25o", new NumberOfLockings(12, 45), new[] { timePeriodDefinition });

            this.system = CreateEmptyLockSystem()
                          .AddLock(new Lock(TorWestId, "W1", null, "Tor West"))
                          .AddKey(new Key(KlausFenderId, "103-1", null, "Fender, Klaus"))
                          .AddAccessPolicy(accessPolicy);
        }
        private void categoriesList_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            Category category = (Category)categoriesList.SelectedItem;

            if (category != null)
            {
                AccessPolicy policy = (AccessPolicy)policyTable[category.PolicyID];
                currentPolicyText.Text = policy.Name;
            }
        }
示例#21
0
        public WhitelistPolicy Namespace(string name, AccessPolicy accessPolicy, Action <NamespacePolicy> setup = null)
        {
            var rule = new NamespacePolicy(name, accessPolicy);

            this.namespaces[name] = rule;

            setup?.Invoke(rule);

            return(this);
        }
        internal static List <AccessPolicyInfo> Get(int officeId, int userId)
        {
            if (!AppUsers.GetCurrent().IsAdministrator)
            {
                return(new List <AccessPolicyInfo>());
            }

            var data = AccessPolicy.GetPolicy(officeId, userId);

            return(data.Adapt <List <AccessPolicyInfo> >());
        }
示例#23
0
        internal static async Task <List <AccessPolicyInfo> > GetAsync(AppUser appUser, int officeId, int roleId)
        {
            if (!appUser.IsAdministrator)
            {
                return(new List <AccessPolicyInfo>());
            }

            var data = await AccessPolicy.GetGroupPolicyAsync(appUser.Tenant, officeId, roleId).ConfigureAwait(false);

            return(data.Adapt <List <AccessPolicyInfo> >());
        }
示例#24
0
        public static async Task SaveAsync(AppUser appUser, int officeId, int roleId, List <AccessPolicyInfo> model)
        {
            if (!appUser.IsAdministrator)
            {
                return;
            }

            await AccessPolicy.SaveGroupPolicyAsync(appUser.Tenant, officeId, roleId, model).ConfigureAwait(false);

            //Invalidate existing cache data
            string prefix  = $"access_policy_{appUser.Tenant}";
            var    factory = new DefaultCacheFactory();

            factory.RemoveByPrefix(prefix);
        }
示例#25
0
        static void ReadPolicyElement(XmlReader reader, ClientAccessPolicy cap)
        {
            if (reader.HasAttributes || reader.IsEmptyElement)
            {
                reader.Skip();
                return;
            }

            var  policy = new AccessPolicy();
            bool valid  = true;

            reader.ReadStartElement("policy", String.Empty);
            for (reader.MoveToContent(); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent())
            {
                if (IsNonElement(reader))
                {
                    reader.Skip();
                    continue;
                }

                switch (reader.LocalName)
                {
                case "allow-from":
                    ReadAllowFromElement(reader, policy);
                    break;

                case "grant-to":
                    ReadGrantToElement(reader, policy);
                    break;

                default:
                    valid = false;
                    reader.Skip();
                    break;
                }
            }

            if (valid)
            {
                cap.AccessPolicyList.Add(policy);
            }
            reader.ReadEndElement();
        }
        private void setPolicyButton_Click(object sender, System.EventArgs e)
        {
            Category category = (Category)categoriesList.SelectedItem;

            AccessPolicy policy = (AccessPolicy)availablePoliciesList.SelectedItem;

            if (category != null && policy != null)
            {
                category.PolicyID = policy.Id;
                bool success = categoryDAO.UpdateCategory(category.Name, policy.Id);
                if (success)
                {
                    currentPolicyText.Text = policy.Name;
                }
                else
                {
                    Error("Could not update category's policy");
                }
            }
        }
示例#27
0
        /// <summary>
        /// Calls the GetUserPermission operation method in the TrainingService.
        /// </summary>
        /// <param name="userID">A userID value.</param>
        /// <param name="policyId">A policyId value.</param>
        /// <returns>Returns a AccessPolicy object.</returns>
        public AccessPolicy GetUserPermission(long userID, string policyId)
        {
            AccessPolicy result = default(AccessPolicy);
            var          proxy  = new TrainingServiceClient();

            try
            {
                result = proxy.GetUserPermission(userID, policyId);
            }
            catch (FaultException fex)
            {
                // TODO: Handle your exception here or raise it to the UI.
                //		 Do not display sensitive information to the UI.
                throw new ApplicationException(fex.Message);
            }
            finally
            {
                proxy.Close();
            }
            return(result);
        }
        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);
        }
        public EvaluationResult evaluateExpression(XmlElement expressionDoc, IContext context)
        {
            // first deserialize expression into a PolicyReference instance
            PolicyReference expression = null;

            try
            {
                XmlNodeReader reader = new XmlNodeReader(expressionDoc);
                expression = (PolicyReference)serializer.Deserialize(reader);
            }
            catch (Exception e)
            {
                throw new PolicyManagerException("Could not deserialize PolicyReference node", e);
            }

            // TODO: load policy reference from DB
            try
            {
                AccessPolicy policy = policyDAO.GetPolicy(expression.policyId);

                if (policy == null)
                {
                    return(new EvaluationResult(TAG, false, "Policy with id " + expression.policyId + " not found in database."));
                }
                else
                {
                    string           policyDoc = policy.Document;
                    EvaluationResult result    = PolicyManager.evaluatePolicy(policyDoc, context);
                    ArrayList        list      = new ArrayList();
                    list.Add(result);
                    return(new EvaluationResult(TAG, result.Result, "Evaluated policy id " + expression.policyId, list));
                }
            }
            catch (PolicyManagerException e)
            {
                return(new EvaluationResult(TAG, false, "Could not evaluate policy id " + expression.policyId + ": " + e));
            }
        }
    public WebAppStack()
    {
        var resourceGroup = new ResourceGroup("rg-easy-azure-webapp");

        var clientConfig = Output.Create(GetClientConfig.InvokeAsync());

        var tenantId         = clientConfig.Apply(config => config.TenantId);
        var currentPrincipal = clientConfig.Apply(config => config.ObjectId);

        var solutionRoot = System.Environment.GetEnvironmentVariable("SOLUTION_ROOT_DIRECTORY");

        var storageAccount = new Account("storage", new AccountArgs
        {
            ResourceGroupName      = resourceGroup.Name,
            AccountReplicationType = "LRS",
            AccountTier            = "Standard",
        });

        var storageContainer = new Container("files", new ContainerArgs
        {
            StorageAccountName  = storageAccount.Name,
            ContainerAccessType = "private",
        });

        var codeBlob = new Blob("zip", new BlobArgs
        {
            StorageAccountName   = storageAccount.Name,
            StorageContainerName = storageContainer.Name,
            Type = "Block",

            Source = new FileArchive(Path.Join(solutionRoot, "src/Services/EasyAzureWebApp/bin/Debug/netcoreapp3.1/publish"))
        });

        var keyVault = new KeyVault("key-vault", new KeyVaultArgs
        {
            ResourceGroupName = resourceGroup.Name,
            SkuName           = "standard",
            TenantId          = tenantId,
            SoftDeleteEnabled = true,
        });

        var keyVaultPolicy = new AccessPolicy("key-vault-policy", new AccessPolicyArgs
        {
            KeyVaultId        = keyVault.Id,
            TenantId          = tenantId,
            ObjectId          = currentPrincipal,
            SecretPermissions = new[] { "delete", "get", "list", "set" },
        });

        var codeBlobSecret = new Secret("zip-secret", new SecretArgs
        {
            KeyVaultId = keyVault.Id,
            Value      = SharedAccessSignature.SignedBlobReadUrl(codeBlob, storageAccount),
        });

        var codeBlobSecretUrl = Output.All(keyVault.VaultUri, codeBlobSecret.Name, codeBlobSecret.Version)
                                .Apply(d => $"{d[0]}secrets/{d[1]}/{d[2]}");

        var appServicePlan = new Plan("easy-azure-webapp-plan", new PlanArgs
        {
            ResourceGroupName = resourceGroup.Name,
            Kind = "App",
            Sku  = new PlanSkuArgs
            {
                Tier = "Basic",
                Size = "B1",
            },
        });

        var appService = new AppService("easy-azure-webapp", new AppServiceArgs
        {
            ResourceGroupName = resourceGroup.Name,
            AppServicePlanId  = appServicePlan.Id,
            Identity          = new AppServiceIdentityArgs
            {
                Type = "SystemAssigned",
            },
            AppSettings = new InputMap <string>
            {
                { "WEBSITE_RUN_FROM_ZIP", codeBlobSecretUrl.Apply(url => $"@Microsoft.KeyVault(SecretUri={url})") },
            }
        });

        var appServiceGet = AppService.Get("easy-azure-webapp-get", appService.Id,
                                           new AppServiceState
        {
            ResourceGroupName = resourceGroup.Name,
            AppServicePlanId  = appServicePlan.Id,
        },
                                           new CustomResourceOptions
        {
            DependsOn = appService,
        }
                                           );

        var principalId = appServiceGet.Identity.Apply(id => id.PrincipalId !);

        var policy = new AccessPolicy("app-policy", new AccessPolicyArgs
        {
            KeyVaultId        = keyVault.Id,
            TenantId          = tenantId,
            ObjectId          = principalId,
            SecretPermissions = "get",
        });

        var subscriptionOutput = Output.Create(GetSubscription.InvokeAsync());
        var scope = Output.All(
            subscriptionOutput.Apply(s => s.SubscriptionId),
            resourceGroup.Name,
            storageAccount.Name,
            storageContainer.Name
            ).Apply(s => $"/subscriptions/{s[0]}/resourcegroups/{s[1]}/providers/Microsoft.Storage/storageAccounts/{s[2]}/blobServices/default/containers/{s[3]}");

        var codeBlobPermission = new Assignment("read-code-blob", new AssignmentArgs
        {
            PrincipalId        = principalId !,
            Scope              = scope,
            RoleDefinitionName = "Storage Blob Data Reader",
        },
		static void ReadGrantToElement (XmlReader reader, AccessPolicy policy)
		{
			var v = new GrantTo ();
			bool valid = true;

			if (reader.HasAttributes || reader.IsEmptyElement) {
				reader.Skip ();
				return;
			}

			reader.ReadStartElement ("grant-to", String.Empty);
			for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
				if (IsNonElement (reader) || !String.IsNullOrEmpty (reader.NamespaceURI)) {
					reader.Skip ();
					continue;
				}

				switch (reader.LocalName) {
				case "resource":
					var r = CreateResource (reader);
					if (r == null)
						valid = false;
					else
						v.Resources.Add (r);
					break;
				case "socket-resource":
					// ignore everything that is not TCP
					if (reader.GetAttribute ("protocol") != "tcp")
						break;
					// we can merge them all together inside a policy
					policy.PortMask |= ParsePorts (reader.GetAttribute ("port"));
					break;
				default:
					valid = false;
					break;
				}
				reader.Skip ();
			}
			if (valid)
				policy.GrantedResources.Add (v);
			reader.ReadEndElement ();
		}
		static void ReadAllowFromElement (XmlReader reader, AccessPolicy policy)
		{
			if (IsNonEmptyElement (reader)) {
				reader.Skip ();
				return;
			}

			bool valid = true;
			string headers = null;
			string methods = null;		// new in SL3
			if (reader.HasAttributes) {
				int n = reader.AttributeCount;
				headers = reader.GetAttribute ("http-request-headers");
				if (headers != null)
					n--;
				methods = reader.GetAttribute ("http-methods");
				if (methods != null)
					n--;
				valid = (n == 0);
			}

			var v = new AllowFrom ();
			v.HttpRequestHeaders.SetHeaders (headers);
			v.AllowAnyMethod = (methods == "*"); // only legal value defined, otherwise restricted to GET and POST
			reader.ReadStartElement ("allow-from", String.Empty);
			for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
				if (IsNonElement (reader) || !String.IsNullOrEmpty (reader.NamespaceURI)) {
					reader.Skip ();
					continue;
				}
				switch (reader.LocalName) {
				case "domain":
					var d = reader.GetAttribute ("uri");
					if (d == "*")
						v.AllowAnyDomain = true;
					else
						v.Domains.Add (d);
					reader.Skip ();
					break;
				default:
					valid = false;
					reader.Skip ();
					continue;
				}
			}
			if (valid)
				policy.AllowedServices.Add (v);
			reader.ReadEndElement ();
		}
		static void ReadPolicyElement (XmlReader reader, ClientAccessPolicy cap)
		{
			if (reader.HasAttributes || reader.IsEmptyElement) {
				reader.Skip ();
				return;
			}

			var policy = new AccessPolicy ();
			bool valid = true;

			reader.ReadStartElement ("policy", String.Empty);
			for (reader.MoveToContent (); reader.NodeType != XmlNodeType.EndElement; reader.MoveToContent ()) {
				if (IsNonElement (reader)) {
					reader.Skip ();
					continue;
				}

				switch (reader.LocalName) {
				case "allow-from":
					ReadAllowFromElement (reader, policy);
					break;
				case "grant-to":
					ReadGrantToElement (reader, policy);
					break;
				default:
					valid = false;
					reader.Skip ();
					break;
				}
			}

			if (valid)
				cap.AccessPolicyList.Add (policy);
			reader.ReadEndElement ();
		}
示例#34
0
 private AssertResult(AccessPolicy policy, Exception error)
 {
     Policy = policy;
     Error = error;
 }