示例#1
0
        public void Test_BasicSave(bool allowCreate)
        {
            UserAccount userAccount = null;
            EntityType  entityType  = null;
            IEntity     entity      = null;
            string      userName;

            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "Test user " + Guid.NewGuid().ToString();
            userAccount.Save();

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

            if (allowCreate)
            {
                new AccessRuleFactory().AddAllow(userAccount.As <Subject>(),
                                                 new [] { Permissions.Create }, entityType.As <SecurableEntity>());
            }

            userName = userAccount.Name;
            using (new SetUser(userAccount))
            {
                Assert.That(() => entity = Entity.Create(entityType),
                            Throws.Nothing);
                Assert.That(() => entity.Save(),
                            allowCreate ? (Constraint)Throws.Nothing
                        : Throws.TypeOf <PlatformSecurityException>()
                            .And.EqualTo(new PlatformSecurityException(userName, new[] { Permissions.Create }, new [] { new EntityRef(entity) })));
            }
        }
示例#2
0
        public void TestOnDeleteAccessRule()
        {
            bool   success     = true;
            string subjectName = "Role" + Guid.NewGuid();
            string typeName    = "Type" + Guid.NewGuid();
            string reportName  = "Report" + Guid.NewGuid();

            var mockAuditLog = new Mock <IAuditLog>(MockBehavior.Strict);

            mockAuditLog.Setup(al => al.OnDeleteAccessRule(success, subjectName, typeName, reportName));

            var eventTarget = new AuditLogAccessRuleEventTarget(mockAuditLog.Object);

            var subject = new Role {
                Name = subjectName
            };
            var type = new EntityType {
                Name = typeName
            };
            var report = new Report {
                Name = reportName
            };
            var accessRule = new AccessRule {
                AllowAccessBy = subject.As <Subject>(), ControlAccess = type.As <SecurableEntity>(), AccessRuleReport = report
            };

            IDictionary <string, object> state = new Dictionary <string, object>();

            eventTarget.GatherAuditLogEntityDetailsForDelete(accessRule, state);
            eventTarget.WriteDeleteAuditLogEntries(success, accessRule.Id, state);

            mockAuditLog.VerifyAll();
        }
        public void Test_GetDisplayReportForSecurableEntity_EnsureDifferent()
        {
            EntityType entityType;
            IAccessRuleReportFactory accessRuleReportFactory;
            Report report1;
            Report report2;

            entityType = new EntityType();
            entityType.Save();

            accessRuleReportFactory = new AccessRuleDisplayReportFactory();
            report1 = accessRuleReportFactory.GetDisplayReportForSecurableEntity(entityType.As <SecurableEntity>());
            report2 = accessRuleReportFactory.GetDisplayReportForSecurableEntity(entityType.As <SecurableEntity>());

            Assert.That(report1, Has.Property("Id").Not.EqualTo(report2.Id));
        }
示例#4
0
        public void Test_EnableCreateRule()
        {
            UserAccount userAccount;
            EntityType  entityType1;
            AccessRule  accessRule;
            IEntityAccessControlService entityAccessControlService;

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

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

                    entityAccessControlService = Factory.EntityAccessControlService;
                    ctx.CommitTransaction();
                }

            using (new SetUser(userAccount))
            {
                Assert.That(entityAccessControlService.CanCreate(entityType1), Is.False,
                            "User can somehow initially create entities (!?)");
            }

            using (var ctx = DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true))
                using (new SecurityBypassContext())
                {
                    accessRule = new AccessRuleFactory().AddAllowCreate(
                        userAccount.As <Subject>(),
                        entityType1.As <SecurableEntity>());
                    ctx.CommitTransaction();
                }

            using (new SetUser(userAccount))
            {
                Assert.That(entityAccessControlService.CanCreate(entityType1), Is.True,
                            "User cannot initially create entities");
            }

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

            using (new SetUser(userAccount))
            {
                Assert.That(entityAccessControlService.CanCreate(entityType1), Is.False,
                            "User can create entities afterwards (!?)");
            }
        }
示例#5
0
        //[TestCase("core:modify", false, true)]  // unsupported
        //[TestCase("core:delete", false, false)] // unsupported
        //[TestCase( "core:modify,core:delete", false, true )] // unsupported
        public void Test_Save(string permissionAliases, bool canGetEntity, bool canSaveEntity)
        {
            UserAccount userAccount = null;
            EntityType  entityType  = null;
            IEntity     entity1     = null;
            IEntity     entity2     = null;
            IEntity     loadedEntity;

            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "Test user " + Guid.NewGuid().ToString();
            userAccount.Save();

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

            entity1 = Entity.Create(new EntityRef(entityType));
            entity1.SetField("core:name", "A");
            entity1.Save();

            entity2 = Entity.Create(new EntityRef(entityType));
            entity2.SetField("core:name", "B");
            entity2.Save();

            if (permissionAliases.Length > 0)
            {
                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(), entityType.As <SecurableEntity>(),
                                                        permissionAliases.Split(',').Select(x => new EntityRef(x)),
                                                        TestQueries.EntitiesWithNameA().ToReport());
            }

            using (new SetUser(userAccount))
            {
                // Only check read permission, even when getting a writable version
                loadedEntity = null;
                Assert.That(() => loadedEntity = Entity.Get <IEntity>(new EntityRef(entity1), true),
                            canGetEntity
                        ? (Constraint)Is.EqualTo(entity1).Using(EntityRefComparer.Instance)
                        : (Constraint)Throws.TypeOf <PlatformSecurityException>(), "Entity 1 Get is incorrect");
                Assert.That(() => Entity.Get <IEntity>(new EntityRef(entity2), true),
                            Throws.TypeOf <PlatformSecurityException>(), "Entity 2 access failed");

                if (canGetEntity)
                {
                    // Requires modify permission
                    Assert.That(() => loadedEntity.Save(),
                                canSaveEntity
                            ? (Constraint)Throws.Nothing
                            : (Constraint)Throws.TypeOf <PlatformSecurityException>());
                }
            }
        }
