/// <summary> /// Factory method to create an <see cref="AclProbe"/> from the passed <see cref="User"/>, <see cref="Role"/> and <see cref="AccessControlEntry"/>. /// </summary> /// <returns></returns> public static AclProbe CreateAclProbe(User user, Role role, AccessControlEntry ace) { ArgumentUtility.CheckNotNull("user", user); ArgumentUtility.CheckNotNull("role", role); ArgumentUtility.CheckNotNull("ace", ace); var aclProbe = new AclProbe(); var owningUser = CreateOwningUserEntry(aclProbe, user, ace); var owningGroup = CreateOwningGroupEntry(aclProbe, role, ace); var owningTenant = CreateOwningTenantEntry(aclProbe, user, ace); var abstractRoles = CreateAbstractRolesEntry(aclProbe, ace); // Create a new Principal which has only the one role we are currently probing for. // If we don't do that and set all the user's roles for the principal, // another role of the user could match the ACE.SpecificPosition // for case GroupSelection.All or GroupSelection.OwningGroup, giving access rights // which the user does not have due to the currently tested role. // (Note that the user is in fact always in all roles at the same time, so he will, in fact, // always have the access rights returned; this is just not the information we want to present in the // ACL-expansion, where we distinguish which role gives rise to which access rights). var principal = new Principal( user.Tenant.GetHandle(), user.GetSafeHandle(), EnumerableUtility.Singleton(new PrincipalRole(role.Position.GetHandle(), role.Group.GetHandle()))); aclProbe._securityToken = SecurityToken.Create(principal, owningTenant, owningGroup, owningUser, abstractRoles); return(aclProbe); }
public void Initialize_Empty() { Tenant principalTenant = CreateTenant("principalTenant"); Principal principal = PrincipalTestHelper.Create(principalTenant, null, new Role[0]); SecurityToken token = SecurityToken.Create(principal, null, null, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >()); Assert.That(token.OwningTenant, Is.Null); Assert.That(token.OwningGroup, Is.Null); Assert.That(token.OwningUser, Is.Null); Assert.That(token.AbstractRoles, Is.Empty); }
public void TokenWithoutPrincipalUser_Matches() { SecurityToken token = SecurityToken.Create( PrincipalTestHelper.Create(_companyHelper.CompanyTenant, null, new Role[0]), _companyHelper.CompanyTenant, null, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >()); SecurityTokenMatcher matcher = new SecurityTokenMatcher(_ace); Assert.That(matcher.MatchesToken(token), Is.True); }
public void TokenWithTenantDifferentFromOwningTenant_DoesNotMatch() { SecurityToken token = SecurityToken.Create( PrincipalTestHelper.Create(TestHelper.CreateTenant("tenant"), null, new Role[0]), _companyHelper.CompanyTenant, null, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >()); SecurityTokenMatcher matcher = new SecurityTokenMatcher(_ace); Assert.That(matcher.MatchesToken(token), Is.False); }
public void TokenWithoutPrincipalRoles_DoesNotMatch() { SecurityToken token = SecurityToken.Create( PrincipalTestHelper.Create(_companyHelper.CompanyTenant, _companyHelper.CarTeamMember, new Role[0]), null, _companyHelper.AustrianCarTeam, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >()); SecurityTokenMatcher matcher = new SecurityTokenMatcher(_ace); Assert.That(matcher.MatchesToken(token), Is.False); }
public SecurityToken CreateToken(User principalUser, Tenant owningTenant, Group owningGroup, User owningUser, IEnumerable <AbstractRoleDefinition> abstractRoleDefinitions) { ArgumentUtility.CheckNotNull("principalUser", principalUser); var abstractRoles = new List <IDomainObjectHandle <AbstractRoleDefinition> > (); if (abstractRoleDefinitions != null) { abstractRoles.AddRange(abstractRoleDefinitions.Select(abstractRole => abstractRole.GetHandle())); } Principal principal = PrincipalTestHelper.Create(principalUser.Tenant, principalUser, principalUser.Roles); return(SecurityToken.Create(principal, owningTenant, owningGroup, owningUser, abstractRoles)); }
public void TokenWithoutPrincipalUserButWithPrincipalRole_Matches() { User user = CreateUser(_companyHelper.CompanyTenant, null); Group userGroup = _companyHelper.AustrianProjectsDepartment; Role userRole = TestHelper.CreateRole(user, userGroup, _companyHelper.HeadPosition); SecurityToken token = SecurityToken.Create( PrincipalTestHelper.Create(_companyHelper.CompanyTenant, null, new[] { userRole }), null, userGroup, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >()); SecurityTokenMatcher matcher = new SecurityTokenMatcher(_ace); Assert.That(matcher.MatchesToken(token), Is.True); }
public void AccessControlList_GetAccessTypes2() { var user = User3; var acl = TestHelper.CreateStatefulAcl(Ace3); Assert.That(Ace3.Validate().IsValid); Principal principal = PrincipalTestHelper.Create(user.Tenant, user, user.Roles); SecurityToken securityToken = SecurityToken.Create( principal, user.Tenant, null, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >()); AccessInformation accessInformation = acl.GetAccessTypes(securityToken); Assert.That(accessInformation.AllowedAccessTypes, Is.EquivalentTo(new[] { ReadAccessType, WriteAccessType })); }
public void TokenWithoutTenantAndOwningTenant_DoesNotMatch() { // Creating a non-null principal with a null Tenant is only possible via reflection. var principal = PrincipalTestHelper.Create(TestHelper.CreateTenant("tenant"), null, new Role[0]); PrivateInvoke.SetNonPublicField(principal, "_tenant", null); SecurityToken token = SecurityToken.Create( principal, _companyHelper.CompanyTenant, null, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >()); SecurityTokenMatcher matcher = new SecurityTokenMatcher(_ace); Assert.That(matcher.MatchesToken(token), Is.False); }
public void GetAccess_UsesSecurityFreeSection() { ClientTransaction subTransaction; using (_clientTransaction.EnterNonDiscardingScope()) { var abstractRoles = new List <IDomainObjectHandle <AbstractRoleDefinition> >(); //abstractRoles.Add (_ace.SpecificAbstractRole.GetHandle()); //_ace.GroupCondition = GroupCondition.AnyGroupWithSpecificGroupType; //_ace.SpecificGroupType = GroupType.NewObject(); OrganizationalStructureFactory organizationalStructureFactory = new OrganizationalStructureFactory(); var role = Role.NewObject(); role.Group = organizationalStructureFactory.CreateGroup(); role.Group.Tenant = _tenant; role.Position = organizationalStructureFactory.CreatePosition(); var token = SecurityToken.Create(PrincipalTestHelper.Create(_tenant, null, new[] { role }), null, null, null, abstractRoles); subTransaction = _clientTransaction.CreateSubTransaction(); using (subTransaction.EnterNonDiscardingScope()) { var aclHandle = CreateAccessControlListHandle(); Expect.Call(_mockAclFinder.Find(_context)) .WhenCalled(invocation => Assert.That(SecurityFreeSection.IsActive, Is.True)) .Return(aclHandle); Expect.Call(_mockTokenBuilder.CreateToken(_principalStub, _context)) .WhenCalled(invocation => Assert.That(SecurityFreeSection.IsActive, Is.True)) .Return(token); } } var serviceLocator = DefaultServiceLocator.Create(); serviceLocator.RegisterSingle(() => MockRepository.GenerateStub <ISecurityProvider>()); using (new ServiceLocatorScope(serviceLocator)) { _clientTransaction.Extensions.Add(new SecurityClientTransactionExtension()); _mocks.ReplayAll(); _service.GetAccess(_context, _principalStub); _mocks.VerifyAll(); } }
public void GetAccess_ContextDoesNotMatchAcl_ReturnsEmptyAccessTypes() { SecurityToken token = SecurityToken.Create( PrincipalTestHelper.Create(_tenant, null, new Role[0]), null, null, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >()); Expect.Call(_mockAclFinder.Find(_context)).Return(null); Expect.Call(_mockTokenBuilder.CreateToken(_principalStub, _context)).Return(token); _mocks.ReplayAll(); AccessType[] actualAccessTypes = _service.GetAccess(_context, _principalStub); Assert.That(actualAccessTypes, Is.Empty); }
public void AccessControlList_GetAccessTypes_AceWithPosition_GroupSelectionAll() { var ace = TestHelper.CreateAceWithPositionAndGroupCondition(Position, GroupCondition.None); AttachAccessTypeReadWriteDelete(ace, true, null, true); Assert.That(ace.Validate().IsValid); var acl = TestHelper.CreateStatefulAcl(ace); Principal principal = PrincipalTestHelper.Create(User.Tenant, User, User.Roles); SecurityToken securityToken = SecurityToken.Create( principal, User.Tenant, null, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >()); AccessInformation accessInformation = acl.GetAccessTypes(securityToken); Assert.That(accessInformation.AllowedAccessTypes, Is.EquivalentTo(new[] { ReadAccessType, DeleteAccessType })); }
/// <summary> /// Converts the specified <paramref name="uriLocation"/> to a tampering protected <see cref="Uri"/>. /// </summary> /// <param name="uriLocation">The URI to protect from tampering.</param> /// <param name="securityKey">The security key to use for the <see cref="SecurityToken"/> encryption.</param> /// <param name="settings">The settings to apply to the <see cref="SecurityToken"/>.</param> /// <param name="algorithmType">The hash algorithm to use for the URI checksum computation. Default is <b><see cref="HashAlgorithmType.SHA1"/></b>.</param> /// <param name="secureUriFormat">The naming format of the required query string parameters of the tamper protected URI. Default is <b>?token={0}&iv={1}&salt={2}</b>, where you can change the naming of the query string parameters.</param> /// <param name="querystringParameterHashName">The name of the checksum parameter to append to the tampering protected URI. Default is <b>hash</b>.</param> /// <returns>An URI equivalent to the <paramref name="uriLocation"/> but protected from tampering - including but not limited to - MITM attacks.</returns> public static Uri CreateTamperingProtectedUri(string uriLocation, byte[] securityKey, SecurityTokenSettings settings, HashAlgorithmType algorithmType, string secureUriFormat, string querystringParameterHashName) { Validator.ThrowIfNullOrEmpty(uriLocation, nameof(uriLocation)); Validator.ThrowIfNull(securityKey, nameof(securityKey)); Validator.ThrowIfNull(settings, nameof(settings)); Validator.ThrowIfEqual(securityKey.Length, 0, nameof(securityKey)); Validator.ThrowIfNullOrEmpty(secureUriFormat, nameof(secureUriFormat)); int foundArguments; if (!StringUtility.ParseFormat(secureUriFormat, 3, out foundArguments)) { throw new ArgumentException("You must - in this order - specify three arguments for; 'token', 'iv' and 'salt'. This value cannot be exceeded nor the opposite. 'token', 'iv' and 'salt' is the default values."); } NameValueCollection formatedQuerytring = QueryStringConverter.FromString(secureUriFormat); SecurityToken securityToken = SecurityToken.Create(settings); byte[] iv = AdvancedEncryptionStandardUtility.GenerateInitializationVector(); byte[] encryptedSecurityToken = SecurityUtility.CreateEncryptedSecurityToken(securityToken, securityKey, iv); string ivAsString = HttpUtility.UrlEncode(Encoding.UTF8.GetString(iv, 0, iv.Length)); string encryptedSecurityTokenAsString = HttpUtility.UrlEncode(Convert.ToBase64String(encryptedSecurityToken)); string salt = HttpUtility.UrlEncode(StringUtility.CreateRandomString(18)); int indexOfQuestionMark = uriLocation.IndexOf('?'); string uriLocationQuerystring = indexOfQuestionMark > 0 ? uriLocation.Substring(indexOfQuestionMark) : ""; uriLocation = indexOfQuestionMark > 0 ? uriLocation.Substring(0, indexOfQuestionMark) : uriLocation; NameValueCollection querystring = QueryStringConverter.FromString(uriLocationQuerystring); NameValueCollection secureQuerystring = QueryStringConverter.FromString(string.Format(CultureInfo.InvariantCulture, secureUriFormat, encryptedSecurityTokenAsString, ivAsString, salt)); secureQuerystring.Add(querystring); querystring = QueryStringUtility.RemoveDublets(secureQuerystring, formatedQuerytring.AllKeys); string secureUri = string.Format(CultureInfo.InvariantCulture, "{0}{1}", uriLocation, QueryStringConverter.FromNameValueCollection(querystring)); secureUri += string.Format(CultureInfo.InvariantCulture, "&{0}={1}", querystringParameterHashName, HashUtility.ComputeHash(secureUri + salt + securityToken.Token, o => { o.AlgorithmType = algorithmType; o.Encoding = Encoding.UTF8; }).ToHexadecimal()); return(new Uri(secureUri)); }
public void GetAccess_ReturnsAccessTypes() { AccessType[] expectedAccessTypes = new AccessType[1]; SecurityToken token = SecurityToken.Create( PrincipalTestHelper.Create(_tenant, null, new Role[0]), null, null, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >()); var aclHandle = CreateAccessControlListHandle(); Expect.Call(_mockAclFinder.Find(_context)).Return(aclHandle); Expect.Call(_mockTokenBuilder.CreateToken(_principalStub, _context)).Return(token); Expect.Call(_mockAccessResolver.GetAccessTypes(aclHandle, token)).Return(expectedAccessTypes); _mocks.ReplayAll(); AccessType[] actualAccessTypes = _service.GetAccess(_context, _principalStub); Assert.That(actualAccessTypes, Is.SameAs(expectedAccessTypes)); }
public void Initialize_Values() { Tenant principalTenant = CreateTenant("principalTenant"); Principal principal = PrincipalTestHelper.Create(principalTenant, null, new Role[0]); Tenant owningTenant = CreateTenant("owningTenant"); Group owningGroup = CreateGroup("owningGroup", null, owningTenant); User owningUser = CreateUser("owningUser", CreateGroup("owningUserGroup", null, owningTenant), owningTenant); AbstractRoleDefinition abstractRole1 = AbstractRoleDefinition.NewObject(Guid.NewGuid(), "role1", 0); AbstractRoleDefinition abstractRole2 = AbstractRoleDefinition.NewObject(Guid.NewGuid(), "role2", 1); SecurityToken token = SecurityToken.Create( principal, owningTenant, owningGroup, owningUser, new[] { abstractRole1.GetHandle(), abstractRole2.GetHandle() }); Assert.That(token.Principal, Is.SameAs(principal)); Assert.That(token.OwningTenant, Is.EqualTo(owningTenant).Using(DomainObjectHandleComparer.Instance)); Assert.That(token.OwningGroup, Is.EqualTo(owningGroup).Using(DomainObjectHandleComparer.Instance)); Assert.That(token.OwningUser, Is.EqualTo(owningUser).Using(DomainObjectHandleComparer.Instance)); Assert.That(token.AbstractRoles, Is.EquivalentTo(new[] { abstractRole1, abstractRole2 }).Using(DomainObjectHandleComparer.Instance)); }
public SecurityToken CreateTokenWithNullPrincipal() { return(SecurityToken.Create(Principal.Null, null, null, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >())); }
public SecurityToken CreateTokenWithoutUser() { Principal principal = PrincipalTestHelper.Create(CreateTenant("AnyTenant"), null, new Role[0]); return(SecurityToken.Create(principal, null, null, null, Enumerable.Empty <IDomainObjectHandle <AbstractRoleDefinition> >())); }
public SecurityToken CreateTokenWithAbstractRole(params AbstractRoleDefinition[] roleDefinitions) { Principal principal = PrincipalTestHelper.Create(CreateTenant("AnyTenant"), null, new Role[0]); return(SecurityToken.Create(principal, null, null, null, roleDefinitions.Select(abstractRole => abstractRole.GetHandle()))); }