private void Do_AddAllowXXXQuery_AllowSingleXXX(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());

                Assert.That(new EntityAccessControlChecker().CheckAccess(new[] { new EntityRef(entity.Id) },
                                                                         permissions, subject),
                            Has.Exactly(1).Property("Key").EqualTo(entity.Id).And.Property("Value").True);
            }
        }
        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);
            }
        }
        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);
            }
        }
Exemple #4
0
        public void Test_EnableReadRule(string description, IEntityAccessControlChecker entityAccessControlChecker)
        {
            AccessRule  accessRule;
            EntityType  entityType;
            UserAccount userAccount;
            IEntity     entity1;
            IDictionary <long, bool> result;

            using (var ctx = DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
            {
                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();

                userAccount = Entity.Create <UserAccount>();

                accessRule = Entity.Create <AccessRule>();
                accessRule.AccessRuleEnabled = false;
                accessRule.PermissionAccess.Add(Permissions.Read.Entity.As <Permission>());
                accessRule.ControlAccess    = entityType.As <SecurableEntity>();
                accessRule.AccessRuleReport = TestQueries.Entities().ToReport();
                accessRule.Save();

                userAccount.AllowAccess.Add(accessRule);
                userAccount.Save();

                entity1 = Entity.Create(entityType);
                entity1.Save();
                ctx.CommitTransaction();
            }

            // Ensure no access
            result = entityAccessControlChecker.CheckAccess(
                new[] { new EntityRef(entity1) },
                new[] { Permissions.Read },
                userAccount);
            Assert.That(result, Has.Count.EqualTo(1));
            Assert.That(result, Has.Exactly(1).Property("Key").EqualTo(entity1.Id)
                        .And.Property("Value").False, "Disabled check");

            using (var ctx = DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
            {
                accessRule.AccessRuleEnabled = true;
                accessRule.Save();
                ctx.CommitTransaction();
            }

            // Ensure access
            result = entityAccessControlChecker.CheckAccess(
                new[] { new EntityRef(entity1) },
                new[] { Permissions.Read },
                userAccount);
            Assert.That(result, Has.Count.EqualTo(1));
            Assert.That(result, Has.Exactly(1).Property("Key").EqualTo(entity1.Id)
                        .And.Property("Value").True, "Enabled check");
        }
        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");
            }
        }
Exemple #6
0
        private IEnumerable <TestCaseData> Test_GetReferencedRelationshipTypes_Source()
        {
            // Using a Func<StructuredQuery> rather than a straight StructuredQuery to
            // avoid issues with NUnit and using a CallContext in a TestCaseSource method.

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.Entities()), new string[0]));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.AccessRulesWithNamedPermission("read")), new[] { "core:permissionAccess" }));

            // Get multiple relationships form the root entity, including an enum
            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.ActiveUsersInRole("administrators")), new[] { "core:userHasRole", "core:accountStatus" }));

            // Test nested related resource nodes and reverse relationships
            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.TypesSecuredBySubjects("administrators")), new[] { "core:allowAccess", "core:controlAccess" }));
        }
Exemple #7
0
        private IEnumerable <TestCaseData> Test_GetFieldTypesReferencedByCondition_Source()
        {
            // Using a Func<StructuredQuery> rather than a straight StructuredQuery to
            // avoid issues with NUnit and using a CallContext in a TestCaseSource method.

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.Entities()), new string[0]));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithNameA()), new[] { "core:name" }));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithDescription()), new[] { "core:description" }));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithNameDescription("a", "a")), new[] { "core:name", "core:description" }));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithNameAndDescriptionInResults("a")), new[] { "core:name" }));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.AccessRulesWithNamedPermission("read")), new[] { "core:name", "core:accessRuleEnabled" }));

            yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.ActiveUsersInRole("administrators")), new[] { "core:name", "core:alias" }));
        }