示例#6
0
        public void Test_AuthorizationDeletion()
        {
            UserAccount            userAccount;
            EntityType             entityType;
            IEntity                entity;
            Authorization          authorization;
            CachingQueryRepository cachingQueryRepository;

            cachingQueryRepository = (CachingQueryRepository) new EntityAccessControlFactory().Caches.First(c => c is CachingQueryRepository);

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

            entityType = new EntityType();
            entityType.Save();

            entity = Entity.Create(entityType);
            entity.Save();

            authorization = new AccessControlHelper().AddAllowReadQuery(userAccount.As <Subject>(),
                                                                        entityType.As <SecurableEntity>(), TestQueries.GetAllEntitiesReport());

            Assert.That(cachingQueryRepository.Cache,
                        Has.Exactly(0)
                        .Property("Key").Property("SubjectId").EqualTo(userAccount.Id)
                        .And.Property("Key").Property("PermissionId").EqualTo(Permission.Read.Id)
                        .And.Property("Key").Property("EntityTypes").Contains(entityType.Id),
                        "Entry initially present in cache");

            using (new SetUser(userAccount))
            {
                Assert.That(() => Entity.Get(entity.Id), Throws.Nothing);
            }

            Assert.That(cachingQueryRepository.Cache,
                        Has.Exactly(1)
                        .Property("Key").Property("SubjectId").EqualTo(userAccount.Id)
                        .And.Property("Key").Property("PermissionId").EqualTo(Permission.Read.Id)
                        .And.Property("Key").Property("EntityTypes").Contains(entityType.Id),
                        "Entry not added to cache");

            authorization.Delete();

            Assert.That(cachingQueryRepository.Cache,
                        Has.Exactly(0)
                        .Property("Key").Property("SubjectId").EqualTo(userAccount.Id)
                        .And.Property("Key").Property("PermissionId").EqualTo(Permission.Read.Id)
                        .And.Property("Key").Property("EntityTypes").Contains(entityType.Id),
                        "Entry not removed from cache");
        }
示例#7
0
        public void TestOnChangeAccessRulePermissions()
        {
            bool          success     = true;
            string        subjectName = "Role" + Guid.NewGuid();
            string        typeName    = "Type" + Guid.NewGuid();
            string        reportName  = "Report" + Guid.NewGuid();
            var           read        = Entity.Get <Permission>("read");
            var           delete      = Entity.Get <Permission>("delete");
            ISet <string> oldPerm     = new SortedSet <string> {
                read.Name
            };
            ISet <string> newPerm = new SortedSet <string> {
                read.Name, delete.Name
            };

            var mockAuditLog = new Mock <IAuditLog>(MockBehavior.Strict);

            mockAuditLog.Setup(al => al.OnChangeAccessRulePermissions(success, subjectName, typeName, reportName, It.Is <ISet <string> >(p => oldPerm.SetEquals(p)), It.Is <ISet <string> >(p => newPerm.SetEquals(p))));

            var eventTarget = new AuditLogAccessRuleEventTarget(mockAuditLog.Object);

            var subject = new Role {
                Name = subjectName
            };
            var type = new EntityType {
                Name = typeName
            };
            var report = new Report {
                Name = reportName
            };

            var accessRule = new AccessRule {
                AllowAccessBy = subject.As <Subject>(), ControlAccess = type.As <SecurableEntity>(), AccessRuleReport = report
            };

            accessRule.PermissionAccess.Add(read);
            accessRule.Save();

            // Change permissions
            accessRule.PermissionAccess.Add(delete);

            IDictionary <string, object> state = new Dictionary <string, object>();

            eventTarget.GatherAuditLogEntityDetailsForSave(accessRule, state);
            eventTarget.WriteSaveAuditLogEntries(success, accessRule.Id, state);

            mockAuditLog.VerifyAll();
        }
示例#8
0
        public void Test_BasicSecurity()
        {
            UserAccount userAccount = null;
            EntityType  entityType  = null;
            IEntity     entity1     = null;
            IEntity     entity2     = null;

            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "GetEntitiesOfType test user " + Guid.NewGuid().ToString();
            userAccount.Save();

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

            entity1 = Entity.Create(new EntityRef(entityType));
            entity1.SetField("core:name", "A");
            entity1.Save();

            entity2 = Entity.Create(new EntityRef(entityType));
            entity2.SetField("core:name", "B");
            entity2.Save();

            new AccessRuleFactory().AddAllowReadQuery(userAccount.As <Subject>(), entityType.As <SecurableEntity>(),
                                                      TestQueries.EntitiesWithNameA().ToReport());

            // Sanity Check. Check directly to avoid any caching or side effect issue.
            IDictionary <long, bool> results = new EntityAccessControlChecker().CheckAccess(
                new[] { new EntityRef(entity1), new EntityRef(entity2) },
                new[] { Permissions.Read },
                new EntityRef(userAccount));

            Assert.That(results, Has.Exactly(1).Property("Key").EqualTo(entity1.Id).And.Property("Value").True,
                        "EntityAccessControlChecker.CheckAccess: No access to Entity ID 1");
            Assert.That(results, Has.Exactly(1).Property("Key").EqualTo(entity2.Id).And.Property("Value").False,
                        "EntityAccessControlChecker.CheckAccess: Access to Entity ID 2");

            using (new SetUser(userAccount))
            {
                IEnumerable <IEntity> entities = Entity.GetInstancesOfType(entityType, true, "name");
                Assert.That(entities.Count(), Is.EqualTo(1),
                            "Entity.GetInstancesOfType: Incorrect count");
                Assert.That(entities, Has.Exactly(1).Property("Id").EqualTo(entity1.Id),
                            "Entity.GetInstancesOfType: Incorrect Id");
            }
        }
        public void Test_GetDisplayReportForSecurableEntity_ValidSecurityQuery()
        {
            EntityType entityType;
            IAccessRuleReportFactory accessRuleReportFactory;
            Report          report;
            StructuredQuery reportStructuredQuery;

            entityType = new EntityType();
            entityType.Save();

            accessRuleReportFactory = new AccessRuleDisplayReportFactory();
            report = accessRuleReportFactory.GetDisplayReportForSecurableEntity(entityType.As <SecurableEntity>());
            reportStructuredQuery = ReportToQueryConverter.Instance.Convert(report);

            Assert.That(reportStructuredQuery, Has.Property("SelectColumns").Count.EqualTo(reportStructuredQuery.SelectColumns.Count),
                        "Select column mismatch");
            Assert.That(reportStructuredQuery.SelectColumns.Any(sc => sc.Expression is IdExpression),
                        Is.EqualTo(reportStructuredQuery.SelectColumns.Any(sc => sc.Expression is IdExpression)), "Id Expression mismatch");
        }
        public void Test_CanCreate_InheritedTypes()
        {
            EntityType  baseEntityType;
            EntityType  derivedEntityType;
            UserAccount userAccount;

            derivedEntityType      = new EntityType();
            derivedEntityType.Name = "Derived Type " + Guid.NewGuid();
            derivedEntityType.Save();

            baseEntityType      = new EntityType();
            baseEntityType.Name = "Base Type " + Guid.NewGuid();
            baseEntityType.DerivedTypes.Add(derivedEntityType);
            baseEntityType.Inherits.Add(UserResource.UserResource_Type);
            baseEntityType.Save();

            derivedEntityType = Entity.Get <EntityType>(derivedEntityType.Id);

            Assert.That(derivedEntityType.GetAncestorsAndSelf(),
                        Is.EquivalentTo(new [] { baseEntityType, derivedEntityType, UserResource.UserResource_Type, Entity.Get <EntityType>("core:resource") })
                        .Using(new EntityIdEqualityComparer <EntityType>()));
            Assert.That(derivedEntityType.IsDerivedFrom(baseEntityType),
                        Is.True, "Not derived form base type");

            userAccount      = new UserAccount();
            userAccount.Name = "Test User Account " + Guid.NewGuid();
            userAccount.Save();

            new AccessRuleFactory().AddAllowCreate(
                userAccount.As <Subject>(),
                baseEntityType.As <SecurableEntity>());

            using (new SetUser(userAccount))
            {
                Assert.That(
                    Factory.EntityAccessControlService.CanCreate(baseEntityType),
                    "Cannot create base type");
                Assert.That(
                    Factory.EntityAccessControlService.CanCreate(derivedEntityType),
                    "Cannot create derived type");
            }
        }
