public void RunReportAllAccess() { var nameDescList = new List <Tuple <string, string> > { new Tuple <string, string>("Name1", "Description1"), new Tuple <string, string>("Name2", "Description2") }; SecurityTestData testData = SetupSecurityTest(nameDescList); var reportingInterface = new ReportingInterface(); // Create an access rule new AccessRuleFactory().AddAllowReadQuery(testData.UserAccount.As <EntityModel.Subject>(), testData.EntityType.As <EntityModel.SecurableEntity>(), TestQueries.Entities(testData.EntityType).ToReport()); ReportResult reportResult; using (new SetUser(testData.UserAccount)) { reportResult = reportingInterface.RunReport(testData.Report, null); } foreach (var nameDesc in nameDescList) { Assert.AreEqual(1, reportResult.GridData.Count(gd => gd.Values[1].Value == nameDesc.Item1 && gd.Values[2].Value == nameDesc.Item2)); } Assert.AreEqual(nameDescList.Count, reportResult.GridData.Count); }
public void Test_QuickSearchFilterCaseInsensitive(bool includeFilter) { StructuredQuery structuredQuery; QuerySettings querySettings; QueryBuild queryResult; structuredQuery = TestQueries.Entities( ); structuredQuery.SelectColumns.Add(new SelectColumn { Expression = new ResourceDataColumn(structuredQuery.RootEntity, new EntityRef("core:name")) }); querySettings = new QuerySettings( ) { SecureQuery = false, SupportQuickSearch = includeFilter }; queryResult = BuildSql(structuredQuery, querySettings); if (includeFilter) { Assert.That(queryResult.Sql, Contains.Substring("COLLATE Latin1_General_CI_AI")); } else { Assert.That(queryResult.Sql, Is.Not.ContainsSubstring("COLLATE Latin1_General_CI_AI")); } }
public void BasicTest(InvalidationCause invalidationCause) { CachingReportToQueryConverter cachingReportToQueryConverter; Report report; StructuredQuery structuredQuery; ItemsRemovedEventHandler <CachingReportToQueryConverterKey> itemsRemovedEventHandler; List <long> itemsRemoved; using (var ctx = EDC.ReadiNow.Database.DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true)) { report = TestQueries.Entities().ToReport(); report.Save(); ctx.CommitTransaction(); } cachingReportToQueryConverter = Factory.Current.Resolve <CachingReportToQueryConverter>(); Assert.That(cachingReportToQueryConverter, Is.Not.Null, "Not report to query converter cache found"); Assert.That(cachingReportToQueryConverter, Is.Not.Null, "Not report to query converter cache found"); itemsRemoved = new List <long>(); itemsRemovedEventHandler = (sender, args) => itemsRemoved.AddRange(args.Items.Select(key => key.ReportId)); structuredQuery = cachingReportToQueryConverter.Convert(report, null); try { cachingReportToQueryConverter.Cache.ItemsRemoved += itemsRemovedEventHandler; Assert.That(cachingReportToQueryConverter.Cache, Has.Exactly(1).Property("Key").Property("ReportId").EqualTo(report.Id)); Assert.That(cachingReportToQueryConverter.Cache, Has.Exactly(1).Property("Value").Property("StructuredQuery").SameAs(structuredQuery)); using (var ctx = EDC.ReadiNow.Database.DatabaseContext.GetContext(true, preventPostSaveActionsPropagating: true)) { if (invalidationCause == InvalidationCause.Save) { report.Save(); } else if (invalidationCause == InvalidationCause.Delete) { report.Delete(); } else { Assert.Fail("Unknown invalidation cause"); } ctx.CommitTransaction(); } Assert.That(cachingReportToQueryConverter.Cache, Has.Exactly(0).Property("Key").EqualTo(report.Id)); Assert.That(itemsRemoved, Has.Exactly(1).EqualTo(report.Id)); } finally { cachingReportToQueryConverter.Cache.ItemsRemoved -= itemsRemovedEventHandler; } }
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) { } } } }
public void Security_CheckInstancesSecurity(bool grant) { IEntityXmlExporter exporter = Factory.EntityXmlExporter; IEntityXmlImporter importer = Factory.EntityXmlImporter; string xml; Definition type = new Definition( ); type.Inherits.Add(UserResource.UserResource_Type); type.Name = Guid.NewGuid( ).ToString( ); type.Save( ); Resource instance = Entity.Create(type.Id).As <Resource>( ); instance.Name = "Mordor"; instance.Save( ); // Generate the XML as admin using (RunAsImportExportRole( )) { xml = exporter.GenerateXml(instance.Id, EntityXmlExportSettings.Default); } // Create a user that can create the types, but not modify the instance var user = Entity.Create <UserAccount>( ); user.Name = "Frodo"; user.UserHasRole.Add(Entity.Get <Role>("core:importExportRole")); user.Save( ); new AccessRuleFactory( ).AddAllowCreate(user.As <Subject>( ), type.As <SecurableEntity>( )).Save( ); if (grant) { new AccessRuleFactory( ).AddAllowByQuery(user.As <Subject>( ), type.As <SecurableEntity>( ), new[] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(new EntityRef(type.Id)).ToReport( )).Save( ); } var res = new EntityAccessControlChecker( ).CheckTypeAccess(new[] { type.As <EntityType>() }, Permissions.Create, user); // Try to reimport as non-priv user using (new SetUser(user)) { Action run = () => importer.ImportXml(xml, EntityXmlImportSettings.Default); if (grant) { run( ); } else { Assert.That(Assert.Throws <PlatformSecurityException>(() => run( )).Message, Is.StringStarting("Frodo does not have edit access to Mordor")); } } }
private IEnumerable <TestCaseData> Test_GetReferencedRelationships_Source() { // Using a Func<StructuredQuery> rather than a straight StructuredQuery to // avoid issues with NUnit and using a CallContext in a TestCaseSource method. yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.Entities()), new string[0])); yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.AccessRulesWithNamedPermission("read")), new[] { "core:permissionAccess" })); // Get multiple relationships form the root entity, including an enum yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.ActiveUsersInRole("administrators")), new[] { "core:userHasRole", "core:accountStatus" })); // Test nested related resource nodes and reverse relationships yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.TypesSecuredBySubjects("administrators")), new[] { "core:allowAccess", "core:controlAccess" })); }
public void Security_CheckRootInstancesSecurity(bool grant) { IEntityXmlExporter exporter = Factory.EntityXmlExporter; IEntityXmlImporter importer = Factory.EntityXmlImporter; string xml = null; Definition type = new Definition( ); type.Inherits.Add(UserResource.UserResource_Type); type.Name = Guid.NewGuid( ).ToString( ); type.Save( ); Resource instance = Entity.Create(type.Id).As <Resource>( ); instance.Name = "Mordor"; instance.Save( ); // Create a user that can create the types, but not modify the instance var user = Entity.Create <UserAccount>( ); user.Name = "Frodo"; user.UserHasRole.Add(Entity.Get <Role>("core:importExportRole")); user.Save( ); if (grant) { new AccessRuleFactory( ).AddAllowReadQuery(user.As <Subject>( ), type.As <SecurableEntity>( ), TestQueries.Entities(new EntityRef(type.Id)).ToReport( )).Save( ); } // Try to reimport as non-priv user using (new SetUser(user)) { // Generate the XML as admin Func <string> run = () => exporter.GenerateXml(instance.Id, EntityXmlExportSettings.Default); if (grant) { xml = run( ); } else { Assert.That(Assert.Throws <PlatformSecurityException>(() => run( )).Message, Is.StringStarting("Frodo does not have view access to Mordor")); } } }
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; } }
private IEnumerable <TestCaseData> Test_GetReferencedFields_Source() { // Using a Func<StructuredQuery> rather than a straight StructuredQuery to // avoid issues with NUnit and using a CallContext in a TestCaseSource method. yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.Entities()), new string[0])); yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithNameA()), new[] { "core:name" })); yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithDescription()), new[] { "core:description" })); yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesOrderByDescription()), new[] { "core:description" })); yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithNameDescription("a", "a")), new[] { "core:name", "core:description" })); yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.EntitiesWithNameAndDescriptionInResults("a")), new [] { "core:name", "core:description" })); yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.AccessRulesWithNamedPermission("read")), new[] { "core:name", "core:accessRuleEnabled" })); yield return(new TestCaseData((Func <StructuredQuery>)(() => TestQueries.ActiveUsersInRole("administrators")), new[] { "core:name", "core:alias" })); }
/// <summary> /// Creates a report entity for a given type. /// </summary> /// <param name="alias">The alias given to the report.</param> /// <param name="name">The name given to the report.</param> /// <param name="description">The description given to the report.</param> /// <param name="type">The type to create the report for.</param> /// <param name="isDefault">Whether the report should be the default display report for the type.</param> /// <returns>The created report entity.</returns> public static Report CreateReport(string alias, string name, string description, EntityType type, bool isDefault) { var query = TestQueries.Entities(type); query.SelectColumns[0].IsHidden = true; query.SelectColumns.Add(new SelectColumn { ColumnName = "Name", DisplayName = "Unit", Expression = new ResourceDataColumn(query.RootEntity, new EntityRef("core:name")) }); var report = query.ToReport(); report.Alias = alias; report.Name = name; report.Description = description; if (isDefault) { report.IsDefaultDisplayReportForTypes.Add(type); } return(report); }
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 } } }
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 } } }
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 } } }
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 } } }
public void Test_Relationship(Direction direction, string identityType, int count) { // Create schema EntityType type = Entity.Create <EntityType>( ); type.Name = "Test Type"; type.Inherits.Add(Entity.Get <EntityType>("core:resource")); type.Save( ); Field stringField = new StringField( ).As <Field>( ); Field intField = new IntField( ).As <Field>( ); EntityType type2 = Entity.Create <EntityType>( ); type2.Name = "Test Type2"; type2.Fields.Add(stringField); type2.Fields.Add(intField); type.Inherits.Add(Entity.Get <EntityType>("core:resource")); type2.Save( ); Relationship relationship = Entity.Create <Relationship>( ); relationship.Name = "Rel1"; relationship.Cardinality_Enum = CardinalityEnum_Enumeration.ManyToMany; relationship.FromType = direction == Direction.Forward ? type : type2; relationship.ToType = direction == Direction.Forward ? type2 : type; relationship.Save( ); var targets = new List <Resource>( ); for (int i = 0; i < count; i++) { string name = "Target" + Guid.NewGuid( ); string stringVal = "StringVal" + i; int intVal = 100 + i; Resource target = Entity.Create(type2.Id).AsWritable <Resource>( ); target.SetField(stringField.Id, stringVal); target.SetField(intField.Id, intVal); target.Name = name; target.Save( ); targets.Add(target); } using (new SecurityBypassContext( )) { new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type.Id).ToReport( )); new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type2.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type2.Id).ToReport( )); } Field lookupField = null; if (identityType.Contains("StringField")) { lookupField = stringField; } else if (identityType.Contains("IntField")) { lookupField = intField; } var identities = new List <string>( ); for (int i = 0; i < count; i++) { var target = targets[i]; string identity; if (identityType.Contains("Null")) { continue; } if (identityType == "Name") { identity = "\"" + target.Name + "\""; } else if (identityType == "Guid") { identity = "\"" + target.UpgradeId + "\""; } else if (identityType == "StringField") { identity = "\"StringVal" + i + "\""; } else if (identityType == "IntField") { identity = (100 + i).ToString( ); } else { throw new InvalidOperationException( ); } identities.Add(identity); } // Create JSON string jsonMember = "rel1"; string json = "{\"" + jsonMember + "\":[" + string.Join(", ", identities) + "]}"; // Create a mapping var mapping = CreateApiResourceMapping(new EntityRef(type.Id)); var relMapping = CreateApiRelationshipMapping(mapping, new EntityRef(relationship.Id), jsonMember, direction == Direction.Reverse); relMapping.MappedRelationshipLookupField = lookupField; relMapping.Save( ); // Fill entity IEntity entity = RunTest(json, mapping); IEntityRelationshipCollection <IEntity> value = entity.GetRelationships(relationship.Id, direction); // Assert mapping Assert.That(value, Is.Not.Null); if (identityType == "Null") { Assert.That(value, Has.Count.EqualTo(0)); } else { Assert.That(value, Has.Count.EqualTo(targets.Count)); var actual = value.Select(e => e.Id).OrderBy(id => id).ToList( ); var expected = targets.Select(e => e.Id).OrderBy(id => id).ToList( ); Assert.That(actual, Is.EquivalentTo(expected)); } }
public void Test_GetActions_Security_ReadModifyDelete(string permissionAliases) { ActionRequestExtended actionRequest; ActionResponse response; Report peopleReport; UserAccount userAccount; Person person; ActionMenuItem viewActionMenuItem; ActionMenuItem editActionMenuItem; ActionMenuItem deleteActionMenuItem; IList <ActionMenuItemInfo> flattenedResults; string[] splitPermissionAliases; splitPermissionAliases = permissionAliases.Split(','); userAccount = Entity.Create <UserAccount>(); userAccount.Save(); person = Entity.Create <Person>(); person.Save(); viewActionMenuItem = Entity.Get <ActionMenuItem>("console:viewResourceAction"); Assert.That(viewActionMenuItem, Is.Not.Null, "No view menu item"); editActionMenuItem = Entity.Get <ActionMenuItem>("console:editResourceAction"); Assert.That(editActionMenuItem, Is.Not.Null, "No edit menu item"); deleteActionMenuItem = Entity.Get <ActionMenuItem>("console:deleteResourceAction"); Assert.That(deleteActionMenuItem, Is.Not.Null, "No delete menu item"); if (!string.IsNullOrWhiteSpace(permissionAliases)) { new AccessRuleFactory().AddAllowByQuery( userAccount.As <Subject>(), Entity.Get <SecurableEntity>(Entity.Get <EntityType>("core:person")), splitPermissionAliases.Select(pa => new EntityRef(pa)), TestQueries.Entities().ToReport()); } peopleReport = Entity.GetByName <Report>("People").FirstOrDefault(); Assert.That(peopleReport, Is.Not.Null, "No People report"); actionRequest = new ActionRequestExtended { SelectedResourceIds = new[] { person.Id }, LastSelectedResourceId = person.Id, CellSelectedResourceId = -1, ReportId = peopleReport.Id, HostResourceIds = new long[0], HostTypeIds = new List <long>(), AdditionalData = new Dictionary <string, object>(), ActionDisplayContext = ActionContext.ActionsMenu }; using (new SetUser(userAccount)) { response = new ActionService().GetActions(actionRequest); } flattenedResults = response.Actions.SelectMany(Flatten).ToList(); Assert.That(flattenedResults, Has.Exactly(splitPermissionAliases.Contains("read") ? 1 : 0).Property("Id").EqualTo(viewActionMenuItem.Id), "View menu incorrect"); Assert.That(flattenedResults, Has.Exactly(splitPermissionAliases.Contains("read") && splitPermissionAliases.Contains("modify") ? 1 : 0).Property("Id").EqualTo(editActionMenuItem.Id), "Edit menu incorrect"); Assert.That(flattenedResults, Has.Exactly(splitPermissionAliases.Contains("read") && splitPermissionAliases.Contains("delete") ? 1 : 0).Property("Id").EqualTo(deleteActionMenuItem.Id), "Delete menu incorrect"); }
[TestCase("API Endpoints", "API Resource Endpoint,API Spreadsheet Endpoint", true)] //#27489 public void Test_GetActions_Security_Create(string reportName, string typeNames, bool admin) { ActionRequestExtended actionRequest; ActionResponse response; Report report; UserAccount userAccount; IList <ActionMenuItemInfo> flattenedResults; string[] splitTypeNames; SecurableEntity securableEntity; splitTypeNames = typeNames.Split(','); userAccount = Entity.Create <UserAccount>(); userAccount.Name = "Action service test " + Guid.NewGuid( ).ToString( ); userAccount.Save(); new AccessRuleFactory( ).AddAllowReadQuery( userAccount.As <Subject>( ), Entity.Get <SecurableEntity>(Entity.Get <EntityType>("core:report")), TestQueries.Entities(new EntityRef("core:report")).ToReport( )); if (!string.IsNullOrWhiteSpace(typeNames)) { foreach (string typeName in splitTypeNames) { securableEntity = Entity.GetByName <SecurableEntity>(typeName).FirstOrDefault(); Assert.That(securableEntity, Is.Not.Null, string.Format("{0} is not a type", typeName)); new AccessRuleFactory().AddAllowCreate( userAccount.As <Subject>(), securableEntity); } } report = Entity.GetByName <Report>(reportName).FirstOrDefault(); Assert.That(report, Is.Not.Null, string.Format("{0} is not a report", reportName)); actionRequest = new ActionRequestExtended { SelectedResourceIds = new long[0], LastSelectedResourceId = 0, CellSelectedResourceId = -1, ReportId = report.Id, HostResourceIds = new long[0], HostTypeIds = new List <long>(), AdditionalData = new Dictionary <string, object>(), ActionDisplayContext = ActionContext.ActionsMenu }; if (admin) { response = new ActionService( ).GetActions(actionRequest); } else { using (new SetUser(userAccount)) { response = new ActionService( ).GetActions(actionRequest); } } flattenedResults = response.Actions.SelectMany(Flatten).ToList(); if (!string.IsNullOrWhiteSpace(typeNames)) { foreach (string typeName in splitTypeNames) { string expectState = typeName == "API Resource Endpoint" ? "resourceEndpointNew" : ActionService.CreateMenuItemActionState; Assert.That(flattenedResults, Has.Exactly(1).Property("HtmlActionState").EqualTo(expectState) .And.Property("Name").EqualTo(typeName)); } } else { Assert.That(flattenedResults, Has.Exactly(0).Property("HtmlActionState").EqualTo(ActionService.CreateMenuItemActionState)); } }
public void Test_RootTable(bool supportRootIdFilter, bool suppressRootTypeCheck, bool exactType, string typeAlias) { StructuredQuery structuredQuery; QuerySettings querySettings; QueryBuild queryResult; const long testEntityId = 42; structuredQuery = TestQueries.Entities(new EntityRef(typeAlias)); querySettings = new QuerySettings( ) { SecureQuery = false, SupportRootIdFilter = supportRootIdFilter, SuppressRootTypeCheck = suppressRootTypeCheck, RootIdFilterList = testEntityId.ToEnumerable( ) }; ((ResourceEntity)structuredQuery.RootEntity).ExactType = exactType; queryResult = BuildSql(structuredQuery, querySettings); if (supportRootIdFilter) { Assert.That(queryResult.Sql, Contains.Substring("@entitylist")); // If the @entitylist attribute is present, then we do not need to join against the entity table, so it should not be present Assert.That(queryResult.Sql, Is.Not.ContainsSubstring("Entity")); } else { Assert.That(queryResult.Sql, Is.Not.ContainsSubstring("@entitylist")); } // Expect a type check, unless it is suppressed, or unless every type of resource is permitted bool expectTypeCheck = !suppressRootTypeCheck && (typeAlias != "core:resource" || exactType); if (expectTypeCheck) { Assert.That(queryResult.Sql, Contains.Substring("/*isOfType*/")); // If there's any form of type check, then there's never a need to use the entity table, because we can use the relationship table, if nothing else Assert.That(queryResult.Sql, Is.Not.ContainsSubstring("Entity")); bool expectExactType = exactType || typeAlias == "test:drink"; // drink has no derived types if (expectExactType) { Assert.That(queryResult.Sql, Contains.Substring(".ToId = @param2")); Assert.That(queryResult.Sql, Is.Not.ContainsSubstring(".ToId in (@param2, @param3")); } else { Assert.That(queryResult.Sql, Contains.Substring(".ToId in (@param2, @param3")); Assert.That(queryResult.Sql, Is.Not.ContainsSubstring(".ToId = @param2")); } } else { Assert.That(queryResult.Sql, Is.Not.ContainsSubstring("/*isOfType*/")); } // Look for a join to the entity list if its type is to be checked if (expectTypeCheck && supportRootIdFilter) { Assert.That(queryResult.Sql, Contains.Substring("r.FromId = el.Id")); } else { Assert.That(queryResult.Sql, Is.Not.ContainsSubstring("r.FromId = el.Id")); } }
public void Security_CheckRelatedInstancesSecurity(bool grant) { IEntityXmlExporter exporter = Factory.EntityXmlExporter; IEntityXmlImporter importer = Factory.EntityXmlImporter; EntityType type = new Definition( ).As <EntityType>( ); type.Inherits.Add(UserResource.UserResource_Type); type.Name = Guid.NewGuid( ).ToString( ); type.Save( ); EntityType type2 = new Definition( ).As <EntityType>( ); type2.Inherits.Add(UserResource.UserResource_Type); type2.Name = Guid.NewGuid( ).ToString( ); type2.Save( ); Relationship rel = new Relationship( ); rel.FromType = type; rel.ToType = type2; rel.CloneAction_Enum = CloneActionEnum_Enumeration.CloneEntities; rel.ReverseCloneAction_Enum = CloneActionEnum_Enumeration.CloneReferences; rel.Cardinality_Enum = CardinalityEnum_Enumeration.ManyToMany; rel.Save( ); Resource instance2 = Entity.Create(type2.Id).As <Resource>( ); instance2.Name = "Mordor"; instance2.Save( ); Resource instance = Entity.Create(type.Id).As <Resource>( ); instance.Name = "Gondor"; instance.GetRelationships(rel.Id, Direction.Forward).Add(instance2); instance.Save( ); // Create a user that can create the types, but not modify the instance var user = Entity.Create <UserAccount>( ); user.Name = "Frodo"; user.UserHasRole.Add(Entity.Get <Role>("core:importExportRole")); user.Save( ); new AccessRuleFactory( ).AddAllowReadQuery(user.As <Subject>( ), type.As <SecurableEntity>( ), TestQueries.Entities(new EntityRef(type.Id)).ToReport( )).Save( ); if (grant) { new AccessRuleFactory( ).AddAllowReadQuery(user.As <Subject>( ), type2.As <SecurableEntity>( ), TestQueries.Entities(new EntityRef(type2.Id)).ToReport( )).Save( ); } // Try to reimport as non-priv user using (new SetUser(user)) { // Generate the XML as admin string xml = exporter.GenerateXml(instance.Id, EntityXmlExportSettings.Default); if (grant) { Assert.That(xml, Is.StringContaining("Mordor")); } else { Assert.That(xml, Is.Not.StringContaining("Mordor")); } } }
public void UpdateEntityDeleteItemFromSecuresToRelationship() { // this case requires that the entity to be delete ONLY receives its access for read/delete through // the relationship with the entity being updated. // (I.e. activityPrompts removed from promptForArguments relationship with promptUserActivity) ///////////////////////////////////////////////////////////////////////////////////////// // Arrange ///////////////////////////////////////////////////////////////////////////////////////// var parentType = Create <EntityType>(); parentType.Inherits.Add(UserResource.UserResource_Type); parentType.Save(); var childType = Create <EntityType>(); childType.Inherits.Add(UserResource.UserResource_Type); childType.Save(); var rel = Create <Relationship>(); rel.FromType = parentType; rel.ToType = childType; rel.Cardinality_Enum = CardinalityEnum_Enumeration.OneToMany; rel.SecuresTo = true; rel.Save(); var parentInstance = Entity.Create(parentType.Id); var childInstance = Entity.Create(childType.Id); SetRel(parentInstance, childInstance, rel); parentInstance.IsTemporaryId.Should().BeFalse(); childInstance.IsTemporaryId.Should().BeFalse(); Entity.Exists(parentInstance.Id).Should().BeTrue(); Entity.Exists(childInstance.Id).Should().BeTrue(); var user = Create <UserAccount>(true); user.Name = "UpdateEntityDeleteItemFromSecuresToRelationship"; user.Save(); using (new SetUser(user)) { Action getParentNoPermission = () => Entity.Get(parentInstance.Id); getParentNoPermission.ShouldThrow <PlatformSecurityException>().WithMessage("*does not have view access to*"); Action getChildNoPermission = () => Entity.Get(childInstance.Id); getChildNoPermission.ShouldThrow <PlatformSecurityException>().WithMessage("*does not have view access to*"); } // grant access via parent var query = TestQueries.Entities(parentType); var queryResult = Factory.QueryRunner.ExecuteQuery(query, new QuerySettings { SecureQuery = true }); queryResult.Should().NotBeNull(); queryResult.DataTable.Rows.Count.Should().Be(1); queryResult.DataTable.Rows[0].ItemArray.Should().Contain(parentInstance.Id); new AccessRuleFactory().AddAllowByQuery(user.As <Subject>(), parentType.As <SecurableEntity>(), new[] { Permissions.Read, Permissions.Modify, Permissions.Delete }, query.ToReport()); Factory.EntityAccessControlService.ClearCaches(); using (new SetUser(user)) { IEntity p = null; Action getParentPermission = () => p = Entity.Get(parentInstance.Id); getParentPermission.ShouldNotThrow(); p.Should().NotBeNull(); p.Id.ShouldBeEquivalentTo(parentInstance.Id); IEntity c = null; Action getChildPermission = () => c = Entity.Get(childInstance.Id); getChildPermission.ShouldNotThrow(); c.Should().NotBeNull(); c.Id.ShouldBeEquivalentTo(childInstance.Id); } var data = new EntityData { Id = new EntityRef(parentInstance.Id), Relationships = new List <RelationshipData> { new RelationshipData { RelationshipTypeId = new EntityRef(rel.Id), Instances = new List <RelationshipInstanceData> { new RelationshipInstanceData { Entity = new EntityData { Id = new EntityRef(childInstance.Id), DataState = DataState.Delete } } } } } }; ///////////////////////////////////////////////////////////////////////////////////////// // Act ///////////////////////////////////////////////////////////////////////////////////////// using (new SetUser(user)) { var svc = new EntityInfoService(); Action callUpdate = () => svc.UpdateEntity(data); callUpdate.ShouldNotThrow(); } ///////////////////////////////////////////////////////////////////////////////////////// // Assert ///////////////////////////////////////////////////////////////////////////////////////// Entity.Exists(parentInstance.Id).Should().BeTrue(); Entity.Exists(childInstance.Id).Should().BeFalse(); }
public void Test_Lookup_NotFound( ) { // Create schema EntityType type = Entity.Create <EntityType>( ); type.Name = "Test Type"; type.Inherits.Add(Entity.Get <EntityType>("core:resource")); type.Save( ); EntityType type2 = Entity.Create <EntityType>( ); type2.Name = "Test Type2"; type.Inherits.Add(Entity.Get <EntityType>("core:resource")); type2.Save( ); Relationship relationship = Entity.Create <Relationship>( ); relationship.Name = "Rel1"; relationship.Cardinality_Enum = CardinalityEnum_Enumeration.OneToOne; relationship.FromType = type; relationship.ToType = type2; relationship.Save( ); using (new SecurityBypassContext( )) { new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type.Id).ToReport( )); new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type2.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type2.Id).ToReport( )); } string identity = "I dont exist"; // Create JSON string jsonMember = "rel1"; string json = "{\"" + jsonMember + "\":\"" + identity + "\"}"; // Create a mapping var mapping = CreateApiResourceMapping(new EntityRef(type.Id)); CreateApiRelationshipMapping(mapping, new EntityRef(relationship.Id), jsonMember, false); // Attempt to fill entity Assert.Throws <ConnectorRequestException>(() => RunTest(json, mapping), "E1003 No resources were found that matched 'I dont exist'."); }
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 } } }
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 } } }
public void Test_IncludedRoles( ) { // Note: ExpectedResult is null when we expect no grant Definition type = null; // needs to be definition, otherwise gets filtered from the report. Role parentRole = null; Role childRole = null; List <IEntity> cleanup = new List <IEntity>( ); try { EntityType editableResource = UserResource.UserResource_Type; // Setup scenario type = Entity.Create <Definition>( ); type.Name = Guid.NewGuid().ToString( ); type.Inherits.Add(editableResource); type.Save( ); cleanup.Add(type); // Set up roles parentRole = Entity.Create <Role>( ); childRole = Entity.Create <Role>( ); parentRole.IncludesRoles.Add(childRole); parentRole.Save( ); cleanup.Add(parentRole); cleanup.Add(childRole); new AccessRuleFactory( ).AddAllowReadQuery(parentRole.As <Subject>( ), type.As <SecurableEntity>( ), TestQueries.Entities(type).ToReport( )); new AccessRuleFactory( ).AddAllowModifyQuery(childRole.As <Subject>( ), type.As <SecurableEntity>( ), TestQueries.Entities(type).ToReport( )); // Tests ITypeAccessReasonService service = Factory.Current.Resolve <ITypeAccessReasonService>( ); var reasons = service.GetTypeAccessReasons(childRole.Id, TypeAccessReasonSettings.Default); Assert.That(reasons.Where(reason => reason.SubjectId == WellKnownAliases.CurrentTenant.EveryoneRole).Count(), Is.GreaterThan(0)); // Sanity check for the type we explicitly grant accses AccessReason childReason = reasons.SingleOrDefault(r => r.SubjectId == childRole.Id); AccessReason parentReason = reasons.SingleOrDefault(r => r.SubjectId == parentRole.Id); Assert.That(childReason, Is.Not.Null, "child reason"); Assert.That(parentReason, Is.Not.Null, "parent reason"); Assert.That(childReason.TypeId, Is.EqualTo(type.Id), "child reason type"); Assert.That(parentReason.TypeId, Is.EqualTo(type.Id), "parent reason type"); } finally { Entity.Delete(cleanup.Select(e => new EntityRef(e))); } }
public void Test_GetActions_Security_MultipleSelection(string entity1Name, string entity2Name, bool expectedResult) { ActionRequestExtended actionRequest; ActionResponse response; Report report; UserAccount userAccount; ActionMenuItem deleteActionMenuItem; IList <ActionMenuItemInfo> flattenedResults; EntityType entityType; IEntity entity1; IEntity entity2; entityType = Entity.Create <EntityType>(); entityType.Inherits.Add(UserResource.UserResource_Type); entityType.Save(); entity1 = Entity.Create(entityType); entity1.SetField("core:name", entity1Name); entity1.Save(); entity2 = Entity.Create(entityType); entity2.SetField("core:name", entity2Name); entity2.Save(); userAccount = Entity.Create <UserAccount>(); userAccount.Name = "Action service test " + Guid.NewGuid( ).ToString( ); userAccount.Save(); new AccessRuleFactory( ).AddAllowReadQuery( userAccount.As <Subject>( ), Entity.Get <SecurableEntity>(Entity.Get <EntityType>("core:report")), TestQueries.Entities(new EntityRef("core:report")).ToReport( )); deleteActionMenuItem = Entity.Get <ActionMenuItem>("console:deleteResourceAction"); Assert.That(deleteActionMenuItem, Is.Not.Null, "No delete menu item"); new AccessRuleFactory().AddAllowByQuery( userAccount.As <Subject>(), entityType.As <SecurableEntity>(), new [] { Permissions.Read, Permissions.Delete }, TestQueries.EntitiesWithNameA(entityType).ToReport()); report = TestQueries.EntitiesWithNameA(entityType).ToReport(); report.Save(); actionRequest = new ActionRequestExtended { SelectedResourceIds = new[] { entity1.Id, entity2.Id }, LastSelectedResourceId = entity1.Id, CellSelectedResourceId = -1, ReportId = report.Id, HostResourceIds = new long[0], HostTypeIds = new List <long>(), AdditionalData = new Dictionary <string, object>(), ActionDisplayContext = ActionContext.ContextMenu }; using (new SetUser(userAccount)) { response = new ActionService().GetActions(actionRequest); } flattenedResults = response.Actions.SelectMany(Flatten).ToList(); Assert.That(flattenedResults, Has.Exactly(expectedResult ? 1 : 0).Property("Id").EqualTo(deleteActionMenuItem.Id), "Delete menu incorrect"); }
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 } } }
private static void CreateUsersAndSecurity(ref GrandDesign testObject) { // // Users // var administratorUser = Entity.Get <UserAccount>(new EntityRef("core:administratorUserAccount"), true); testObject.Accounts.Add("administrator", administratorUser); // // Access Rules // new AccessRuleFactory().AddAllowByQuery(administratorUser.As <Subject>(), testObject.Types["unit"].As <SecurableEntity>(), new[] { "core:read", "core:modify", "core:delete", "core:create" }.Select(p => new EntityRef(p)), TestQueries.Entities(testObject.Types["unit"]).ToReport()); // // Read // var reader = Entity.Create <Person>(); reader.FirstName = "Robbie"; reader.LastName = "Reader"; var readerAccount = Entity.Create <UserAccount>(); readerAccount.Name = "reader"; readerAccount.AccountHolder = reader; readerAccount.Save(); testObject.Accounts.Add("reader", readerAccount); new AccessRuleFactory().AddAllowByQuery(readerAccount.As <Subject>(), testObject.Types["unit"].As <SecurableEntity>(), new[] { "core:read" }.Select(p => new EntityRef(p)), TestQueries.Entities(testObject.Types["unit"]).ToReport()); // // Read + Modify // var modifier = Entity.Create <Person>(); modifier.FirstName = "Margie"; modifier.LastName = "Modifier"; var modifierAccount = Entity.Create <UserAccount>(); modifierAccount.Name = "modifier"; modifierAccount.AccountHolder = modifier; modifierAccount.Save(); testObject.Accounts.Add("modifier", modifierAccount); new AccessRuleFactory().AddAllowByQuery(modifierAccount.As <Subject>(), testObject.Types["unit"].As <SecurableEntity>(), new[] { "core:read", "core:modify" }.Select(p => new EntityRef(p)), TestQueries.Entities(testObject.Types["unit"]).ToReport()); // // Read, Modify + Create // var creator = Entity.Create <Person>(); creator.FirstName = "Connie"; creator.LastName = "Creator"; var creatorAccount = Entity.Create <UserAccount>(); creatorAccount.Name = "creator"; creatorAccount.AccountHolder = creator; creatorAccount.Save(); testObject.Accounts.Add("creator", creatorAccount); new AccessRuleFactory().AddAllowByQuery(creatorAccount.As <Subject>(), testObject.Types["unit"].As <SecurableEntity>(), new[] { "core:read", "core:modify", "core:create" }.Select(p => new EntityRef(p)), TestQueries.Entities(testObject.Types["unit"]).ToReport()); // // Read, Modify + Delete // var deleter = Entity.Create <Person>(); deleter.FirstName = "Donnie"; deleter.LastName = "Deleter"; var deleterAccount = Entity.Create <UserAccount>(); deleterAccount.Name = "deleter"; deleterAccount.AccountHolder = deleter; deleterAccount.Save(); testObject.Accounts.Add("deleter", deleterAccount); new AccessRuleFactory().AddAllowByQuery(deleterAccount.As <Subject>(), testObject.Types["unit"].As <SecurableEntity>(), new[] { "core:read", "core:modify", "core:delete" }.Select(p => new EntityRef(p)), TestQueries.Entities(testObject.Types["unit"]).ToReport()); // // Folder // var folder = Entity.Create <Folder>(); folder.Name = "Get Actions"; folder.ResourceInFolder.Add(Entity.GetByName <NavSection>("Test Solution").First().As <NavContainer>()); folder.Save(); testObject.WorkingFolder = folder; // // All these accounts should see... // foreach (var account in testObject.Accounts.Values) { // // ...workflows // new AccessRuleFactory().AddAllowByQuery(account.As <Subject>(), Workflow.Workflow_Type.As <SecurableEntity>(), new EntityRef("core:read").ToEnumerable(), TestQueries.Entities(new EntityRef("core:workflow")).ToReport()); // // ... report templates // new AccessRuleFactory().AddAllowByQuery(account.As <Subject>(), ReportTemplate.ReportTemplate_Type.As <SecurableEntity>(), new EntityRef("core:read").ToEnumerable(), TestQueries.Entities(new EntityRef("core:reportTemplate")).ToReport()); } }
public void Test_Lookup(Direction direction, string identityType) { string name = "Target" + Guid.NewGuid(); // Create schema EntityType type = Entity.Create <EntityType>( ); type.Name = "Test Type"; type.Inherits.Add(Entity.Get <EntityType>("core:resource")); type.Save( ); Field stringField = new StringField( ).As <Field>( ); Field intField = new IntField( ).As <Field>( ); EntityType type2 = Entity.Create <EntityType>( ); type2.Fields.Add(stringField); type2.Fields.Add(intField); type2.Name = "Test Type2"; type.Inherits.Add(Entity.Get <EntityType>("core:resource")); type2.Save( ); Relationship relationship = Entity.Create <Relationship>( ); relationship.Name = "Rel1"; relationship.Cardinality_Enum = CardinalityEnum_Enumeration.OneToOne; relationship.FromType = direction == Direction.Forward ? type : type2; relationship.ToType = direction == Direction.Forward ? type2 : type; relationship.Save( ); Resource target = Entity.Create(type2.Id).AsWritable <Resource>(); target.Name = name; target.SetField(stringField.Id, "StringVal"); target.SetField(intField.Id, 101); target.Save( ); using (new SecurityBypassContext( )) { new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type.Id).ToReport( )); new AccessRuleFactory( ).AddAllowByQuery(Entity.Get <Subject>("core:everyoneRole").AsWritable <Subject>( ), type2.As <SecurableEntity>( ), new [] { Permissions.Read, Permissions.Modify }, TestQueries.Entities(type2.Id).ToReport( )); } Field lookupField = null; string identity; if (identityType == "Name") { identity = "\"" + name + "\""; } else if (identityType == "Guid") { identity = "\"" + target.UpgradeId.ToString() + "\""; } else if (identityType.Contains("Null")) { identity = "null"; } else if (identityType == "StringField") { identity = "\"StringVal\""; } else if (identityType == "IntField") { identity = "101"; } else { throw new InvalidOperationException(); } if (identityType.Contains("StringField")) { lookupField = stringField; } else if (identityType.Contains("IntField")) { lookupField = intField; } // Create JSON string jsonMember = "rel1"; string json = "{\"" + jsonMember + "\":" + identity + "}"; // Create a mapping var mapping = CreateApiResourceMapping(new EntityRef(type.Id)); var relMapping = CreateApiRelationshipMapping(mapping, new EntityRef(relationship.Id), jsonMember, direction == Direction.Reverse); relMapping.MappedRelationshipLookupField = lookupField; relMapping.Save( ); // Fill entity IEntity entity = RunTest(json, mapping); IEntityRelationshipCollection <IEntity> value = entity.GetRelationships(relationship.Id, direction); // Assert mapping Assert.That(value, Is.Not.Null); if (identityType.Contains("Null")) { Assert.That(value, Has.Count.EqualTo(0)); } else { Assert.That(value, Has.Count.EqualTo(1)); Assert.That(value.First( ).Id, Is.EqualTo(target.Id)); } }
public void 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); } } } }
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 }; }