Exemple #8
0
        public void CreateSuperAdminAccount()
        {
            UserAccount        superAdministratorUserAccount;
            IAccessRuleFactory accessRuleFactory;

            superAdministratorUserAccount = new UserAccount
            {
                Name = SpecialStrings.SystemAdministratorUser,
                AccountStatus_Enum = UserAccountStatusEnum_Enumeration.Disabled
            };
            superAdministratorUserAccount.Save();

            accessRuleFactory = new AccessRuleFactory();
            accessRuleFactory.AddAllowByQuery(
                superAdministratorUserAccount.As <Subject>(),
                Entity.Get <SecurableEntity>("core:resource"),
                new[] { Permissions.Create, Permissions.Read, Permissions.Modify, Permissions.Delete },
                TestQueries.Entities().ToReport()
                );
        }
        public void TestSinglePermissionQuery(string permissionAlias)
        {
            QueryRepository        queryRepository;
            SecurableEntity        securableEntityType;
            AccessRule             accessRule;
            Role                   subject;
            List <AccessRuleQuery> result;
            Permission             permission;
            Report                 report;

            using (DatabaseContext.GetContext(true))
            {
                permission = Entity.Get <Permission>(permissionAlias);

                securableEntityType = Entity.Create <EntityType>().As <SecurableEntity>();
                securableEntityType.Save();

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

                accessRule = Entity.Create <AccessRule>();
                accessRule.AccessRuleEnabled = true;
                accessRule.PermissionAccess.Add(permission);
                accessRule.ControlAccess    = securableEntityType;
                accessRule.AccessRuleReport = report;
                accessRule.Save();

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

                queryRepository = new QueryRepository();
                result          = new List <AccessRuleQuery>(queryRepository.GetQueries(subject.Id,
                                                                                        permission, new[] { securableEntityType.Id }));

                Assert.That(result, Has.Count.EqualTo(1));
                Assert.That(TestQueries.IsCreatedFrom(result[0].Query, report), Is.True);
            }
        }
        public void TestQueriesGetFiltered(QueryFilter queryFilter, int mockResultToMatch, bool nullParams)
        {
            FilteringQueryRepository filteringRepository;
            Mock <IQueryRepository>  mockRepository;
            long         subjectId      = 1;
            EntityRef    permissionId   = nullParams ? null : new EntityRef(2);
            long         typeId         = 3;
            IList <long> securableTypes = nullParams ? null : new List <long> {
                typeId
            };
            StructuredQuery queryWithCurrentUser;
            StructuredQuery queryWithoutCurrentUser;

            AccessRuleQuery[]             mockResults;
            IEnumerable <AccessRuleQuery> result;

            queryWithoutCurrentUser = TestQueries.Entities(new EntityRef(typeId));
            queryWithCurrentUser    = TestQueries.Entities(new EntityRef(typeId));
            queryWithCurrentUser.Conditions.Add(new QueryCondition {
                Operator = ConditionType.CurrentUser
            });

            mockResults = new AccessRuleQuery[]
            {
                new AccessRuleQuery(1, 2, 3, queryWithoutCurrentUser, false),
                new AccessRuleQuery(4, 5, 6, queryWithCurrentUser, false)
            };

            mockRepository = new Mock <IQueryRepository>(MockBehavior.Strict);
            mockRepository.Setup(qr => qr.GetQueries(subjectId, permissionId, securableTypes)).Returns(mockResults);

            filteringRepository = new FilteringQueryRepository(mockRepository.Object, queryFilter);
            result = filteringRepository.GetQueries(subjectId, permissionId, securableTypes);

            Assert.That(result, Is.EquivalentTo(new[] { mockResults[mockResultToMatch] }));
        }
        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");
            }
        }