示例#11
0
        //[TestCase("core:modify", false)] // unsupported
        //[TestCase("core:delete", true)]  // unsupported
        //[TestCase("core:modify,core:delete", true)] // unsupported
        public void Test_Delete(string permissionAliases, bool canDeleteEntity1)
        {
            UserAccount userAccount = null;
            EntityType  entityType  = null;
            IEntity     entity1     = null;
            IEntity     entity2     = null;

            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "Test user " + Guid.NewGuid().ToString();
            userAccount.Save();

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

            entity1 = Entity.Create(new EntityRef(entityType));
            entity1.SetField("core:name", "A");
            entity1.Save();

            entity2 = Entity.Create(new EntityRef(entityType));
            entity2.SetField("core:name", "B");
            entity2.Save();

            if (permissionAliases.Length > 0)
            {
                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(), entityType.As <SecurableEntity>(),
                                                        permissionAliases.Split(',').Select(x => new EntityRef(x)),
                                                        TestQueries.EntitiesWithNameA().ToReport());
            }

            using (new SetUser(userAccount))
            {
                Assert.That(() => entity1.Delete(),
                            canDeleteEntity1
                        ? (Constraint)Throws.Nothing
                        : (Constraint)Throws.TypeOf <PlatformSecurityException>());
                Assert.That(() => Entity.Get <IEntity>(new EntityRef(entity2)),
                            Throws.TypeOf <PlatformSecurityException>(), "Entity 2 delete somehow worked");
            }
        }
示例#12
0
        public void Test_TemporaryIds(long id, bool shouldRaiseException)
        {
            UserAccount             userAccount = null;
            EntityType              entityType  = null;
            MockRepository          mockRepository;
            Mock <IEntity>          mockEntity         = null;
            Mock <IEntityInternal>  mockEntityInternal = null;
            EntityModificationToken entityModificationToken;

            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "Test user " + Guid.NewGuid().ToString();
            userAccount.Save();

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

            new AccessRuleFactory().AddAllowCreate(userAccount.As <Subject>(),
                                                   entityType.As <SecurableEntity>());

            // Mock an Entity. Yes, I am completely insane.
            mockRepository = new MockRepository(MockBehavior.Loose);
            mockEntity     = mockRepository.Create <IEntity>();
            mockEntity.SetupGet(e => e.TypeIds).Returns(() => new[] { entityType.Id });
            mockEntity.SetupGet(e => e.EntityTypes).Returns(() => new[] { entityType });
            mockEntity.Setup(e => e.IsReadOnly).Returns(() => false);
            mockEntity.SetupGet(e => e.Id).Returns(() => id);
            mockEntityInternal = mockEntity.As <IEntityInternal>();
            mockEntityInternal.SetupGet(ei => ei.IsTemporaryId).Returns(() => EntityTemporaryIdAllocator.IsAllocatedId(id));
            entityModificationToken = new EntityModificationToken();
            mockEntityInternal.SetupGet(ei => ei.ModificationToken).Returns(() => entityModificationToken);

            using (new SetUser(userAccount))
            {
                Assert.That(() => Entity.Save(new [] { mockEntity.Object }, false),
                            shouldRaiseException ? (Constraint)Throws.Nothing : Throws.TypeOf <PlatformSecurityException>());
            }
        }
