public void Test_CheckTypeAccess_WithAccess( )
        {
            IList <EntityType> entityTypes;
            UserAccount        userAccount;
            const int          numEntities = 2;

            entityTypes = new List <EntityType>();
            for (int i = 0; i < numEntities; i++)
            {
                EntityType entityType;

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

                entityTypes.Add(entityType);
            }

            userAccount = new UserAccount();
            userAccount.Save();

            Assert.That(new EntityAccessControlChecker().CheckTypeAccess(entityTypes, Permissions.Create, userAccount),
                        Is.EquivalentTo(entityTypes.ToDictionary(et => et.Id, et => false)));

            new AccessRuleFactory().AddAllowCreate(userAccount.As <Subject>(),
                                                   entityTypes[0].As <SecurableEntity>());
            new AccessRuleFactory().AddAllowCreate(userAccount.As <Subject>(),
                                                   entityTypes[1].As <SecurableEntity>());

            Assert.That(new EntityAccessControlChecker().CheckTypeAccess(entityTypes, Permissions.Create, userAccount),
                        Is.EquivalentTo(entityTypes.ToDictionary(et => et.Id, et => true)));
        }
Exemple #2
0
        public void Test_SimpleReport()
        {
            UserAccount userAccount = null;
            EntityType  reportType;
            EntityType  conditionalFormatIcon;

            ReadiNow.Model.Report report;
            HttpWebResponse       response;

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

                reportType            = Entity.Get <EntityType>("core:report");
                conditionalFormatIcon = Entity.Get <EntityType>("core:conditionalFormatIcon");

                report = Entity.Get <ReadiNow.Model.Report>("k:reportsReport");
                Assert.That(report, Is.Not.Null, "Test report not found");
                Assert.That(report, Has.Property("RootNode").Not.Null, "Test report not converted");

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

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

                // Sanity check
                using (new SetUser(userAccount))
                {
                    IDictionary <long, bool> checkResult = Factory.EntityAccessControlService.Check(
                        new[] { new EntityRef(report), },
                        new[] { Permissions.Read });

                    Assert.That(checkResult, Has.Exactly(1).Property("Key").EqualTo(report.Id).And.Property("Value").True);
                }

                // Load the first row of the report
                using (var request = new PlatformHttpRequest(@"data/v1/report/" + report.Id + "?page=0,1", PlatformHttpMethod.Get, userAccount))
                {
                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(HttpStatusCode.OK),
                                "Web service call failed");
                }
            }
            finally
            {
                if (userAccount != null)
                {
                    // Will cascade delete and remove the access rule
                    try { userAccount.Delete(); }
                    catch (Exception) { }
                }
            }
        }
Exemple #3
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) })));
            }
        }
Exemple #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 (!?)");
            }
        }
Exemple #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>());
                }
            }
        }
Exemple #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");
        }
Exemple #7
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 virtual void TestFixtureSetup()
        {
            EntityType entityType;

            try
            {
                DatabaseContext = DatabaseContext.GetContext(true);

                RunAsDefaultTenant = new RunAsDefaultTenant();
                RunAsDefaultTenant.BeforeTest(null);

                entityType = EDC.ReadiNow.Model.Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();

                Entities = CreateEntities(entityType, MatchingName);

                // Ensure the results are ordered
                Query = TestQueries.Entities(entityType);
                Query.OrderBy.Add(new OrderByItem()
                {
                    Expression = new ColumnReference()
                    {
                        ColumnId = Query.SelectColumns[0].ColumnId
                    },
                    Direction = OrderByDirection.Ascending
                });

                UserAccount = new UserAccount();
                UserAccount.Save();

                new AccessRuleFactory().AddAllowReadQuery(UserAccount.As <Subject>(), entityType.As <SecurableEntity>(),
                                                          TestQueries.EntitiesWithNameA(entityType).ToReport());
            }
            catch (Exception ex)
            {
                Console.Error.WriteLine("Setup failed: " + ex);
                if (DatabaseContext != null)
                {
                    DatabaseContext.Dispose();
                }
                throw;
            }
        }
Exemple #9
0
        public void RelationshipSaveProblemDemo2( )
        {
            using (DatabaseContext.GetContext(true))
            {
                var u1 = new UserAccount( );
                var u3 = new UserAccount( );


                // Failing version
                u1.SecurityOwnerOf.Add(u3.As <Resource>( ));
                u3.SecurityOwnerOf.Add(u1.As <Resource>( ));

                // Working version
                //u3.SecurityOwner = u1;
                //u1.SecurityOwner = u3;

                //u1.Save( );
            }
        }
        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");
            }
        }