Exemple #12
0
        public void SetupEntities()
        {
            using (DatabaseContext context = DatabaseContext.GetContext(true))
            {
                using (new SecurityBypassContext())
                {
                    Role              administratorRole;
                    EntityType        resourceType;
                    AccessRuleFactory accessControlHelper;

                    administratorRole = Entity.Get <Role>(new EntityRef("core", "administratorRole"), true);
                    resourceType      = Entity.Get <EntityType>(new EntityRef("core", "resource"));
                    // resourceType = Entity.Get<EntityType>(new EntityRef("core", "securableEntity"));
                    accessControlHelper = new AccessRuleFactory();

                    accessControlHelper.AddAllowCreate(administratorRole.As <Subject>(), resourceType.As <SecurableEntity>());
                    accessControlHelper.AddAllowByQuery(administratorRole.As <Subject>(), resourceType.As <SecurableEntity>(),
                                                        new[] { Permissions.Read, Permissions.Modify, Permissions.Delete }, TestQueries.Entities().ToReport());

                    context.CommitTransaction();
                }
            }
        }
 public void Test_AddAllowDeleteQuery_AllowMultipleDelete()
 {
     Do_AddAllowXXXQuery_AllowMultiple(
         (s, se) => new AccessRuleFactory().AddAllowDeleteQuery(s, se, TestQueries.Entities().ToReport()),
         new[] { Permissions.Delete });
 }