示例#13
0
        public void Test_Relationship(Direction direction, string identityType, int count)
        {
            // Create schema
            EntityType type = Entity.Create <EntityType>( );

            type.Name = "Test Type";
            type.Inherits.Add(Entity.Get <EntityType>("core:resource"));
            type.Save( );
            Field      stringField = new StringField( ).As <Field>( );
            Field      intField    = new IntField( ).As <Field>( );
            EntityType type2       = Entity.Create <EntityType>( );

            type2.Name = "Test Type2";
            type2.Fields.Add(stringField);
            type2.Fields.Add(intField);
            type.Inherits.Add(Entity.Get <EntityType>("core:resource"));
            type2.Save( );
            Relationship relationship = Entity.Create <Relationship>( );

            relationship.Name             = "Rel1";
            relationship.Cardinality_Enum = CardinalityEnum_Enumeration.ManyToMany;
            relationship.FromType         = direction == Direction.Forward ? type : type2;
            relationship.ToType           = direction == Direction.Forward ? type2 : type;
            relationship.Save( );

            var targets = new List <Resource>( );

            for (int i = 0; i < count; i++)
            {
                string name      = "Target" + Guid.NewGuid( );
                string stringVal = "StringVal" + i;
                int    intVal    = 100 + i;

                Resource target = Entity.Create(type2.Id).AsWritable <Resource>( );
                target.SetField(stringField.Id, stringVal);
                target.SetField(intField.Id, intVal);
                target.Name = name;
                target.Save( );
                targets.Add(target);
            }


            using (new SecurityBypassContext( ))
            {
                new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type.Id).ToReport( ));
                new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type2.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type2.Id).ToReport( ));
            }

            Field lookupField = null;

            if (identityType.Contains("StringField"))
            {
                lookupField = stringField;
            }
            else if (identityType.Contains("IntField"))
            {
                lookupField = intField;
            }

            var identities = new List <string>( );

            for (int i = 0; i < count; i++)
            {
                var    target = targets[i];
                string identity;
                if (identityType.Contains("Null"))
                {
                    continue;
                }
                if (identityType == "Name")
                {
                    identity = "\"" + target.Name + "\"";
                }
                else if (identityType == "Guid")
                {
                    identity = "\"" + target.UpgradeId + "\"";
                }
                else if (identityType == "StringField")
                {
                    identity = "\"StringVal" + i + "\"";
                }
                else if (identityType == "IntField")
                {
                    identity = (100 + i).ToString( );
                }
                else
                {
                    throw new InvalidOperationException( );
                }
                identities.Add(identity);
            }

            // Create JSON
            string jsonMember = "rel1";
            string json       = "{\"" + jsonMember + "\":[" + string.Join(", ", identities) + "]}";

            // Create a mapping
            var mapping    = CreateApiResourceMapping(new EntityRef(type.Id));
            var relMapping = CreateApiRelationshipMapping(mapping, new EntityRef(relationship.Id), jsonMember, direction == Direction.Reverse);

            relMapping.MappedRelationshipLookupField = lookupField;
            relMapping.Save( );

            // Fill entity
            IEntity entity = RunTest(json, mapping);
            IEntityRelationshipCollection <IEntity> value = entity.GetRelationships(relationship.Id, direction);

            // Assert mapping
            Assert.That(value, Is.Not.Null);
            if (identityType == "Null")
            {
                Assert.That(value, Has.Count.EqualTo(0));
            }
            else
            {
                Assert.That(value, Has.Count.EqualTo(targets.Count));
                var actual   = value.Select(e => e.Id).OrderBy(id => id).ToList( );
                var expected = targets.Select(e => e.Id).OrderBy(id => id).ToList( );

                Assert.That(actual, Is.EquivalentTo(expected));
            }
        }
