public void TestChangeType( )
        {
            // Note: refer to additional tests directly on Entity.ChangeType.

            var svc = new EntityInfoService( );

            IEntity e = null;

            try
            {
                e = Entity.Create(new EntityRef("test:person"));

                var ed = new EntityData
                {
                    Id = e.Id
                };
                ed.TypeIds.Add(new EntityRef("test:manager"));

                svc.UpdateEntityType(ed);
            }
            catch
            {
                if (e != null)
                {
                    e.Delete( );
                }
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Given the <paramref name="subject"/> the specified access to <paramref name="securableEntity"/>.
        /// </summary>
        /// <param name="subject">
        /// The subject (user or role). This cannot be null.
        /// </param>
        /// <param name="permissions">
        /// The permission(s) to add. This cannot be null or contain null.
        /// </param>
        /// <param name="securableEntity">
        /// The secured entity (type). This cannot be null.
        /// </param>
        /// <returns>
        /// The <see cref="AccessRule"/> object representing the new query.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// No argument can be null.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// <paramref name="permissions"/> cannot contain null.
        /// </exception>
        public AccessRule AddAllow(Subject subject, IEnumerable <EntityRef> permissions, SecurableEntity securableEntity)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (permissions == null)
            {
                throw new ArgumentNullException("permissions");
            }
            if (permissions.Contains(null))
            {
                throw new ArgumentException("Cannot contain null", "permissions");
            }
            if (securableEntity == null)
            {
                throw new ArgumentNullException("securableEntity");
            }

            AccessRule accessRule;

            accessRule      = Entity.Create <AccessRule>();
            accessRule.Name = string.Format("'{0}' accessing '{1}'", subject.Name ?? string.Empty, securableEntity.Name ?? string.Empty);
            accessRule.AccessRuleEnabled = true;
            accessRule.PermissionAccess.AddRange(permissions.Select(x => x.Entity.As <Permission>()));
            accessRule.ControlAccess = securableEntity;
            accessRule.AllowAccessBy = subject;
            accessRule.Save();

            subject.Save();

            return(accessRule);
        }
Ejemplo n.º 3
0
        public void Test_GetQueries_SubjectWithAccessRuleButNoControl()
        {
            QueryRepository          queryRepository;
            SecurableEntity          securableEntityType;
            AccessRule               accessRule;
            Role                     subject;
            ICollection <AccessRule> result;
            IEntityRepository        entityRepository = Factory.EntityRepository;

            using (DatabaseContext.GetContext(true))
            {
                securableEntityType = Entity.Create <EntityType>().As <SecurableEntity>();
                securableEntityType.Save();

                accessRule = Entity.Create <AccessRule>();
                accessRule.AccessRuleEnabled = true;
                accessRule.PermissionAccess.Add(Permissions.Read.Entity.As <Permission>());
                accessRule.Save();

                subject = Entity.Create <Role>();
                subject.AllowAccess.Add(accessRule.As <AccessRule>());
                subject.Save();

                queryRepository = new QueryRepository();
                result          = new RuleRepository(entityRepository).GetAccessRules(subject.Id, Permissions.Read, new [] { securableEntityType.Id });

                Assert.That(result, Is.Not.Null);
                Assert.That(result, Is.Empty);
            }
        }
        private void Do_AddAllowXXXQuery_AllowSingleXXXAddTwice(EntityRef permission)
        {
            EntityType       securableEntityType;
            IEntity          entity;
            Subject          subject;
            List <EntityRef> permissions;

            using (DatabaseContext.GetContext(true))
            {
                permissions = new List <EntityRef>()
                {
                    permission
                };

                securableEntityType = Entity.Create <EntityType>();
                securableEntityType.Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityType.Save();
                entity = Entity.Create(new EntityRef(securableEntityType.Id));
                entity.SetField("core:name", "Entity 1");
                entity.Save();
                subject = Entity.Create <UserAccount>().As <Subject>();
                subject.Save();

                new AccessRuleFactory().AddAllowByQuery(subject, securableEntityType.As <SecurableEntity>(), permissions, TestQueries.Entities().ToReport());
                new AccessRuleFactory().AddAllowByQuery(subject, securableEntityType.As <SecurableEntity>(), permissions, TestQueries.Entities().ToReport());

                Assert.That(new EntityAccessControlChecker().CheckAccess(new[] { new EntityRef(entity.Id) }, permissions, subject),
                            Has.Exactly(1).Property("Key").EqualTo(entity.Id).And.Property("Value").True);
                Assert.That(subject.AllowAccess.Select(x => x.ControlAccess),
                            Has.Exactly(2).Property("Id").EqualTo(securableEntityType.Id));
                Assert.That(subject.AllowAccess.Where(x => x.ControlAccess.Id == securableEntityType.Id).SelectMany(x => x.PermissionAccess),
                            Has.Exactly(2).Property("Id").EqualTo(permission.Id));
            }
        }
        public void Test_CheckTypeAccess_SingleSpecificType(bool grant)
        {
            var entityType = Entity.Create <EntityType>();

            entityType.Save();

            var userAccount = Entity.Create <UserAccount>();

            userAccount.Save();

            IDictionary <SubjectPermissionTuple, IList <AccessRuleQuery> > rules = new Dictionary <SubjectPermissionTuple, IList <AccessRuleQuery> >();

            if (grant)
            {
                rules.Add(new SubjectPermissionTuple(userAccount.Id, Permissions.Create.Id),
                          new List <AccessRuleQuery> {
                    new AccessRuleQuery(100, 101, entityType.Id, new StructuredQuery(), false)
                });
            }

            var mockRepo = new MockRepository(MockBehavior.Strict);
            var accessQueryFactoryMock = mockRepo.Create <IAccessRuleQueryFactory>();

            accessQueryFactoryMock.Setup(f => f.GetQueries()).Returns(rules);

            var checker = new SystemEntityAccessControlChecker(new UserRoleRepository(), new SystemAccessRuleQueryRepository(accessQueryFactoryMock.Object),
                                                               new EntityTypeRepository());

            var entityTypes = new [] { entityType };

            Assert.AreEqual(grant, checker.CheckTypeAccess(entityTypes, Permissions.Create, userAccount)[entityType.Id], "CheckTypeAccess returned incorrect result");
        }
Ejemplo n.º 6
0
        public void Test_GetQueries_NullSecurableEntityType()
        {
            Role                     testSubject;
            EntityType               testSecurableEntityType;
            AccessRule               accessRule;
            SecurableEntity          securableEntityType;
            ICollection <AccessRule> result;
            IEntityRepository        entityRepository = Factory.EntityRepository;

            using (DatabaseContext.GetContext(true))
            {
                securableEntityType = Entity.Create <EntityType>( ).As <SecurableEntity>( );
                securableEntityType.Save( );

                accessRule = Entity.Create <AccessRule>( );
                accessRule.AccessRuleEnabled = true;
                accessRule.PermissionAccess.Add(Permissions.Read.Entity.As <Permission>( ));
                accessRule.Save( );

                testSubject = Entity.Create <Role>( );
                testSubject.AllowAccess.Add(accessRule.As <AccessRule>( ));
                testSubject.Save();

                testSecurableEntityType = Entity.Create <EntityType>();
                testSecurableEntityType.Save();

                result = null;
                Assert.That(() => result = new RuleRepository(entityRepository).GetAccessRules(testSubject.Id, Permissions.Read, null),
                            Throws.Nothing);
                Assert.That(result, Is.Not.Null);
                Assert.That(result, Has.Count.EqualTo(1));
                Assert.That(result.First( ).Id, Is.EqualTo(accessRule.Id));
            }
        }
        public void Test_CheckAccess_SecurityBypassContext()
        {
            EntityRef[] entityIds;
            IDictionary <long, bool> result;
            UserAccount userAccount;
            EntityAccessControlChecker entityAccessControlChecker;
            MockRepository             mockRepository;

            entityIds = new EntityRef[] { 1, 2, 3 };

            mockRepository = new MockRepository(MockBehavior.Strict);

            entityAccessControlChecker = new EntityAccessControlChecker(
                mockRepository.Create <IUserRoleRepository>().Object,
                mockRepository.Create <IQueryRepository>().Object,
                mockRepository.Create <IEntityTypeRepository>().Object
                );

            userAccount = Entity.Create <UserAccount>();
            userAccount.Save();

            using (new SecurityBypassContext())
            {
                result = entityAccessControlChecker.CheckAccess(entityIds,
                                                                new[] { Permissions.Read },
                                                                userAccount);
            }

            Assert.That(result, Has.Count.EqualTo(entityIds.Count()));
            Assert.That(result, Has.All.Property("Value").True);

            mockRepository.VerifyAll();
        }
Ejemplo n.º 8
0
        public void Test_GetQueries_NullPermission( )
        {
            Role       testSubject;
            EntityType testSecurableEntityType;
            IEnumerable <AccessRuleQuery> result;
            AccessRule      accessRule;
            Report          report;
            QueryRepository queryRepository;

            using (DatabaseContext.GetContext(true))
            {
                testSecurableEntityType = Entity.Create <EntityType>( );
                testSecurableEntityType.Save( );

                report = TestQueries.Entities( ).ToReport( );
                report.Save( );

                accessRule = Entity.Create <AccessRule>( );
                accessRule.AccessRuleEnabled = true;
                accessRule.PermissionAccess.Add(Entity.Get <Permission>(Permissions.Read));
                accessRule.ControlAccess    = testSecurableEntityType.As <SecurableEntity>( );
                accessRule.AccessRuleReport = report;
                accessRule.Save( );

                testSubject = Entity.Create <Role>( );
                testSubject.AllowAccess.Add(accessRule.As <AccessRule>( ));
                testSubject.Save( );

                queryRepository = new QueryRepository( );
                result          = new List <AccessRuleQuery>(queryRepository.GetQueries(testSubject.Id,
                                                                                        null, new [] { testSecurableEntityType.Id }));

                Assert.That(result, Is.Not.Empty);
            }
        }
        private void Do_AddAllowXXXQuery_AllowMultiple(Action <Subject, SecurableEntity> addAccess, ICollection <EntityRef> operations)
        {
            EntityType securableEntityType;
            const int  numEntities = 5;

            Entity[] entities;
            Subject  subject;
            IDictionary <long, bool> result;

            using (DatabaseContext.GetContext(true))
            {
                securableEntityType = Entity.Create <EntityType>();
                securableEntityType.Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityType.Save();
                entities = new Entity[numEntities];
                for (int i = 0; i < numEntities; i++)
                {
                    entities[i] = Entity.Create(new EntityRef(securableEntityType.Id)).As <Entity>();
                    entities[i].Save();
                }
                subject = Entity.Create <UserAccount>().As <Subject>();
                subject.Save();

                addAccess(subject, securableEntityType.As <SecurableEntity>());

                result = new EntityAccessControlChecker().CheckAccess(entities.Select(x => (EntityRef)x).ToList(),
                                                                      operations.ToList(), subject);
                for (int i = 0; i < numEntities; i++)
                {
                    Assert.That(result,
                                Has.Exactly(1).Property("Key").EqualTo(entities[i].Id).And.Property("Value").True);
                }
            }
        }
Ejemplo n.º 10
0
        public void Test_GetQueries_SubjectWithAccessRuleButNoPermissions()
        {
            QueryRepository queryRepository;
            SecurableEntity securableEntityType;
            AccessRule      accessRule;
            Role            subject;
            IEnumerable <AccessRuleQuery> result;
            Report authReport;

            using (DatabaseContext.GetContext(true))
            {
                securableEntityType = Entity.Create <EntityType>().As <SecurableEntity>();
                securableEntityType.Save();

                authReport = Entity.Create <Report>();
                authReport.Save();

                accessRule = Entity.Create <AccessRule>();
                accessRule.AccessRuleEnabled = true;
                accessRule.ControlAccess     = securableEntityType;
                accessRule.AccessRuleReport  = authReport;
                accessRule.Save();

                subject = Entity.Create <Role>();
                subject.AllowAccess.Add(accessRule.As <AccessRule>());
                subject.Save();

                queryRepository = new QueryRepository();
                result          = queryRepository.GetQueries(subject.Id, Permissions.Read, new[] { securableEntityType.Id });

                Assert.That(result, Is.Not.Null);
                Assert.That(result, Is.Empty);
            }
        }
Ejemplo n.º 11
0
        public void Test_AddAllowReadQuery_NameQuery()
        {
            using (DatabaseContext.GetContext(true))
            {
                EntityType securableEntityType1;
                IEntity    entity1A;
                IEntity    entity1Z;
                Subject    subject;
                Report     report;
                IDictionary <long, bool> result;

                securableEntityType1 = Entity.Create <EntityType>();
                securableEntityType1.Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityType1.Save();
                entity1A = Entity.Create(new EntityRef(securableEntityType1.Id));
                entity1A.SetField("core:name", "A");
                entity1A.Save();
                entity1Z = Entity.Create(new EntityRef(securableEntityType1.Id));
                entity1Z.SetField("core:name", "Z");
                entity1Z.Save();
                subject = Entity.Create <UserAccount>().As <Subject>();
                subject.Save();
                report = TestQueries.EntitiesWithNameA().ToReport();

                new AccessRuleFactory().AddAllowReadQuery(subject, securableEntityType1.As <SecurableEntity>(), report);

                result = new EntityAccessControlChecker().CheckAccess(
                    new[] { new EntityRef(entity1A.Id), new EntityRef(entity1Z.Id) },
                    new[] { Permissions.Read },
                    subject);
                Assert.That(result, Has.Property("Count").EqualTo(2));
                Assert.That(result, Has.Exactly(1).Property("Key").EqualTo(entity1A.Id).And.Property("Value").True);
                Assert.That(result, Has.Exactly(1).Property("Key").EqualTo(entity1Z.Id).And.Property("Value").False);
            }
        }
Ejemplo n.º 12
0
        public void Test_AddAllowCreate_AllowMultipleCreate()
        {
            EntityType[]             securableEntityTypes;
            const int                numTypes = 5;
            Subject                  subject;
            IDictionary <long, bool> result;

            IEntity[] entities;

            subject = Entity.Create <UserAccount>().As <Subject>();
            subject.Save();

            securableEntityTypes = new EntityType[numTypes];
            for (int i = 0; i < numTypes; i++)
            {
                securableEntityTypes[i] = Entity.Create <EntityType>();
                securableEntityTypes[i].Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityTypes[i].Save();

                new AccessRuleFactory().AddAllowCreate(subject, securableEntityTypes[i].As <SecurableEntity>());
            }

            entities = new IEntity[numTypes];
            for (int i = 0; i < numTypes; i++)
            {
                entities[i] = Entity.Create(securableEntityTypes[i]);
            }

            result = new EntityAccessControlChecker().CheckAccess(entities.Select(x => new EntityRef(x)).ToList(),
                                                                  new[] { Permissions.Create }, subject);

            Assert.That(result, Has.Count.EqualTo(numTypes));
            Assert.That(result.Keys, Is.EquivalentTo(entities.Select(x => x.Id)));
            Assert.That(result.Values, Has.All.True);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Creates an action menu item.
        /// </summary>
        /// <typeparam name="T">The action menu item implementation.</typeparam>
        /// <param name="name">The name of the menu item.</param>
        /// <param name="emptySelectName">The name to show when selection is empty.</param>
        /// <param name="multiSelectName">The name to show when there are multiple selections.</param>
        /// <param name="order">The ordinal of the menu item.</param>
        /// <param name="isMenu">True if the menu item has been or is to be included in the menu.</param>
        /// <param name="isContextMenu">True if the menu item shows on right click.</param>
        /// <param name="isButton">True if the menu item renders as a button.</param>
        /// <param name="isSeperator">True if this is just a separator for other items.</param>
        /// <param name="isSystem">True if this is a system reserved action menu item.</param>
        /// <param name="singleSelect">True if this menu item applies to single selection.</param>
        /// <param name="multiSelect">True if this menu item applies to multi selection.</param>
        /// <param name="requiredPermissions">Any permission required by this item to appear.</param>
        /// <param name="method">The method string indicating item behavior.</param>
        /// <param name="state">The state information modifying behaviour of the method above.</param>
        /// <param name="target">Optional specific information about the target this item should apply to.</param>
        /// <returns>The created action menu item entity.</returns>
        public static T CreateActionItem <T>(string name, string emptySelectName, string multiSelectName, int?order,
                                             bool isMenu, bool isContextMenu, bool isButton, bool isSeperator, bool isSystem,
                                             bool singleSelect, bool multiSelect, string[] requiredPermissions,
                                             string method, string state, string target) where T : ActionMenuItem
        {
            var action = Entity.Create <T>();

            action.Name                    = name;
            action.EmptySelectName         = emptySelectName;
            action.MultiSelectName         = multiSelectName;
            action.MenuOrder               = order;
            action.IsActionItem            = isMenu;
            action.IsContextMenu           = isContextMenu;
            action.IsActionButton          = isButton;
            action.IsMenuSeparator         = isSeperator;
            action.IsSystem                = isSystem;
            action.AppliesToSelection      = singleSelect;
            action.AppliesToMultiSelection = multiSelect;
            action.HtmlActionMethod        = method;
            action.HtmlActionState         = state;
            action.HtmlActionTarget        = target;
            foreach (var p in requiredPermissions)
            {
                action.ActionRequiresPermission.Add(Entity.Get <Permission>(p));
            }
            return(action);
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Creates an empty console behavior entity.
        /// </summary>
        /// <returns>The created console behavior entity.</returns>
        public static ConsoleBehavior CreateBehavior()
        {
            var cb = Entity.Create <ConsoleBehavior>();

            cb.BehaviorActionMenu = Entity.Create <ActionMenu>();
            return(cb);
        }
Ejemplo n.º 15
0
 public void Test_AddAllowReadQuery_NullReport()
 {
     using (DatabaseContext.GetContext(true))
     {
         Assert.That(() => new AccessRuleFactory().AddAllowReadQuery(Entity.Create <Subject>(), Entity.Create <SecurableEntity>(), null),
                     Throws.TypeOf <ArgumentNullException>().And.Property("ParamName").EqualTo("report"));
     }
 }
        public void TestCloneAndUpdateUpdateFields()
        {
            var svc = new EntityInfoService();

            string initialName        = "Initial name" + Guid.NewGuid();
            string initialDescription = "Initial description" + Guid.NewGuid();

            string newName        = "New name" + Guid.NewGuid();
            string newDescription = "New description" + Guid.NewGuid();

            IEntity e = Entity.Create(new EntityRef("test:person"));

            e.SetField("core:name", initialName);
            e.SetField("core:description", initialDescription);
            e.Save();

            Assert.AreEqual(initialName, e.GetField("core:name"));
            Assert.AreEqual(initialDescription, e.GetField("core:description"));

            var data = new EntityData
            {
                Id     = e.Id,
                Fields = new List <FieldData>()
                {
                    new FieldData
                    {
                        FieldId = new EntityRef("name"),
                        Value   = new TypedValue(newName)
                    },
                    new FieldData
                    {
                        FieldId = new EntityRef("description"),
                        Value   = new TypedValue(newDescription)
                    }
                },
                DataState = DataState.Update
            };

            var cloneIdsMap = svc.CloneAndUpdateEntity(data);

            long cloneId;

            Assert.IsTrue(cloneIdsMap.TryGetValue(e.Id, out cloneId), "The initial entity is not found.");

            // Check the fields were cloned
            IEntity clonedEntity = Entity.Get(cloneId);

            Assert.AreEqual(newName, clonedEntity.GetField("core:name"));
            Assert.AreEqual(newDescription, clonedEntity.GetField("core:description"));

            // Check initial entity is not touched
            IEntity initialEntity = Entity.Get(e.Id);

            Assert.AreEqual(initialName, initialEntity.GetField("core:name"));
            Assert.AreEqual(initialDescription, initialEntity.GetField("core:description"));
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Creates a report template against the specified type.
        /// </summary>
        /// <param name="alias">The alias given to the report template.</param>
        /// <param name="name">The name given to the report template.</param>
        /// <param name="description">The description given to the report template.</param>
        /// <param name="type">The type to apply the report template to.</param>
        /// <returns>The created report template entity.</returns>
        public static ReportTemplate CreateReportTemplate(string alias, string name, string description, EntityType type)
        {
            var template = Entity.Create <ReportTemplate>();

            template.Alias       = alias;
            template.Name        = name;
            template.Description = description;
            template.ReportTemplateAppliesToType = type;
            return(template);
        }
Ejemplo n.º 18
0
        public void Test_GetQueries_SubjectWith2SEs2SQsDifferentPermissions()
        {
            QueryRepository        queryRepository;
            EntityType             securableEntityType1;
            EntityType             securableEntityType2;
            Role                   subject;
            List <StructuredQuery> result;
            Report                 authReport1;
            Report                 authReport2;

            // Test:
            //
            //                           |--------------> Read
            //                           |
            //  Subject -------> Access Rule -----------> SE1
            //           |
            //           |-----> Access Rule -----------> SE2
            //                           |
            //                           |--------------> Modify

            using (DatabaseContext.GetContext(true))
            {
                securableEntityType1 = Entity.Create <EntityType>();
                securableEntityType1.Save();

                authReport1 = TestQueries.Entities().ToReport();
                authReport1.Save();

                securableEntityType2 = Entity.Create <EntityType>();
                securableEntityType2.Save();

                authReport2 = TestQueries.Entities().ToReport();
                authReport2.Save();

                subject = Entity.Create <Role>();
                subject.Save();

                new AccessRuleFactory().AddAllowReadQuery(subject.As <Subject>(), securableEntityType1.As <SecurableEntity>(), authReport1);
                new AccessRuleFactory().AddAllowModifyQuery(subject.As <Subject>(), securableEntityType1.As <SecurableEntity>(), authReport2);

                queryRepository = new QueryRepository();

                result = new List <StructuredQuery>(queryRepository.GetQueries(subject.Id, Permissions.Read,
                                                                               new[] { securableEntityType1.Id, securableEntityType2.Id }).Select(q => q.Query));
                Assert.That(result,
                            Is.EquivalentTo(new [] { ReportToQueryConverter.Instance.Convert(authReport1) })
                            .Using(new StructuredQueryEqualityComparer()), "Incorrect read queries");

                result = new List <StructuredQuery>(queryRepository.GetQueries(subject.Id, Permissions.Modify,
                                                                               new[] { securableEntityType1.Id, securableEntityType2.Id }).Select(q => q.Query));
                Assert.That(result,
                            Is.EquivalentTo(new [] { ReportToQueryConverter.Instance.Convert(authReport2) })
                            .Using(new StructuredQueryEqualityComparer()), "Incorrect modify queries");
            }
        }
Ejemplo n.º 19
0
        public void Test_GetQueries_SubjectWith2SEs2SQs()
        {
            RuleRepository    ruleRepository;
            EntityType        securableEntityType1;
            EntityType        securableEntityType2;
            Role              subject;
            AccessRule        accessRule1;
            AccessRule        accessRule2;
            List <AccessRule> result;
            IEntityRepository entityRepository = Factory.EntityRepository;

            // Test:
            //
            //                           |--------------> Read
            //                           |
            //  Subject -------> Access Rule -----------> SE1
            //           |
            //           |-----> Access Rule -----------> SE2
            //                           |
            //                           |--------------> Read

            using (DatabaseContext.GetContext(true))
            {
                securableEntityType1 = Entity.Create <EntityType>();
                securableEntityType1.Save();

                accessRule1 = Entity.Create <AccessRule>();
                accessRule1.AccessRuleEnabled = true;
                accessRule1.PermissionAccess.Add(Permissions.Read.Entity.As <Permission>());
                accessRule1.ControlAccess = securableEntityType1.As <SecurableEntity>();
                accessRule1.Save();

                securableEntityType2 = Entity.Create <EntityType>();
                securableEntityType2.Save();

                accessRule2 = Entity.Create <AccessRule>();
                accessRule2.AccessRuleEnabled = true;
                accessRule2.PermissionAccess.Add(Permissions.Read.Entity.As <Permission>());
                accessRule2.ControlAccess = securableEntityType2.As <SecurableEntity>();
                accessRule2.Save();

                subject = Entity.Create <Role>();
                subject.AllowAccess.Add(accessRule1.As <AccessRule>());
                subject.AllowAccess.Add(accessRule2.As <AccessRule>());
                subject.Save();

                ruleRepository = new RuleRepository(entityRepository);
                result         = new List <AccessRule>(ruleRepository.GetAccessRules(subject.Id, Permissions.Read,
                                                                                     new[] { securableEntityType1.Id, securableEntityType2.Id }));

                Assert.That(result, Is.Not.Null);
                Assert.That(result, Has.Count.EqualTo(2));
            }
        }
Ejemplo n.º 20
0
        public void Test_AddMultiplePermissions()
        {
            EntityType securableEntityType1;
            EntityType securableEntityType2;
            Entity     entity1;
            Entity     entity2;
            Subject    subject;
            IDictionary <long, bool> result;

            using (DatabaseContext.GetContext(true))
            {
                securableEntityType1 = Entity.Create <EntityType>();
                securableEntityType1.Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityType1.Save();
                securableEntityType2 = Entity.Create <EntityType>();
                securableEntityType2.Inherits.Add(Entity.Get <EntityType>("core:resource"));
                securableEntityType2.Save();
                entity1 = Entity.Create(securableEntityType1).As <Entity>();
                entity1.SetField("core:alias", "entity1__test");
                entity1.Save();
                entity2 = Entity.Create(securableEntityType2).As <Entity>();
                entity2.SetField("core:alias", "entity2__test");
                entity2.Save();
                subject = Entity.Create <UserAccount>().As <Subject>();
                subject.Save();

                new AccessRuleFactory().AddAllowReadQuery(subject, securableEntityType1.As <SecurableEntity>(), TestQueries.Entities().ToReport());
                new AccessRuleFactory().AddAllowReadQuery(subject, securableEntityType2.As <SecurableEntity>(), TestQueries.Entities().ToReport());
                new AccessRuleFactory().AddAllowModifyQuery(subject, securableEntityType2.As <SecurableEntity>(), TestQueries.Entities().ToReport());

                result = new EntityAccessControlChecker().CheckAccess(new EntityRef[] { entity1, entity2 },
                                                                      new[] { Permissions.Read }, subject);
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity1.Id).And.Property("Value").True, "Allow read");
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity2.Id).And.Property("Value").True, "Allow read");

                result = new EntityAccessControlChecker().CheckAccess(new EntityRef[] { entity1, entity2 },
                                                                      new[] { Permissions.Modify }, subject);
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity1.Id).And.Property("Value").False, "Allow modify");
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity2.Id).And.Property("Value").True, "Allow modify");

                result = new EntityAccessControlChecker().CheckAccess(new EntityRef[] { entity1, entity2 },
                                                                      new[] { Permissions.Read, Permissions.Modify }, subject);
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity1.Id).And.Property("Value").False, "Allow read and modify");
                Assert.That(result,
                            Has.Exactly(1).Property("Key").EqualTo(entity2.Id).And.Property("Value").True, "Allow read and modify");
            }
        }
        public void TestCloneAndUpdateTemporaryEntity()
        {
            var svc = new EntityInfoService();

            IEntity e = Entity.Create(new EntityRef("test:person"));

            var ed = new EntityData
            {
                Id = e.Id
            };

            Assert.Throws <InvalidOperationException>(() => svc.CloneAndUpdateEntity(ed));
        }