Exemple #11
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()
                );
        }
Exemple #12
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");
            }
        }
Exemple #13
0
        public void SetUp()
        {
            _ratAttrib = new RunAsDefaultTenant();          // Explicitly calling the RunAsDefaultTenant attribute so that we can set up some common objects to speed up the test.

            _ratAttrib.BeforeTest(null);

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


            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Workflow.Workflow_Type.As <SecurableEntity>(),
                Permissions.Read.ToEnumerable(),
                TestQueries.WorkflowWithName("A").ToReport());

            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Resource.Resource_Type.As <SecurableEntity>(),
                new EntityRef("core:read").ToEnumerable(),
                TestQueries.EntitiesWithName("Readable").ToReport());

            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Resource.Resource_Type.As <SecurableEntity>(),
                new EntityRef("core:modify").ToEnumerable(),
                TestQueries.EntitiesWithName("Writable").ToReport());

            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Resource.Resource_Type.As <SecurableEntity>(),
                new EntityRef("core:create").ToEnumerable(),
                TestQueries.EntitiesWithName("Creatable").ToReport());

            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Resource.Resource_Type.As <SecurableEntity>(),
                new EntityRef("core:delete").ToEnumerable(),
                TestQueries.EntitiesWithName("Deletable").ToReport());

            new AccessRuleFactory().AddAllowByQuery(
                _userAccount.As <Subject>(),
                Resource.Resource_Type.As <SecurableEntity>(),
                new EntityRef("core:read").ToEnumerable(),
                TestQueries.EntitiesWithName("Deletable").ToReport());
        }
Exemple #14
0
        public void TestNewTemporaryEntityMasterIndex( )
        {
            using (DatabaseContext.GetContext(true))
            {
                var u1 = new UserAccount( );
                var u2 = new UserAccount( );

                long u1Id = u1.Id;
                long u2Id = u2.Id;

                u1.SecurityOwnerOf.Add(u2.As <Resource>( ));
                u2.SecurityOwnerOf.Add(u1.As <Resource>( ));

                u1.Save( );
                u2.Save( );

                Assert.AreNotEqual(u1.Id, u1Id);
                Assert.AreNotEqual(u2.Id, u2Id);
                Assert.IsTrue(u2.SecurityOwnerOf.Any(r => r.Id == u1.Id));
                Assert.IsTrue(u1.SecurityOwnerOf.Any(r => r.Id == u2.Id));
            }
        }
Exemple #15
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>());
            }
        }
Exemple #16
0
        public void Test_AddingRuleDirectToUser( )
        {
            EntityType           entityType;
            UserAccount          userAccount;
            Role                 role1;
            IUserRuleSetProvider userRuleSetProvider;
            UserRuleSet          userRuleSet1;

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

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

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


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

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

                // Add a new role
                new AccessRuleFactory( ).AddAllowReadQuery(userAccount.As <Subject>( ), entityType.As <SecurableEntity>( ), TestQueries.Entities(entityType).ToReport( ));

                ctx.CommitTransaction();
            }

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

            Assert.That(userRuleSet1, Is.Not.EqualTo(userRuleSet2));
        }
Exemple #17
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");
            }
        }