示例#14
0
        public void Test_Filter_ActionRequiresParentModifyAccess(string parentEntityPermissions, string childEntityPermissions)
        {
            SecurityActionMenuItemFilter securityActionMenuItemFilter;
            UserAccount userAccount;
            EntityType  parentEntityType;
            EntityType  childEntityType;
            IEntity     parentEntity;
            IEntity     childEntity;

            const string viewResourceActionAlias       = "console:viewResourceAction";
            const string editResourceActionAlias       = "console:editResourceAction";
            const string deleteResourceActionAlias     = "console:deleteResourceAction";
            const string addRelationshipActionAlias    = "console:addRelationshipAction";
            const string removeRelationshipActionAlias = "console:removeRelationshipAction";

            var splitParentEntityPermissions = parentEntityPermissions.Split(new[] { ',' },
                                                                             StringSplitOptions.RemoveEmptyEntries);

            var splitChildEntityPermissions = childEntityPermissions.Split(new[] { ',' },
                                                                           StringSplitOptions.RemoveEmptyEntries);


            userAccount      = new UserAccount();
            userAccount.Name = "Test user " + Guid.NewGuid();
            userAccount.Save();

            // parent
            parentEntityType = new EntityType();
            parentEntityType.Inherits.Add(UserResource.UserResource_Type);
            parentEntityType.Save();

            parentEntity = Entity.Create(new EntityRef(parentEntityType));
            parentEntity.SetField("core:name", "A"); // "A" so it will match the access rule
            parentEntity.Save();

            // related child entity
            childEntityType = new EntityType();
            childEntityType.Inherits.Add(UserResource.UserResource_Type);
            childEntityType.Save();

            childEntity = Entity.Create(new EntityRef(childEntityType));
            childEntity.SetField("core:name", "B"); // "B" so it will match the access rule
            childEntity.Save();

            // grant accesses
            // parent entity
            new AccessRuleFactory().AddAllowByQuery(
                userAccount.As <Subject>(),
                parentEntityType.As <SecurableEntity>(),
                splitParentEntityPermissions.Select(s => new EntityRef(s)),
                TestQueries.EntitiesWithNameA().ToReport());

            // child entity
            new AccessRuleFactory().AddAllowByQuery(
                userAccount.As <Subject>(),
                childEntityType.As <SecurableEntity>(),
                splitChildEntityPermissions.Select(s => new EntityRef(s)),
                TestQueries.EntitiesWithNameB().ToReport());

            // actions
            var dummyRequest = new ActionRequestExtended();
            Func <ActionRequestExtended, ActionMenuItem, ActionTargetInfo> dummyHandler = (a, i) => new ActionTargetInfo();
            var actions = new List <ActionMenuItemInfo>();

            foreach (string menuItemAlias in new[]
            {
                viewResourceActionAlias,
                editResourceActionAlias,
                addRelationshipActionAlias,
                removeRelationshipActionAlias,
                deleteResourceActionAlias,
            })
            {
                actions.Add(Entity.Get <ActionMenuItem>(menuItemAlias).ToInfo(dummyRequest, null, dummyHandler));
            }

            actions.Add(new ActionMenuItemInfo
            {
                EntityId        = childEntityType.Id,
                HtmlActionState = "createForm",
                IsNew           = true
            });

            // filter actions
            using (new SetUser(userAccount))
            {
                securityActionMenuItemFilter = new SecurityActionMenuItemFilter();
                securityActionMenuItemFilter.Filter(parentEntity.Id, new[] { childEntity.Id }, actions);
            }

            // checks
            if (splitParentEntityPermissions.Contains("core:read") && splitParentEntityPermissions.Contains("core:modify"))
            {
                Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(addRelationshipActionAlias), "Missing add relationship resource action");
                Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(removeRelationshipActionAlias), "Missing remove relationship resource action");

                // child create
                if (splitChildEntityPermissions.Contains("core:create"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("HtmlActionState").EqualTo("createForm"), "Missing create resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("HtmlActionState").EqualTo("createForm"), "Create resource action should not be available");
                }

                // child read
                if (splitChildEntityPermissions.Contains("core:read"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(viewResourceActionAlias), "Missing view resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("Alias").EqualTo(viewResourceActionAlias), "View resource action should not be available");
                }

                // child modify
                if (splitChildEntityPermissions.Contains("core:modify"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(editResourceActionAlias), "Missing edit resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("Alias").EqualTo(editResourceActionAlias), "Edit resource action should not be available");
                }

                // child delete
                if (splitChildEntityPermissions.Contains("core:delete"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(deleteResourceActionAlias), "Missing delete resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("Alias").EqualTo(deleteResourceActionAlias), "Delete resource action should not be available");
                }
            }
            else if (splitParentEntityPermissions.Contains("core:read") && !splitParentEntityPermissions.Contains("core:modify"))
            {
                Assert.That(actions, Has.None.Property("Alias").EqualTo(addRelationshipActionAlias), "Add relationship action should not be available");
                Assert.That(actions, Has.None.Property("Alias").EqualTo(removeRelationshipActionAlias), "Remove relationship action should not be available");

                // child create
                Assert.That(actions, Has.None.Property("HtmlActionState").EqualTo("createForm"), "Create resource action should not be available");

                // child read
                if (splitChildEntityPermissions.Contains("core:read"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(viewResourceActionAlias), "Missing view resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("Alias").EqualTo(viewResourceActionAlias), "View resource action should not be available");
                }

                // child modify
                if (splitChildEntityPermissions.Contains("core:modify"))
                {
                    Assert.That(actions, Has.Exactly(1).Property("Alias").EqualTo(editResourceActionAlias), "Missing edit resource action");
                }
                else
                {
                    Assert.That(actions, Has.None.Property("Alias").EqualTo(editResourceActionAlias), "Edit resource action should not be available");
                }

                // child delete
                Assert.That(actions, Has.None.Property("Alias").EqualTo(deleteResourceActionAlias), "Delete resource action should not be available");
            }
        }
示例#15
0
        private void CreateScenarioImpl(string testInstanceName, Func <EntityRef[]> permissionsCallback)
        {
            // Define key and user
            using (new TenantAdministratorContext(TenantName))
            {
                // Define schema
                type = new EntityType( );
                type.Inherits.Add(UserResource.UserResource_Type);
                type.Name = "Test type " + Guid.NewGuid( );
                type.Save( );

                type2 = new EntityType( );
                type2.Inherits.Add(UserResource.UserResource_Type);
                type2.Name = "Test type2 " + Guid.NewGuid( );
                type2.Save( );

                stringField               = new StringField( );
                stringField.Name          = "Field 1";
                stringField.FieldIsOnType = type;
                stringField.MaxLength     = 50;
                stringField.Save( );

                lookup = new Relationship( );
                lookup.Cardinality_Enum = CardinalityEnum_Enumeration.OneToOne;
                lookup.FromType         = type;
                lookup.ToType           = type2;

                relationship = new Relationship( );
                relationship.Cardinality_Enum = CardinalityEnum_Enumeration.ManyToMany;
                relationship.FromType         = type;
                relationship.ToType           = type2;

                // Define API
                mapping            = new ApiResourceMapping( );
                mapping.Name       = "Test mapping " + Guid.NewGuid( );;
                mapping.MappedType = type;
                mapping.Save( );

                fieldMapping             = new ApiFieldMapping( );
                fieldMapping.Name        = "field1";
                fieldMapping.MappedField = stringField.As <Field>( );
                fieldMapping.MemberForResourceMapping = mapping;
                fieldMapping.Save( );

                lookupMapping      = new ApiRelationshipMapping( );
                lookupMapping.Name = "lookup1";
                lookupMapping.MappedRelationship       = lookup;
                lookupMapping.MemberForResourceMapping = mapping;
                lookupMapping.Save( );

                relationshipMapping      = new ApiRelationshipMapping( );
                relationshipMapping.Name = "rel1";
                relationshipMapping.MappedRelationship       = relationship;
                relationshipMapping.MemberForResourceMapping = mapping;
                relationshipMapping.Save( );

                endpoint      = new ApiResourceEndpoint( );
                endpoint.Name = "Test endpoint " + Guid.NewGuid( );;
                endpoint.ApiEndpointAddress      = EndpointAddress;
                endpoint.EndpointResourceMapping = mapping;
                endpoint.ApiEndpointEnabled      = true;
                endpoint.EndpointCanCreate       = true;
                endpoint.EndpointCanUpdate       = true;
                endpoint.EndpointCanDelete       = true;
                endpoint.Save( );

                api            = new Api( );
                api.Name       = "Test API " + Guid.NewGuid( );;
                api.ApiAddress = ApiAddress;
                api.ApiEnabled = true;
                api.ApiEndpoints.Add(endpoint.As <ApiEndpoint>( ));
                api.Save( );

                // Define access
                userAccount      = new UserAccount( );
                userAccount.Name = "Test user " + Guid.NewGuid( );
                userAccount.AccountStatus_Enum = UserAccountStatusEnum_Enumeration.Active;
                userAccount.Password           = "******";
                userAccount.Save( );

                key      = new ApiKey( );
                key.Name = ApiKey;
                key.ApiKeyUserAccount = userAccount;
                key.ApiKeyEnabled     = true;
                key.KeyForApis.Add(api);
                key.Save( );

                if (testInstanceName != null)
                {
                    scenarioInstance = Entity.Create(type);
                    scenarioInstance.SetField("core:name", testInstanceName);
                    scenarioInstance.Save( );
                }

                foreignName     = "Foreign" + Guid.NewGuid( ).ToString( );
                foreignInstance = Entity.Create(type2);
                foreignInstance.SetField("core:name", foreignName);
                foreignInstance.Save( );

                // Grant create
                var permissions = permissionsCallback( );
                IAccessRuleFactory accessControlHelper = new AccessRuleFactory( );
                if (permissions [0] == Permissions.Create)
                {
                    accessControlHelper.AddAllowCreate(userAccount.As <Subject>( ), type.As <SecurableEntity>( ));
                }
                else if (permissions.Length > 0)
                {
                    accessControlHelper.AddAllowByQuery(userAccount.As <Subject>( ), type.As <SecurableEntity>( ), permissions, TestQueries.Entities(type).ToReport( ));
                }

                accessControlHelper.AddAllowByQuery(userAccount.As <Subject>( ), type2.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type2).ToReport( ));
            }
        }
示例#16
0
        public void Setup( )
        {
            // Getting Forbidden? Or ConnectorConfigException?
            // Maybe there's duplicate copies of these objects in the DB.

            // Define key and user
            using (new TenantAdministratorContext(TenantName))
            {
                // Define schema
                type = new EntityType( );
                type.Inherits.Add(UserResource.UserResource_Type);
                type.Name = "Test type " + Guid.NewGuid( );
                type.Save( );

                type2 = new EntityType();
                type2.Inherits.Add(UserResource.UserResource_Type);
                type2.Name = "Test type2 " + Guid.NewGuid();
                type2.Save();

                stringField               = new StringField( );
                stringField.Name          = "Field 1";
                stringField.FieldIsOnType = type;
                stringField.Save( );

                lookup = new Relationship();
                lookup.Cardinality_Enum = CardinalityEnum_Enumeration.OneToOne;
                lookup.FromType         = type;
                lookup.ToType           = type2;

                // Define API
                mapping            = new ApiResourceMapping( );
                mapping.Name       = "Test mapping " + Guid.NewGuid( );;
                mapping.MappedType = type;
                mapping.Save( );

                lookupMapping      = new ApiRelationshipMapping();
                lookupMapping.Name = "lookup1";
                lookupMapping.MappedRelationship       = lookup;
                lookupMapping.MemberForResourceMapping = mapping;
                lookupMapping.Save();

                fieldMapping             = new ApiFieldMapping( );
                fieldMapping.Name        = "field1";
                fieldMapping.MappedField = stringField.As <Field>( );
                fieldMapping.MemberForResourceMapping = mapping;
                fieldMapping.Save( );

                endpoint      = new ApiResourceEndpoint( );
                endpoint.Name = "Test endpoint " + Guid.NewGuid( );
                endpoint.ApiEndpointAddress      = EndpointAddress;
                endpoint.EndpointResourceMapping = mapping;
                endpoint.ApiEndpointEnabled      = true;
                endpoint.EndpointCanCreate       = true;
                endpoint.EndpointCanDelete       = true;
                endpoint.EndpointCanUpdate       = true;
                endpoint.Save( );

                api            = new Api( );
                api.Name       = "Test API " + Guid.NewGuid( );;
                api.ApiAddress = ApiAddress;
                api.ApiEnabled = true;
                api.ApiEndpoints.Add(endpoint.As <ApiEndpoint>( ));
                api.Save( );

                // Define access
                userAccount      = new UserAccount( );
                userAccount.Name = "Test user " + Guid.NewGuid( );
                userAccount.AccountStatus_Enum = UserAccountStatusEnum_Enumeration.Active;
                userAccount.Password           = "******";
                userAccount.Save( );

                key      = new ApiKey( );
                key.Name = ApiKey;
                key.ApiKeyUserAccount = userAccount;
                key.ApiKeyEnabled     = true;
                key.KeyForApis.Add(api);
                key.Save( );

                updateInstance             = Entity.Create(type).AsWritable <Resource>( );
                updateInstance.Name        = updateInstanceName = "ResourceToUpdate" + Guid.NewGuid( );
                updateInstance.Description = updateInstanceDesc = "ResourceToUpdate" + Guid.NewGuid( );
                updateInstance.Save( );
                updateInstanceGuid = updateInstance.UpgradeId;

                IAccessRuleFactory accessControlHelper = new AccessRuleFactory( );
                accessRule = accessControlHelper.AddAllowCreate(userAccount.As <Subject>( ), type.As <SecurableEntity>( ));
                accessRule = accessControlHelper.AddAllowByQuery(userAccount.As <Subject>( ), type.As <SecurableEntity>( ), new[] { Permissions.Read, Permissions.Modify, Permissions.Delete }, TestQueries.Entities(type).ToReport( ));
            }

            cleanup = new List <IEntity> {
                userAccount, key, api, type, mapping, endpoint, fieldMapping, stringField, accessRule, updateInstance
            };
        }
        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));
            }
        }