Exemple #14
0
        public void Test_ChangeAccessRuleForPermissions()
        {
            UserAccount userAccount;
            EntityType  entityType;
            IEntity     entity;
            EntityRef   entityRef;
            AccessRule  accessRule;
            IEntityAccessControlService entityAccessControlService;
            Permission readPermission;
            Permission modifyPermission;

            using (var ctx = DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
                using (new SecurityBypassContext())
                {
                    userAccount      = new UserAccount();
                    userAccount.Name = Guid.NewGuid().ToString();
                    userAccount.Save();

                    entityType = new EntityType();
                    entityType.Inherits.Add(UserResource.UserResource_Type);
                    entityType.Save();

                    entity = Entity.Create(entityType);
                    entity.Save();
                    entityRef = new EntityRef(entity);

                    entityAccessControlService = Factory.EntityAccessControlService;

                    ctx.CommitTransaction();
                }

            using (new SetUser(userAccount))
            {
                Assert.That(entityAccessControlService.Check(entityRef, new[] { Permissions.Read }), Is.False,
                            "User can somehow initially read entities (!?)");
                Assert.That(entityAccessControlService.Check(entityRef, new[] { Permissions.Modify }), Is.False,
                            "User can somehow initially write entities (!?)");
            }


            using (var ctx = DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
                using (new SecurityBypassContext())
                {
                    accessRule = new AccessRuleFactory().AddAllowByQuery(
                        userAccount.As <Subject>(),
                        entityType.As <SecurableEntity>(),
                        new[] { Permissions.Read, Permissions.Modify },
                        TestQueries.Entities(entityType).ToReport());
                    ctx.CommitTransaction();
                }

            readPermission   = Entity.Get <Permission>(Permissions.Read, true);
            modifyPermission = Entity.Get <Permission>(Permissions.Modify, true);

            using (new SetUser(userAccount))
            {
                Assert.That(entityAccessControlService.Check(entityRef, new[] { Permissions.Read }), Is.True,
                            "User cannot read entity after access rule creation");
                Assert.That(entityAccessControlService.Check(entityRef, new[] { Permissions.Modify }), Is.True,
                            "User cannot modify entity after access rule creation");
            }

            using (var ctx = DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
            {
                modifyPermission.PermissionAccessBy.Remove(accessRule);
                modifyPermission.Save();
                ctx.CommitTransaction();
            }

            using (new SetUser(userAccount))
            {
                Assert.That(entityAccessControlService.Check(entityRef, new[] { Permissions.Read }), Is.True,
                            "User cannot read entity after removing modify access");
                Assert.That(entityAccessControlService.Check(entityRef, new[] { Permissions.Modify }), Is.False,
                            "User can modify entity after removing modify access");
            }

            using (var ctx = DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
            {
                readPermission.PermissionAccessBy.Remove(accessRule);
                readPermission.Save();
                ctx.CommitTransaction();
            }

            using (new SetUser(userAccount))
            {
                Assert.That(entityAccessControlService.Check(entityRef, new[] { Permissions.Read }), Is.False,
                            "User can read entity after removing read access");
                Assert.That(entityAccessControlService.Check(entityRef, new[] { Permissions.Modify }), Is.False,
                            "User can modify entity after removing read access");
            }

            using (var ctx = DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
            {
                readPermission.PermissionAccessBy.Add(accessRule);
                readPermission.Save();
                ctx.CommitTransaction();
            }

            using (new SetUser(userAccount))
            {
                Assert.That(entityAccessControlService.Check(entityRef, new[] { Permissions.Read }), Is.True,
                            "User cannot read entity after re-adding read access");
                Assert.That(entityAccessControlService.Check(entityRef, new[] { Permissions.Modify }), Is.False,
                            "User can modify entity after re-adding read access");
            }
        }
        public void Test_RelationshipInstance(string action, string fromPerms, string toPerms, Direction direction, bool saveBothEnds, bool haveFieldChanges, bool expectAllow)
        {
            if (fromPerms == "modify")
            {
                fromPerms = "read,modify";
            }
            if (toPerms == "modify")
            {
                toPerms = "read,modify";
            }

            // Create schema
            EntityType fromType = new EntityType();

            fromType.Inherits.Add(UserResource.UserResource_Type);
            fromType.Name = Guid.NewGuid().ToString();
            fromType.Save();

            EntityType toType = new EntityType();

            toType.Inherits.Add(UserResource.UserResource_Type);
            toType.Name = Guid.NewGuid().ToString();
            toType.Save();

            Relationship rel = new Relationship();

            rel.Name             = Guid.NewGuid().ToString();
            rel.FromType         = fromType;
            rel.ToType           = toType;
            rel.Cardinality_Enum = CardinalityEnum_Enumeration.ManyToMany;
            rel.Save();

            // Create data
            IEntity toInst = new Entity(toType);

            toInst.Save();
            IEntity fromInst = new Entity(fromType);

            if (action != "Create")
            {
                fromInst.SetRelationships(rel, new EntityRelationshipCollection <IEntity> {
                    toInst
                });
            }
            fromInst.Save();

            // Create test user
            UserAccount userAccount = Entity.Create <UserAccount>();

            userAccount.Name = Guid.NewGuid().ToString();
            userAccount.Save();

            // Grant access
            if (!string.IsNullOrEmpty(fromPerms))
            {
                new AccessRuleFactory().AddAllowByQuery(
                    userAccount.As <Subject>(),
                    fromType.As <SecurableEntity>(),
                    fromPerms.Split(',').Select(pa => new EntityRef(pa)),
                    TestQueries.Entities().ToReport());
            }
            if (!string.IsNullOrEmpty(toPerms))
            {
                new AccessRuleFactory().AddAllowByQuery(
                    userAccount.As <Subject>(),
                    toType.As <SecurableEntity>(),
                    toPerms.Split(',').Select(pa => new EntityRef(pa)),
                    TestQueries.Entities().ToReport());
            }

            // Test

            bool allowed = false;

            try
            {
                using (new SetUser(userAccount))
                {
                    IEntity source = Entity.Get(direction == Direction.Forward ? fromInst.Id : toInst.Id);
                    if (action != "Read")
                    {
                        source = source.AsWritable();
                    }
                    Func <IEntity> target = () => Entity.Get(direction == Direction.Forward ? toInst.Id : fromInst.Id);

                    IEntityRelationshipCollection <IEntity> relCol = null;

                    switch (action)
                    {
                    case "Read":
                        relCol = source.GetRelationships(rel.Id, direction);
                        IEntity entity = relCol.FirstOrDefault();
                        allowed = entity != null;
                        break;

                    case "Create":
                        relCol = new EntityRelationshipCollection <IEntity> {
                            target()
                        };
                        source.SetRelationships(rel, relCol);
                        if (haveFieldChanges)
                        {
                            source.SetField("core:name", Guid.NewGuid().ToString());
                        }
                        if (saveBothEnds)
                        {
                            Entity.Save(new[] { source, target() });
                        }
                        else
                        {
                            source.Save();
                        }
                        allowed = true;
                        break;

                    case "Remove":
                        relCol = source.GetRelationships(rel.Id, direction);
                        relCol.Remove(target());
                        source.SetRelationships(rel, relCol);
                        if (haveFieldChanges)
                        {
                            source.SetField("core:name", Guid.NewGuid().ToString());
                        }
                        if (saveBothEnds)
                        {
                            Entity.Save(new[] { source, target() });
                        }
                        else
                        {
                            source.Save();
                        }
                        allowed = true;
                        break;

                    case "Clear":
                        relCol = source.GetRelationships(rel.Id, direction);
                        relCol.Clear();
                        source.SetRelationships(rel, relCol);
                        if (haveFieldChanges)
                        {
                            source.SetField("core:name", Guid.NewGuid().ToString());
                        }
                        if (saveBothEnds)
                        {
                            Entity.Save(new[] { source, target() });
                        }
                        else
                        {
                            source.Save();
                        }
                        allowed = true;
                        break;

                    default:
                        throw new InvalidOperationException("Unknown " + action);
                    }
                }
                Assert.That(allowed, Is.EqualTo(expectAllow));
            }
            catch (PlatformSecurityException)
            {
                Assert.That(false, Is.EqualTo(expectAllow));
            }
        }
Exemple #16
0
        public void Test_AddingNewRuleToRole( )
        {
            EntityType           entityType1;
            EntityType           entityType2;
            UserAccount          userAccount;
            Role                 role1;
            UserRuleSet          userRuleSet1;
            IUserRuleSetProvider userRuleSetProvider;

            using (var ctx = DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
            {
                entityType1 = EDC.ReadiNow.Model.Entity.Create <EntityType>();
                entityType1.Save();
                entityType2 = EDC.ReadiNow.Model.Entity.Create <EntityType>();
                entityType2.Save();

                role1 = new Role();
                role1.Save();

                userAccount = new UserAccount();
                userAccount.UserHasRole.Add(role1);
                userAccount.Save();

                new AccessRuleFactory().AddAllowReadQuery(role1.As <Subject>(), entityType1.As <SecurableEntity>(), TestQueries.Entities(entityType1).ToReport());

                userRuleSetProvider = Factory.UserRuleSetProvider;
                userRuleSet1        = userRuleSetProvider.GetUserRuleSet(userAccount.Id, Permissions.Read);

                // Add a new rule
                new AccessRuleFactory().AddAllowReadQuery(role1.As <Subject>(), entityType2.As <SecurableEntity>(), TestQueries.Entities(entityType2).ToReport());
                ctx.CommitTransaction();
            }

            UserRuleSet userRuleSet2 = userRuleSetProvider.GetUserRuleSet(userAccount.Id, Permissions.Read);

            Assert.That(userRuleSet1, Is.Not.EqualTo(userRuleSet2));
        }
        public void Test_GetQueries_SubjectWith2SEs2SQs()
        {
            QueryRepository        queryRepository;
            EntityType             securableEntityType1;
            EntityType             securableEntityType2;
            Role                   subject;
            AccessRule             accessRule1;
            AccessRule             accessRule2;
            List <AccessRuleQuery> result;
            Report                 authReport1;
            Report                 authReport2;

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

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

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

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

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

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

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

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

                queryRepository = new QueryRepository();
                result          = new List <AccessRuleQuery>(queryRepository.GetQueries(subject.Id, Permissions.Read,
                                                                                        new[] { securableEntityType1.Id, securableEntityType2.Id }));

                Assert.That(result, Is.Not.Null);
                Assert.That(result, Has.Count.EqualTo(2));
                Assert.That(result.Select(q => q.Query),
                            Is.EquivalentTo(new [] {
                    ReportToQueryConverter.Instance.Convert(authReport1),
                    ReportToQueryConverter.Instance.Convert(authReport2)
                })
                            .Using(new StructuredQueryEqualityComparer()));
            }
        }