Ejemplo n.º 22
0
        public void Test_GetQueries_InvalidSubjectId()
        {
            EntityType testSecurableEntityType;

            using (DatabaseContext.GetContext(true))
            {
                testSecurableEntityType = Entity.Create <EntityType>();
                testSecurableEntityType.Save();

                Assert.That(() => new QueryRepository().GetQueries(testSecurableEntityType.Id, Permissions.Read, new[] { testSecurableEntityType.Id }),
                            Throws.ArgumentException.And.Property("ParamName").EqualTo("subjectId"));
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Given the <paramref name="subject" /> the specified access to <paramref name="securableEntity" /> governed by
        /// the query <paramref name="report" />.
        /// </summary>
        /// <param name="subject">The subject (user or role). This cannot be null.</param>
        /// <param name="securableEntity">The secured entity (type). This cannot be null.</param>
        /// <param name="permissions">The permission(s) to add. This cannot be null or contain null.</param>
        /// <param name="report">The query (as a <see cref="Report" />) to add. This should be a new report, not used for any security.
        /// This cannot be null.</param>
        /// <param name="enabled">True if the access rule should be enabled on creation, false if disabled.</param>
        /// <param name="solution">The solution.</param>
        /// <returns>
        /// The <see cref="AccessRule" /> object representing the new query.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">subject
        /// or
        /// securableEntity
        /// or
        /// permissions
        /// or
        /// report</exception>
        /// <exception cref="System.ArgumentException">Cannot contain null - permissions</exception>
        /// <exception cref="ArgumentNullException">No argument can be null.</exception>
        /// <exception cref="ArgumentException">
        ///   <paramref name="permissions" /> cannot contain null.</exception>
        public AccessRule AddAllowByQuery(Subject subject, SecurableEntity securableEntity, IEnumerable <EntityRef> permissions,
                                          Report report, bool enabled = true, Solution solution = null)
        {
            if (subject == null)
            {
                throw new ArgumentNullException("subject");
            }
            if (securableEntity == null)
            {
                throw new ArgumentNullException("securableEntity");
            }
            if (permissions == null)
            {
                throw new ArgumentNullException("permissions");
            }
            if (permissions.Contains(null))
            {
                throw new ArgumentException("Cannot contain null", "permissions");
            }
            if (report == null)
            {
                throw new ArgumentNullException("report");
            }

            AccessRule accessRule;

            // Give a name to avoid warnings about unnamed reports
            if (string.IsNullOrWhiteSpace(report.Name))
            {
                report.Name = "Security report";
            }

            accessRule      = Entity.Create <AccessRule>( );
            accessRule.Name = string.Format("'{0}' accessing '{1}'", subject.Name ?? string.Empty, securableEntity.Name ?? string.Empty);
            accessRule.AccessRuleEnabled = enabled;
            accessRule.PermissionAccess.AddRange(permissions.Select(x => x.Entity.As <Permission>( )));
            accessRule.ControlAccess    = securableEntity;
            accessRule.AccessRuleReport = report;
            accessRule.AllowAccessBy    = subject;

            if (solution != null)
            {
                accessRule.InSolution = solution;
            }

            accessRule.Save( );

            subject.Save( );

            return(accessRule);
        }
Ejemplo n.º 24
0
        internal static IEnumerable <long> InsertDateFieldDummyData(EntityType definition, string newRecordPrefix, string analyserFieldColumnName, string oper, string value, bool isDateOnlyField, int financialYearStartMonth)
        {
            // generate 3 random dateTime values
            DateTime minDate, maxDate;
            var      conditionOper = (ConditionType)Enum.Parse(typeof(ConditionType), oper);
            int?     argument      = null;

            if (!string.IsNullOrEmpty(value))
            {
                argument = int.Parse(value);
            }



            // workout minDate and maxDate
            PeriodConditionHelper.GetPeriodFromConditionType(conditionOper, DateTime.Today, argument, financialYearStartMonth, isDateOnlyField, out minDate, out maxDate);

            // get a random value between min and max date values
            var rand          = new Random();
            var dateDiffTicks = maxDate.Ticks - minDate.Ticks;

            var newEntities           = new long[3];
            var textFieldColumnId     = definition.Fields.FirstOrDefault(f => f.Name == "TextField").Id;
            var analyserFieldColumnId = definition.Fields.FirstOrDefault(f => f.Name == analyserFieldColumnName).Id;

            // get
            using (DatabaseContext.GetContext(false))
            {
                for (int ctr = 0; ctr < 3; ctr++)
                {
                    string randomTextFieldColValue = string.Format("{0}-{1}", newRecordPrefix, DateTime.Now.ToUniversalTime().ToLongTimeString());
                    var    randPercentNum          = rand.Next(1, 100);
                    var    randomTicks             = dateDiffTicks * randPercentNum / 100;
                    var    dt = minDate.AddTicks(randomTicks);  // add a random percentage of difference to the min date value

                    // server stores value in utc. 'dateToSave' is saved as it is.
                    // in case of dateOnly field, time portion is ignored and only date value is used. thats why we save 'dt' as it is.
                    // in case of dateAndTime field, the whole vale is adjusted to current timezone. Thats why we save the utc vale of 'dt'.
                    var dateToSave = isDateOnlyField ? dt : dt.ToUniversalTime();

                    var entity = Entity.Create(definition.Id);
                    entity.SetField(textFieldColumnId, randomTextFieldColValue);
                    entity.SetField(analyserFieldColumnId, dateToSave);
                    entity.Save();

                    newEntities[ctr] = entity.Id;
                }
            }
            return(newEntities);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Create entities used for testing.
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="matchingName"></param>
        protected override IEntity[] CreateEntities(EntityType entityType, string matchingName)
        {
            const int numEntities = 5;

            IEntity[] result;

            result = new IEntity[numEntities];
            for (int i = 0; i < numEntities; i++)
            {
                result[i] = Entity.Create(entityType);
                result[i].Save();
            }

            return(result);
        }
        public void Test_CheckTypeAccess_CreateSingleInheritedType(bool grant)
        {
            var derivedEntityType = new EntityType {
                Name = "Derived Type " + Guid.NewGuid()
            };

            derivedEntityType.Save();

            var baseEntityType = new EntityType {
                Name = "Base Type " + Guid.NewGuid()
            };

            baseEntityType.DerivedTypes.Add(derivedEntityType);
            baseEntityType.Save();

            var userAccount = Entity.Create <UserAccount>();

            userAccount.Save();

            IDictionary <SubjectPermissionTuple, IList <AccessRuleQuery> > rules = new Dictionary <SubjectPermissionTuple, IList <AccessRuleQuery> >();

            if (grant)
            {
                // Grant access to base type
                rules.Add(new SubjectPermissionTuple(userAccount.Id, Permissions.Create.Id),
                          new List <AccessRuleQuery> {
                    new AccessRuleQuery(100, 101, baseEntityType.Id, new StructuredQuery(), false)
                });
            }

            var mockRepo = new MockRepository(MockBehavior.Strict);
            var accessQueryFactoryMock = mockRepo.Create <IAccessRuleQueryFactory>();

            accessQueryFactoryMock.Setup(f => f.GetQueries()).Returns(rules);

            var checker = new SystemEntityAccessControlChecker(new UserRoleRepository(), new SystemAccessRuleQueryRepository(accessQueryFactoryMock.Object),
                                                               new EntityTypeRepository());

            // Check derived type

            var derivedEntityTypes = new [] { derivedEntityType };
            var baseEntityTypes    = new [] { baseEntityType };

            Assert.AreEqual(grant, checker.CheckTypeAccess(derivedEntityTypes, Permissions.Create, userAccount)[derivedEntityType.Id], "CheckTypeAccess returned incorrect result");
            Assert.AreEqual(grant, checker.CheckTypeAccess(baseEntityTypes, Permissions.Create, userAccount)[baseEntityType.Id], "CheckTypeAccess returned incorrect result");
        }
        public void Test_CheckAccess_AccessByQueryOnly()
        {
            UserAccount              userAccount;
            SecurableEntity          securableEntity;
            IDictionary <long, bool> result;
            AccessRule accessRule;
            Report     authReport;

            // Test:
            //
            //                                      Folder Instance
            //                                          ^
            //                                          |
            //                                          |
            //  UserAccount ----> AccessRule -----> FolderType
            //
            //             (no PermissionAccess relationship)
            //

            using (DatabaseContext.GetContext(true))
            {
                securableEntity = Entity.Create <SecurableEntity>();
                securableEntity.Save();

                authReport = Entity.Create <Report>();
                authReport.Save();

                accessRule = Entity.Create <AccessRule>();
                accessRule.AccessRuleEnabled = true;
                accessRule.AccessRuleReport  = authReport;
                accessRule.ControlAccess     = securableEntity;
                // Do not set accessRule.PermissionAccess
                accessRule.Save();

                userAccount = Entity.Create <UserAccount>();
                userAccount.AllowAccess.Add(accessRule.As <AccessRule>());
                userAccount.Save();

                result = new EntityAccessControlChecker().CheckAccess(new[] { new EntityRef(securableEntity.Id) },
                                                                      new[] { Permissions.Read },
                                                                      new EntityRef(userAccount.Id));

                Assert.That(result[securableEntity.Id], Is.False);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Create entities used for testing.
        /// </summary>
        /// <param name="entityType"></param>
        /// <param name="matchingName"></param>
        protected override IEntity[] CreateEntities(EntityType entityType, string matchingName)
        {
            const int numEntities = 10;

            IEntity[] result;

            result = new IEntity[numEntities];
            for (int i = 0; i < numEntities; i++)
            {
                result[i] = Entity.Create(entityType);
                // Set the odd numbered entities to have the matching name
                if (i % 2 == 1)
                {
                    result[i].SetField("core:name", matchingName);
                }
                result[i].Save();
            }

            return(result);
        }
Ejemplo n.º 29
0
        public void Test_AddAllowCreate_BasicAllowCreate()
        {
            EntityType securableEntityType;
            Subject    subject;
            IEntity    entity;

            securableEntityType = Entity.Create <EntityType>();
            securableEntityType.Inherits.Add(Entity.Get <EntityType>("core:resource"));
            securableEntityType.Save();

            subject = Entity.Create <UserAccount>().As <Subject>();
            subject.Save();

            new AccessRuleFactory().AddAllowCreate(subject, securableEntityType.As <SecurableEntity>());

            entity = Entity.Create(securableEntityType);
            Assert.That(new EntityAccessControlChecker().CheckAccess(new[] { new EntityRef(entity) },
                                                                     new [] { Permissions.Create }, subject),
                        Has.Exactly(1).Property("Key").EqualTo(entity.Id).And.Property("Value").True);
        }
Ejemplo n.º 30
0
        public void Test_GetQueries_EmptySecurableEntityType()
        {
            Role       testSubject;
            EntityType testSecurableEntityType;
            IEnumerable <AccessRuleQuery> result;

            using (DatabaseContext.GetContext(true))
            {
                testSubject = Entity.Create <Role>();
                testSubject.Save();

                testSecurableEntityType = Entity.Create <EntityType>();
                testSecurableEntityType.Save();

                result = null;
                Assert.That(() => result = new QueryRepository().GetQueries(testSubject.Id, Permissions.Read, new long[0]),
                            Throws.Nothing);
                Assert.That(result, Is.Not.Null);
                Assert.That(result, Is.Empty);
            }
        }