示例#18
0
        public void Test_Writeable_Related_Entity(string toPermissionAliases, bool toEntityWriteable)
        {
            var userAccount = Entity.Create <UserAccount>();

            userAccount.Name = "Test user " + Guid.NewGuid();
            userAccount.Save();

            var fromType = new EntityType();

            fromType.Inherits.Add(UserResource.UserResource_Type);
            fromType.Save();

            var toType = new EntityType();

            toType.Inherits.Add(UserResource.UserResource_Type);
            toType.Save();

            var relationship = new Relationship {
                FromType = fromType, ToType = toType
            };

            relationship.Save();

            IEntity fromEntity = Entity.Create(new EntityRef(fromType));

            fromEntity.SetField("core:name", "A");
            fromEntity.Save();

            IEntity toEntity = Entity.Create(new EntityRef(toType));

            toEntity.SetField("core:name", "B");
            toEntity.SetRelationships(relationship, new EntityRelationshipCollection <IEntity>()
            {
                fromEntity
            }, Direction.Reverse);
            toEntity.Save();

            // Read / modify from type
            new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(), fromType.As <SecurableEntity>(),
                                                    new List <EntityRef> {
                new EntityRef("core:read"), new EntityRef("core:modify")
            },
                                                    TestQueries.EntitiesWithNameA().ToReport());

            if (toPermissionAliases.Length > 0)
            {
                // Access to to type
                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(), toType.As <SecurableEntity>(),
                                                        toPermissionAliases.Split(',').Select(x => new EntityRef(x)),
                                                        TestQueries.EntitiesWithNameB().ToReport());
            }

            using (new SetUser(userAccount))
            {
                // The from entity should be able to be retrieved
                var fromEntityWriteable = Entity.Get <IEntity>(new EntityRef(fromEntity), true);
                Assert.AreEqual(fromEntity.Id, fromEntityWriteable.Id);

                // Check access to to entity
                IEntity entity = fromEntityWriteable.GetRelationships(relationship, Direction.Forward).FirstOrDefault( );

                IEntity toEntityFromRel = null;

                if (entity != null)
                {
                    toEntityFromRel = entity.Entity;
                }

                if (toPermissionAliases.Length > 0)
                {
                    Assert.AreEqual(toEntity.Id, toEntityFromRel.Id);
                    var toEntityWrite = toEntityFromRel.AsWritable();
                    toEntityWrite.SetField("core:description", "Test");

                    if (toEntityWriteable)
                    {
                        // Should be able to save
                        Assert.DoesNotThrow(() => toEntityWrite.Save());
                    }
                    else
                    {
                        // Should not be able to save
                        Assert.That(toEntityWrite.Save,
                                    Throws.TypeOf <PlatformSecurityException>(), "Entity access is incorrect. Should notbe able to save.");
                    }
                }
                else
                {
                    // We do not have read access to the to entity so it should be null
                    Assert.IsNull(toEntityFromRel);
                }
            }
        }
        public void Setup( )
        {
            // Getting Forbidden? Or ConnectorConfigException?
            // Maybe there's duplicate copies of these objects in the DB.

            UserAccount userAccount;
            AccessRule  accessRule;
            Api         api;

            // Define key and user
            using (new TenantAdministratorContext(TenantName))
            {
                // Create Type
                type = new EntityType
                {
                    Fields =
                    {
                        new StringField {
                            Name = "Incident Description"
                        }.As <Field>( )
                    }
                };
                type.Inherits.Add(UserResource.UserResource_Type);
                type.Save( );

                // Define access
                userAccount = new UserAccount
                {
                    Name = "Test user " + Guid.NewGuid( ),
                    AccountStatus_Enum = UserAccountStatusEnum_Enumeration.Active,
                    Password           = "******"
                };
                userAccount.Save( );

                var field = type.Fields [0];

                // Create import config
                importConfig = new ImportConfig
                {
                    Name = "Test import config " + Guid.NewGuid( ),
                    ImportFileType_Enum = ImportFileTypeEnum_Enumeration.ImportFileTypeExcel,
                    ImportConfigMapping = new ApiResourceMapping
                    {
                        MappingSourceReference = "Incident",
                        ImportHeadingRow       = 4,
                        ImportDataRow          = 5,
                        MappedType             = type,
                        ResourceMemberMappings =
                        {
                            new ApiFieldMapping {
                                Name = "A", MappedField = Resource.Name_Field.As <Field>( ),
                            }.As <ApiMemberMapping>( ),
                            new ApiFieldMapping {
                                Name = "B", MappedField = field
                            }.As <ApiMemberMapping>( )
                        }
                    }
                };

                // Create API
                api = new Api
                {
                    Name         = "Test API " + Guid.NewGuid( ),
                    ApiAddress   = ApiAddress,
                    ApiEnabled   = true,
                    ApiEndpoints =
                    {
                        new ApiSpreadsheetEndpoint
                        {
                            Name = "Test spreadsheet endpoint " + Guid.NewGuid( ),
                            ApiEndpointAddress   = EndpointAddress,
                            ApiEndpointEnabled   = true,
                            EndpointImportConfig = importConfig
                        }.As <ApiEndpoint>( )
                    },
                    ApiKeys =
                    {
                        new ApiKey
                        {
                            Name = ApiKey,
                            ApiKeyUserAccount = userAccount,
                            ApiKeyEnabled     = true
                        }
                    }
                };
                api.Save( );

                IAccessRuleFactory accessControlHelper = new AccessRuleFactory( );
                accessRule = accessControlHelper.AddAllowCreate(userAccount.As <Subject>( ), type.As <SecurableEntity>( ));
                //accessRule2 = accessControlHelper.AddAllowByQuery( userAccount.As<Subject>( ), type.As<SecurableEntity>( ), new [ ] { Permissions.Read, Permissions.Modify }, TestQueries.Entities( type ).ToReport( ) );


                IEntity apiKey = api.ApiKeys? [0];

                cleanup = new List <IEntity> {
                    userAccount, api, type, accessRule, importConfig, apiKey
                };
            }
        }