Exemple #18
0
        public void Test_Post(string entityPermissions, bool expectEntity)
        {
            EntityType      entityType;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity;

            string[]             splitEntityPermissions;
            ReportDataDefinition result;

            splitEntityPermissions = entityPermissions.Split(new[] { ',' },
                                                             StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

                entity = Entity.Create(entityType);
                entity.SetField("core:name", "A");
                entity.Save();
                entitiesToDelete.Add(entity.Id);

                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(),
                                                        entityType.As <SecurableEntity>(),
                                                        splitEntityPermissions.Select(s => new EntityRef(s)),
                                                        TestQueries.Entities().ToReport());

                using (var request = new PlatformHttpRequest(@"data/v1/entity/query", PlatformHttpMethod.Post, userAccount))
                {
                    request.PopulateBody(new JsonStructuredQuery
                    {
                        Root = new JsonEntityInQuery
                        {
                            Id = entityType.Id.ToString(CultureInfo.InvariantCulture)
                        }
                    });

                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(HttpStatusCode.OK),
                                "Web service call failed");
                    result = request.DeserialiseResponseBody <ReportDataDefinition>();
                    if (expectEntity)
                    {
                        Assert.That(result.ReportDataRows, Has.Count.EqualTo(1));
                        Assert.That(result.ReportDataRows, Has.Exactly(1).Property("Id").EqualTo(entity.Id));
                    }
                    else
                    {
                        Assert.That(result.ReportDataRows, Is.Empty);
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
Exemple #19
0
        public void Test_Get(string entityPermissions, HttpStatusCode expectedResult)
        {
            EntityType      entityType;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity;

            string[]              splitEntityPermissions;
            const string          initialName = "foo";
            JsonEntityQueryResult jsonEntityQueryResult;

            splitEntityPermissions = entityPermissions.Split(new[] { ',' },
                                                             StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

                entity = Entity.Create(entityType);
                entity.SetField("core:name", initialName);
                entity.Save();
                entitiesToDelete.Add(entity.Id);

                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(),
                                                        entityType.As <SecurableEntity>(),
                                                        splitEntityPermissions.Select(s => new EntityRef(s)),
                                                        TestQueries.Entities().ToReport());

                using (var request = new PlatformHttpRequest(string.Format(@"data/v1/entity/{0}?request=name", entity.Id),
                                                             PlatformHttpMethod.Get, userAccount))
                {
                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(expectedResult),
                                "Web service call failed");
                    jsonEntityQueryResult = request.DeserialiseResponseBody <JsonEntityQueryResult>();
                    if (expectedResult == HttpStatusCode.OK)
                    {
                        Assert.That(jsonEntityQueryResult.Ids, Is.EquivalentTo(new long[] { entity.Id }));
                    }
                    else
                    {
                        Assert.That(jsonEntityQueryResult.Ids, Is.Null);
                        Assert.That(jsonEntityQueryResult.Entities, Is.Empty);
                        Assert.That(jsonEntityQueryResult.EntityRefs, Is.Empty);
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
Exemple #20
0
        public void Test_Clone(string entityPermissions, string entityTypePermissions, HttpStatusCode expectedResult)
        {
            EntityType      entityType;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity;
            IEntity         clonedEntity;

            string[]     splitEntityPermissions;
            string[]     splitEntityTypePermissions;
            const string initialName = "foo";
            const string newName     = "bar";
            long         cloneId;

            splitEntityPermissions = entityPermissions.Split(new[] { ',' },
                                                             StringSplitOptions.RemoveEmptyEntries);
            splitEntityTypePermissions = entityTypePermissions.Split(new[] { ',' },
                                                                     StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

                entity = Entity.Create(entityType);
                entity.SetField("core:name", initialName);
                entity.Save();
                entitiesToDelete.Add(entity.Id);

                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(),
                                                        entityType.As <SecurableEntity>(),
                                                        splitEntityPermissions.Select(s => new EntityRef(s)),
                                                        TestQueries.Entities().ToReport());
                new AccessRuleFactory().AddAllow(userAccount.As <Subject>(),
                                                 splitEntityTypePermissions.Select(s => new EntityRef(s)),
                                                 entityType.As <SecurableEntity>());

                using (var request = new PlatformHttpRequest(@"data/v1/entity/clone", PlatformHttpMethod.Post, userAccount))
                {
                    request.PopulateBody(new EntityCloneRequest
                    {
                        Id   = new JsonEntityRef(new EntityRef(entity)),
                        Name = newName
                    });

                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(expectedResult),
                                "Web service call failed");
                    if (expectedResult == HttpStatusCode.OK)
                    {
                        cloneId = request.DeserialiseResponseBody <long>();
                        entitiesToDelete.Add(cloneId);

                        clonedEntity = Entity.Get(cloneId);
                        Assert.That(clonedEntity, Is.Not.Null, "Entity not found");
                        Assert.That(clonedEntity.GetField("core:name"), Is.EqualTo(newName), "Name incorrect");
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
Exemple #21
0
        public void Test_Delete(string permissions, HttpStatusCode expectedResult)
        {
            EntityType      entityType;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity;
            IEntity         modifiedEntity;

            string[] splitPermissions;

            splitPermissions = permissions.Split(new[] { ',' },
                                                 StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

                entity = Entity.Create(entityType);
                entity.Save();
                entitiesToDelete.Add(entity.Id);

                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(),
                                                        entityType.As <SecurableEntity>(),
                                                        splitPermissions.Select(s => new EntityRef(s)),
                                                        TestQueries.Entities().ToReport());

                using (var request = new PlatformHttpRequest(@"data/v1/entity?id=" + entity.Id, PlatformHttpMethod.Delete, userAccount))
                {
                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(expectedResult), "Web service call failed");

                    if (expectedResult != HttpStatusCode.OK)
                    {
                        return;
                    }

                    EntityCache.Instance.Remove(entity.Id);
                    modifiedEntity = Entity.Get(entity.Id);
                    Assert.That(modifiedEntity, Is.Null, "Entity not deleted");
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
Exemple #22
0
        public void Test_ModifyRelationship(string entity1Permissions,
                                            string entity2Permissions, bool forward, HttpStatusCode expectedResult)
        {
            EntityType      entityType1;
            EntityType      entityType2;
            Relationship    relationship;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity1;
            IEntity         entity2;
            long            newId;
            IEntity         newEntity;

            string[] splitEntity1Permissions;
            string[] splitEntity2Permissions;

            splitEntity1Permissions = entity1Permissions.Split(new[] { ',' },
                                                               StringSplitOptions.RemoveEmptyEntries);
            splitEntity2Permissions = entity2Permissions.Split(new[] { ',' },
                                                               StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType1 = Entity.Create <EntityType>();
                entityType1.Inherits.Add(UserResource.UserResource_Type);
                entityType1.Save();
                entitiesToDelete.Add(entityType1.Id);

                entity1 = Entity.Create(entityType1);
                entity1.Save();
                entitiesToDelete.Add(entity1.Id);

                entityType2 = Entity.Create <EntityType>();
                entityType2.Inherits.Add(UserResource.UserResource_Type);
                entityType2.Save();
                entitiesToDelete.Add(entityType2.Id);

                entity2 = Entity.Create(entityType2);
                entity2.Save();
                entitiesToDelete.Add(entity2.Id);

                relationship          = Entity.Create <Relationship>();
                relationship.FromType = entityType1;
                relationship.ToType   = entityType2;
                relationship.RelType  = Entity.Get <RelTypeEnum>("core:relManyToMany");
                relationship.Save();
                entitiesToDelete.Add(relationship.Id);

                new AccessRuleFactory().AddAllowByQuery(
                    userAccount.As <Subject>(),
                    entityType1.As <SecurableEntity>(),
                    splitEntity1Permissions.Select(p => new EntityRef(p)),
                    TestQueries.Entities().ToReport());
                new AccessRuleFactory().AddAllowByQuery(
                    userAccount.As <Subject>(),
                    entityType2.As <SecurableEntity>(),
                    splitEntity2Permissions.Select(p => new EntityRef(p)),
                    TestQueries.Entities().ToReport());

                using (var request = new PlatformHttpRequest(@"data/v1/entity", PlatformHttpMethod.Post, userAccount))
                {
                    request.PopulateBody(new JsonEntityQueryResult
                    {
                        Ids = new List <long> {
                            entity1.Id
                        },
                        Entities = new List <JsonEntity>
                        {
                            new JsonEntity
                            {
                                Id      = entity1.Id,
                                TypeIds = new List <long> {
                                    entityType1.Id
                                },
                                Fields        = new List <JsonFieldData>(),
                                Relationships = new List <JsonRelationshipData>
                                {
                                    new JsonRelationshipData
                                    {
                                        RelTypeId = new JsonEntityRef(relationship),
                                        Instances = new List <JsonRelationshipInstanceData>
                                        {
                                            new JsonRelationshipInstanceData
                                            {
                                                Entity    = entity2.Id,
                                                RelEntity = 0,
                                                DataState = DataState.Create
                                            }
                                        },
                                        IsReverse = !forward
                                    }
                                },
                                DataState = DataState.Create
                            }
                        },
                        EntityRefs = new List <JsonEntityRef>
                        {
                            new JsonEntityRef(new EntityRef(entity1)),
                            new JsonEntityRef(new EntityRef(entity2)),
                            new JsonEntityRef(new EntityRef(entityType1)),
                            new JsonEntityRef(new EntityRef(entityType2)),
                            new JsonEntityRef(new EntityRef(relationship))
                        }
                    });

                    response = request.GetResponse();
                    Assert.That(response, Has.Property("StatusCode").EqualTo(expectedResult),
                                "Web service call failed");

                    if (expectedResult == HttpStatusCode.OK)
                    {
                        newId = request.DeserialiseResponseBody <long>();
                        entitiesToDelete.Add(newId);

                        newEntity = Entity.Get(newId);
                        Assert.That(newEntity, Is.Not.Null, "New entity does not exist");
                        Assert.That(newEntity, Has.Property("TypeIds").Contains(entityType1.Id),
                                    "New entity missing correct type");
                        if (forward)
                        {
                            Assert.That(newEntity.GetRelationships(relationship), Has.Count.EqualTo(1),
                                        "Relationship count incorrect");
                        }
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
Exemple #23
0
        public void Test_SimpleCreate(bool allowCreate)
        {
            EntityType      entityType;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            long            id = EntityId.Max;
            long            newId;
            IEntity         newEntity;

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

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

                    // Sanity Check.
                    using (new SetUser(userAccount))
                    {
                        Assert.That(Factory.EntityAccessControlService.CanCreate(entityType), Is.True,
                                    "User cannot create type");
                    }
                }

                // Actual test
                using (var request = new PlatformHttpRequest(@"data/v1/entity", PlatformHttpMethod.Post, userAccount))
                {
                    request.PopulateBody(new JsonEntityQueryResult
                    {
                        Ids = new List <long> {
                            id
                        },
                        Entities = new List <JsonEntity>
                        {
                            new JsonEntity
                            {
                                Id      = id,
                                TypeIds = new List <long> {
                                    entityType.Id
                                },
                                Fields        = new List <JsonFieldData>(),
                                Relationships = new List <JsonRelationshipData>(),
                                DataState     = DataState.Create
                            }
                        },
                        EntityRefs = new List <JsonEntityRef>
                        {
                            new JsonEntityRef(new EntityRef(id)),
                            new JsonEntityRef(new EntityRef(entityType))
                        }
                    });

                    response = request.GetResponse();

                    if (allowCreate)
                    {
                        Assert.That(response, Has.Property("StatusCode").EqualTo(HttpStatusCode.OK),
                                    "Web service call failed");

                        newId = request.DeserialiseResponseBody <long>();
                        entitiesToDelete.Add(newId);

                        newEntity = Entity.Get(newId);
                        Assert.That(newEntity, Is.Not.Null, "New entity does not exist");
                        Assert.That(newEntity, Has.Property("TypeIds").Contains(entityType.Id),
                                    "New entity missing correct type");
                    }
                    else
                    {
                        Assert.That(response, Has.Property("StatusCode").EqualTo(HttpStatusCode.Forbidden),
                                    "Web service call failed");
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
Exemple #24
0
        public void Test_CreateWithRelationship(bool allowCreateEntity1, bool allowReadEntityType2)
        {
            EntityType      entityType1;
            EntityType      entityType2;
            Relationship    relationship;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            long            entity1Id = EntityId.Max;
            IEntity         entity2;
            long            newId;
            IEntity         newEntity;

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                entityType1 = Entity.Create <EntityType>();
                entityType1.Inherits.Add(UserResource.UserResource_Type);
                entityType1.Save();
                entitiesToDelete.Add(entityType1.Id);

                entityType2 = Entity.Create <EntityType>();
                entityType2.Inherits.Add(UserResource.UserResource_Type);
                entityType2.Save();
                entitiesToDelete.Add(entityType2.Id);

                entity2 = Entity.Create(entityType2);
                entity2.Save();
                entitiesToDelete.Add(entity2.Id);

                relationship          = Entity.Create <Relationship>();
                relationship.FromType = entityType1;
                relationship.ToType   = entityType2;
                relationship.RelType  = Entity.Get <RelTypeEnum>("core:relManyToMany");
                relationship.Save();
                entitiesToDelete.Add(relationship.Id);

                if (allowCreateEntity1)
                {
                    new AccessRuleFactory().AddAllowCreate(userAccount.As <Subject>(),
                                                           entityType1.As <SecurableEntity>());
                }
                if (allowReadEntityType2)
                {
                    new AccessRuleFactory().AddAllowReadQuery(userAccount.As <Subject>(),
                                                              entityType2.As <SecurableEntity>(), TestQueries.Entities().ToReport());
                }

                using (var request = new PlatformHttpRequest(@"data/v1/entity", PlatformHttpMethod.Post, userAccount))
                {
                    request.PopulateBody(new JsonEntityQueryResult
                    {
                        Ids = new List <long> {
                            entity1Id
                        },
                        Entities = new List <JsonEntity>
                        {
                            new JsonEntity
                            {
                                Id      = entity1Id,
                                TypeIds = new List <long> {
                                    entityType1.Id
                                },
                                Fields        = new List <JsonFieldData>(),
                                Relationships = new List <JsonRelationshipData>
                                {
                                    new JsonRelationshipData
                                    {
                                        RelTypeId = new JsonEntityRef(relationship),
                                        Instances = new List <JsonRelationshipInstanceData>
                                        {
                                            new JsonRelationshipInstanceData
                                            {
                                                Entity    = entity2.Id,
                                                RelEntity = 0,
                                                DataState = DataState.Create
                                            }
                                        }
                                    }
                                },
                                DataState = DataState.Create
                            }
                        },
                        EntityRefs = new List <JsonEntityRef>
                        {
                            new JsonEntityRef(new EntityRef(entity1Id)),
                            new JsonEntityRef(new EntityRef(entity2.Id)),
                            new JsonEntityRef(new EntityRef(entityType1)),
                            new JsonEntityRef(new EntityRef(entityType2)),
                            new JsonEntityRef(new EntityRef(relationship))
                        }
                    });

                    response = request.GetResponse();

                    if (allowCreateEntity1 && allowReadEntityType2)
                    {
                        Assert.That(response, Has.Property("StatusCode").EqualTo(HttpStatusCode.OK),
                                    "Web service call failed");

                        newId = request.DeserialiseResponseBody <long>();
                        entitiesToDelete.Add(newId);

                        newEntity = Entity.Get(newId);
                        Assert.That(newEntity, Is.Not.Null, "New entity does not exist");
                        Assert.That(newEntity, Has.Property("TypeIds").Contains(entityType1.Id),
                                    "New entity missing correct type");
                        Assert.That(newEntity.GetRelationships(relationship), Has.Count.EqualTo(1),
                                    "Relationship count incorrect");
                    }
                    else
                    {
                        Assert.That(response, Has.Property("StatusCode").EqualTo(HttpStatusCode.Forbidden),
                                    "Web service call failed");
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
Exemple #25
0
        public void Test_CreateWithField()
        {
            EntityType      entityType;
            StringField     field;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            long            id = EntityId.Max;
            long            newId;
            IEntity         newEntity;
            const string    fieldValue = "foo";

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                field      = Entity.Create <StringField>();
                field.Name = "Test field " + Guid.NewGuid();
                field.Save();
                entitiesToDelete.Add(field.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Fields.Add(field.As <Field>());
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

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

                using (var request = new PlatformHttpRequest(@"data/v1/entity", PlatformHttpMethod.Post, userAccount))
                {
                    request.PopulateBody(new JsonEntityQueryResult
                    {
                        Ids = new List <long> {
                            id
                        },
                        Entities = new List <JsonEntity>
                        {
                            new JsonEntity
                            {
                                Id      = id,
                                TypeIds = new List <long> {
                                    entityType.Id
                                },
                                Fields = new List <JsonFieldData>
                                {
                                    new JsonFieldData
                                    {
                                        FieldId  = field.Id,
                                        Value    = fieldValue,
                                        TypeName = "String"
                                    }
                                },
                                Relationships = new List <JsonRelationshipData>(),
                                DataState     = DataState.Create
                            }
                        },
                        EntityRefs = new List <JsonEntityRef>
                        {
                            new JsonEntityRef(new EntityRef(id)),
                            new JsonEntityRef(new EntityRef(entityType)),
                            new JsonEntityRef(new EntityRef(field))
                        }
                    });

                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(HttpStatusCode.OK),
                                "Web service call failed");

                    newId = request.DeserialiseResponseBody <long>();
                    entitiesToDelete.Add(newId);

                    newEntity = Entity.Get(newId);
                    Assert.That(newEntity, Is.Not.Null, "New entity does not exist");
                    Assert.That(newEntity, Has.Property("TypeIds").Contains(entityType.Id),
                                "New entity missing correct type");
                    Assert.That(newEntity.GetField(field), Is.EqualTo(fieldValue),
                                "Field value incorrect");
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
Exemple #26
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 #28
0
        public void Test_ModifyField(string permissions, HttpStatusCode expectedResult)
        {
            EntityType      entityType;
            StringField     field;
            List <long>     entitiesToDelete;
            UserAccount     userAccount;
            HttpWebResponse response;
            IEntity         entity;
            IEntity         modifiedEntity;
            const string    initialFieldValue = "foo";
            const string    newFieldValue     = "bar";

            string[] splitPermissions;

            splitPermissions = permissions.Split(new [] { ',' },
                                                 StringSplitOptions.RemoveEmptyEntries);

            entitiesToDelete = new List <long>();
            try
            {
                userAccount      = new UserAccount();
                userAccount.Name = "Test user " + Guid.NewGuid();
                userAccount.Save();
                entitiesToDelete.Add(userAccount.Id);

                field      = Entity.Create <StringField>();
                field.Name = "Test field " + Guid.NewGuid();
                field.Save();
                entitiesToDelete.Add(field.Id);

                entityType = Entity.Create <EntityType>();
                entityType.Inherits.Add(UserResource.UserResource_Type);
                entityType.Fields.Add(field.As <Field>());
                entityType.Save();
                entitiesToDelete.Add(entityType.Id);

                entity = Entity.Create(entityType);
                entity.SetField(field, initialFieldValue);
                entity.Save();
                entitiesToDelete.Add(entity.Id);

                new AccessRuleFactory().AddAllowByQuery(userAccount.As <Subject>(),
                                                        entityType.As <SecurableEntity>(),
                                                        splitPermissions.Select(s => new EntityRef(s)),
                                                        TestQueries.Entities().ToReport());

                using (var request = new PlatformHttpRequest(@"data/v1/entity", PlatformHttpMethod.Post, userAccount))
                {
                    request.PopulateBody(new JsonEntityQueryResult
                    {
                        Ids = new List <long> {
                            entity.Id
                        },
                        Entities = new List <JsonEntity>
                        {
                            new JsonEntity
                            {
                                Id      = entity.Id,
                                TypeIds = new List <long> {
                                    entityType.Id
                                },
                                Fields = new List <JsonFieldData>
                                {
                                    new JsonFieldData
                                    {
                                        FieldId  = field.Id,
                                        Value    = newFieldValue,
                                        TypeName = "String"
                                    }
                                },
                                Relationships = new List <JsonRelationshipData>(),
                                DataState     = DataState.Update
                            }
                        },
                        EntityRefs = new List <JsonEntityRef>
                        {
                            new JsonEntityRef(new EntityRef(entity.Id)),
                            new JsonEntityRef(new EntityRef(entityType)),
                            new JsonEntityRef(new EntityRef(field))
                        }
                    });

                    response = request.GetResponse();

                    Assert.That(response, Has.Property("StatusCode").EqualTo(expectedResult),
                                "Web service call failed");

                    if (expectedResult == HttpStatusCode.OK)
                    {
                        modifiedEntity = Entity.Get(entity.Id);
                        Assert.That(modifiedEntity, Is.Not.Null, "Entity not found");
                        Assert.That(modifiedEntity.GetField(field), Is.EqualTo(newFieldValue),
                                    "Field value incorrect");
                    }
                }
            }
            finally
            {
                try
                {
                    Entity.Delete(entitiesToDelete);
                }
                catch (Exception)
                {
                    // Do nothing
                }
            }
        }
Exemple #29
0
        public void LowAccessUserPausedPriorNestedWorkflow_bug_27863()
        {
            using (new WorkflowRunContext {
                RunTriggersInCurrentThread = true
            })
            {
                Workflow       myParentWorkflow = null;
                Workflow       myChildWorkflow  = null;
                UserAccount    myUser           = null;
                Person         myPerson         = null;
                PromptUserTask userInputTask    = null;

                try
                {
                    myChildWorkflow = Entity.Create <Workflow>()
                                      .AddDefaultExitPoint()
                                      .AddInput <BoolArgument>("InputChild")
                                      .AddLog("Child Log", "Child Log");

                    myChildWorkflow.Name = "Child Workflow 27863 " + DateTime.Now;
                    myChildWorkflow.WorkflowRunAsOwner = true;
                    myChildWorkflow.Save();

                    myParentWorkflow = Entity.Create <Workflow>()
                                       .AddDefaultExitPoint()
                                       .AddInput <BoolArgument>("InputParent")
                                       .AddPromptUser("User Input")
                                       .AddWorkflowProxy("Child Workflow", myChildWorkflow)
                                       .AddLog("Parent Log", "Parent Log");

                    var childWorkflowActivity = myParentWorkflow.ContainedActivities.FirstOrDefault(a => a.Name == "Child Workflow");

                    ActivityTestHelper.AddExpressionToActivityArgument(myParentWorkflow, childWorkflowActivity, "InputChild", "[InputParent]");

                    myParentWorkflow.Name = "Parent Workflow 27863 " + DateTime.Now;
                    myParentWorkflow.WorkflowRunAsOwner = true;
                    myParentWorkflow.Save();

                    myPerson             = Entity.Create <Person>();
                    myPerson.FirstName   = "Billy";
                    myPerson.LastName    = "Bob";
                    myUser               = Entity.Create <UserAccount>();
                    myUser.Name          = "bb" + DateTime.Now;
                    myUser.AccountHolder = myPerson;
                    myUser.Save();

                    new AccessRuleFactory().AddAllowByQuery(myUser.As <Subject>(),
                                                            Workflow.Workflow_Type.As <SecurableEntity>(),
                                                            new EntityRef("core:read").ToEnumerable(),
                                                            TestQueries.Entities(new EntityRef("core:workflow")).ToReport());

                    WorkflowRun run;

                    using (new SetUser(myUser))
                        using (new WorkflowRunContext(true)
                        {
                            RunTriggersInCurrentThread = true
                        })
                        {
                            run = RunWorkflow(myParentWorkflow);
                        }

                    run.WorkflowRunStatus_Enum.Should().Be(WorkflowRunState_Enumeration.WorkflowRunPaused);
                    run.PendingActivity.Should().NotBeNull();
                    run.PendingActivity.Name.Should().Be("User Input");
                    run.TaskWithinWorkflowRun.Should().NotBeNull().And.NotBeEmpty().And.HaveCount(1);

                    userInputTask = run.TaskWithinWorkflowRun.First().AsWritable <PromptUserTask>();
                    userInputTask.Should().NotBeNull();

                    userInputTask.PromptForTaskStateInfo.Should().NotBeNull().And.HaveCount(1);
                    userInputTask.PromptForTaskStateInfo.Select(si => si.StateInfoArgument.Name).Should().Contain("InputParent");

                    var value = userInputTask.PromptForTaskStateInfo.First(si => si.StateInfoArgument.Name == "InputParent");
                    var param = value.StateInfoValue.AsWritable <BoolArgument>();
                    param.BoolParameterValue = true;
                    param.Save();

                    userInputTask.TaskStatus_Enum    = TaskStatusEnum_Enumeration.TaskStatusCompleted;
                    userInputTask.UserTaskIsComplete = true;

                    using (new SetUser(myUser))
                        using (new WorkflowRunContext(true)
                        {
                            RunTriggersInCurrentThread = true
                        })
                        {
                            userInputTask.Save();
                        }

                    var wf = Entity.Get <Workflow>(myParentWorkflow.Id, Workflow.RunningInstances_Field);

                    wf.RunningInstances.Count().Should().Be(1);
                    var runResume = wf.RunningInstances.First();

                    Assert.IsTrue(WaitForWorkflowToStop(runResume), "Workflow run should have completed.");

                    runResume = Entity.Get <WorkflowRun>(runResume.Id, WorkflowRun.WorkflowRunStatus_Field);
                    runResume.Should().NotBeNull();
                    runResume.WorkflowRunStatus_Enum.Should().Be(WorkflowRunState_Enumeration.WorkflowRunCompleted);
                    runResume.RunLog.Should().NotBeNull().And.NotBeEmpty();
                }
                finally
                {
                    if (userInputTask != null)
                    {
                        ToDelete.Add(userInputTask.Id);
                    }
                    if (myParentWorkflow != null)
                    {
                        ToDelete.Add(myParentWorkflow.Id);
                    }
                    if (myChildWorkflow != null)
                    {
                        ToDelete.Add(myChildWorkflow.Id);
                    }
                    if (myUser != null)
                    {
                        ToDelete.Add(myUser.Id);
                    }
                    if (myPerson != null)
                    {
                        ToDelete.Add(myPerson.Id);
                    }
                }
            }
        }
Exemple #30
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
            };
        }