示例#20
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");
            }
        }
示例#21
0
        public void Test_Lookup_NotFound( )
        {
            // Create schema
            EntityType type = Entity.Create <EntityType>( );

            type.Name = "Test Type";
            type.Inherits.Add(Entity.Get <EntityType>("core:resource"));
            type.Save( );
            EntityType type2 = Entity.Create <EntityType>( );

            type2.Name = "Test Type2";
            type.Inherits.Add(Entity.Get <EntityType>("core:resource"));
            type2.Save( );
            Relationship relationship = Entity.Create <Relationship>( );

            relationship.Name             = "Rel1";
            relationship.Cardinality_Enum = CardinalityEnum_Enumeration.OneToOne;
            relationship.FromType         = type;
            relationship.ToType           = type2;
            relationship.Save( );

            using (new SecurityBypassContext( ))
            {
                new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type.Id).ToReport( ));
                new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type2.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type2.Id).ToReport( ));
            }

            string identity = "I dont exist";

            // Create JSON
            string jsonMember = "rel1";
            string json       = "{\"" + jsonMember + "\":\"" + identity + "\"}";

            // Create a mapping
            var mapping = CreateApiResourceMapping(new EntityRef(type.Id));

            CreateApiRelationshipMapping(mapping, new EntityRef(relationship.Id), jsonMember, false);

            // Attempt to fill entity
            Assert.Throws <ConnectorRequestException>(() => RunTest(json, mapping), "E1003 No resources were found that matched 'I dont exist'.");
        }
示例#22
0
        public void Test_Lookup(Direction direction, string identityType)
        {
            string name = "Target" + Guid.NewGuid();

            // Create schema
            EntityType type = Entity.Create <EntityType>( );

            type.Name = "Test Type";
            type.Inherits.Add(Entity.Get <EntityType>("core:resource"));
            type.Save( );
            Field      stringField = new StringField( ).As <Field>( );
            Field      intField    = new IntField( ).As <Field>( );
            EntityType type2       = Entity.Create <EntityType>( );

            type2.Fields.Add(stringField);
            type2.Fields.Add(intField);
            type2.Name = "Test Type2";
            type.Inherits.Add(Entity.Get <EntityType>("core:resource"));
            type2.Save( );
            Relationship relationship = Entity.Create <Relationship>( );

            relationship.Name             = "Rel1";
            relationship.Cardinality_Enum = CardinalityEnum_Enumeration.OneToOne;
            relationship.FromType         = direction == Direction.Forward ? type : type2;
            relationship.ToType           = direction == Direction.Forward ? type2 : type;
            relationship.Save( );
            Resource target = Entity.Create(type2.Id).AsWritable <Resource>();

            target.Name = name;
            target.SetField(stringField.Id, "StringVal");
            target.SetField(intField.Id, 101);
            target.Save( );

            using (new SecurityBypassContext( ))
            {
                new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type.Id).ToReport( ));
                new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type2.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type2.Id).ToReport( ));
            }

            Field lookupField = null;

            string identity;

            if (identityType == "Name")
            {
                identity = "\"" + name + "\"";
            }
            else if (identityType == "Guid")
            {
                identity = "\"" + target.UpgradeId.ToString() + "\"";
            }
            else if (identityType.Contains("Null"))
            {
                identity = "null";
            }
            else if (identityType == "StringField")
            {
                identity = "\"StringVal\"";
            }
            else if (identityType == "IntField")
            {
                identity = "101";
            }
            else
            {
                throw new InvalidOperationException();
            }

            if (identityType.Contains("StringField"))
            {
                lookupField = stringField;
            }
            else if (identityType.Contains("IntField"))
            {
                lookupField = intField;
            }

            // Create JSON
            string jsonMember = "rel1";
            string json       = "{\"" + jsonMember + "\":" + identity + "}";

            // Create a mapping
            var mapping    = CreateApiResourceMapping(new EntityRef(type.Id));
            var relMapping = CreateApiRelationshipMapping(mapping, new EntityRef(relationship.Id), jsonMember, direction == Direction.Reverse);

            relMapping.MappedRelationshipLookupField = lookupField;
            relMapping.Save( );

            // Fill entity
            IEntity entity = RunTest(json, mapping);
            IEntityRelationshipCollection <IEntity> value = entity.GetRelationships(relationship.Id, direction);

            // Assert mapping
            Assert.That(value, Is.Not.Null);
            if (identityType.Contains("Null"))
            {
                Assert.That(value, Has.Count.EqualTo(0));
            }
            else
            {
                Assert.That(value, Has.Count.EqualTo(1));
                Assert.That(value.First( ).Id, Is.EqualTo(target.Id));
            }
        }
        public void Test_GetImplicitRelated(string instructions, bool expectReturned)
        {
            if (_runner == "EntityInfoService")
            {
                Assert.Ignore();
            }

            bool securesTo   = instructions.Contains("securesTo");
            bool securesFrom = instructions.Contains("securesFrom");
            bool isReverse   = instructions.Contains("reverse");

            UserAccount  userAccount;
            EntityType   entityType;
            Relationship relationship;
            IEntity      entity;
            IEntity      relatedEntity;

            // Create user
            userAccount      = Entity.Create <UserAccount>();
            userAccount.Name = "Test user " + Guid.NewGuid();
            userAccount.Save();

            // Create type (used for both ends)
            entityType = new EntityType();
            entityType.Inherits.Add(UserResource.UserResource_Type);
            entityType.Save();

            // Create relationship
            relationship = new Relationship();
            relationship.Cardinality_Enum = CardinalityEnum_Enumeration.ManyToMany;
            relationship.FromType         = entityType;
            relationship.ToType           = entityType;
            relationship.SecuresTo        = securesTo;
            relationship.SecuresFrom      = securesFrom;
            relationship.Save();

            // Create related entity (the one that may or may not be visible)
            relatedEntity = Entity.Create(new EntityRef(entityType));
            relatedEntity.SetField("core:name", "B"); // "B" so it does not match the access rule
            relatedEntity.Save();

            // Create initial entity (the one that will be explicitly granted permissions, and queried)
            entity = Entity.Create(new EntityRef(entityType));
            entity.SetField("core:name", "A"); // "A" so it will match the access rule
            var relInstances = entity.GetRelationships(relationship.Id, isReverse ? Direction.Reverse : Direction.Forward);

            relInstances.Add(relatedEntity);
            entity.SetRelationships(relationship.Id, relInstances, isReverse ? Direction.Reverse : Direction.Forward);
            entity.Save();

            // Grant access to initial entity
            new AccessRuleFactory().AddAllowReadQuery(userAccount.As <Subject>(),
                                                      entityType.As <SecurableEntity>(),
                                                      TestQueries.EntitiesWithNameA().ToReport());

            // Build request
            string query = string.Format("name,{0}#{1}.name", isReverse ? "-" : "", relationship.Id);
            EntityMemberRequest request = EntityRequestHelper.BuildRequest(query);
            var svc = GetService();

            // Run request
            EntityData result;

            using (new SetUser(userAccount))
            {
                result = svc.GetEntityData(new EntityRef(entity.Id), request);
            }

            // Check results
            Assert.That(result, Is.Not.Null);
            Assert.That(result.Relationships, Has.Exactly(1).Not.Null);
            if (expectReturned)
            {
                Assert.That(result.Relationships[0].Instances, Has.Exactly(1).Not.Null);
                Assert.That(result.Relationships[0].Instances[0].Entity.Id.Id, Is.EqualTo(relatedEntity.Id));
            }
            else
            {
                Assert.That(result.Relationships[0].Instances, Is.Empty);
            }
        }