Search in sources :

Example 1 with InvalidEntityException

use of org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException in project syncope by apache.

the class JPAUserDAO method enforcePolicies.

@Transactional(readOnly = true)
@Override
public Pair<Boolean, Boolean> enforcePolicies(final User user) {
    // ------------------------------
    // Verify password policies
    // ------------------------------
    LOG.debug("Password Policy enforcement");
    try {
        int maxPPSpecHistory = 0;
        for (PasswordPolicy policy : getPasswordPolicies(user)) {
            if (user.getPassword() == null && !policy.isAllowNullPassword()) {
                throw new PasswordPolicyException("Password mandatory");
            }
            for (Implementation impl : policy.getRules()) {
                Optional<PasswordRule> rule = ImplementationManager.buildPasswordRule(impl);
                if (rule.isPresent()) {
                    rule.get().enforce(user);
                }
            }
            if (user.verifyPasswordHistory(user.getClearPassword(), policy.getHistoryLength())) {
                throw new PasswordPolicyException("Password value was used in the past: not allowed");
            }
            if (policy.getHistoryLength() > maxPPSpecHistory) {
                maxPPSpecHistory = policy.getHistoryLength();
            }
        }
        // update user's password history with encrypted password
        if (maxPPSpecHistory > 0 && user.getPassword() != null && !user.getPasswordHistory().contains(user.getPassword())) {
            user.getPasswordHistory().add(user.getPassword());
        }
        // keep only the last maxPPSpecHistory items in user's password history
        if (maxPPSpecHistory < user.getPasswordHistory().size()) {
            for (int i = 0; i < user.getPasswordHistory().size() - maxPPSpecHistory; i++) {
                user.getPasswordHistory().remove(i);
            }
        }
    } catch (Exception e) {
        LOG.error("Invalid password for {}", user, e);
        throw new InvalidEntityException(User.class, EntityViolationType.InvalidPassword, e.getMessage());
    } finally {
        // password has been validated, let's remove its clear version
        user.removeClearPassword();
    }
    // ------------------------------
    // Verify account policies
    // ------------------------------
    LOG.debug("Account Policy enforcement");
    boolean suspend = false;
    boolean propagateSuspension = false;
    try {
        if (user.getUsername() == null) {
            throw new AccountPolicyException("Null username");
        }
        if (adminUser.equals(user.getUsername()) || anonymousUser.equals(user.getUsername())) {
            throw new AccountPolicyException("Not allowed: " + user.getUsername());
        }
        if (!USERNAME_PATTERN.matcher(user.getUsername()).matches()) {
            throw new AccountPolicyException("Character(s) not allowed");
        }
        for (AccountPolicy policy : getAccountPolicies(user)) {
            for (Implementation impl : policy.getRules()) {
                Optional<AccountRule> rule = ImplementationManager.buildAccountRule(impl);
                if (rule.isPresent()) {
                    rule.get().enforce(user);
                }
            }
            suspend |= user.getFailedLogins() != null && policy.getMaxAuthenticationAttempts() > 0 && user.getFailedLogins() > policy.getMaxAuthenticationAttempts() && !user.isSuspended();
            propagateSuspension |= policy.isPropagateSuspension();
        }
    } catch (Exception e) {
        LOG.error("Invalid username for {}", user, e);
        throw new InvalidEntityException(User.class, EntityViolationType.InvalidUsername, e.getMessage());
    }
    return ImmutablePair.of(suspend, propagateSuspension);
}
Also used : PasswordRule(org.apache.syncope.core.persistence.api.dao.PasswordRule) AccountRule(org.apache.syncope.core.persistence.api.dao.AccountRule) JPAUser(org.apache.syncope.core.persistence.jpa.entity.user.JPAUser) User(org.apache.syncope.core.persistence.api.entity.user.User) AccountPolicyException(org.apache.syncope.core.provisioning.api.utils.policy.AccountPolicyException) Implementation(org.apache.syncope.core.persistence.api.entity.Implementation) NoResultException(javax.persistence.NoResultException) AccountPolicyException(org.apache.syncope.core.provisioning.api.utils.policy.AccountPolicyException) PasswordPolicyException(org.apache.syncope.core.provisioning.api.utils.policy.PasswordPolicyException) DelegatedAdministrationException(org.apache.syncope.core.spring.security.DelegatedAdministrationException) InvalidEntityException(org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException) InvalidEntityException(org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException) AccountPolicy(org.apache.syncope.core.persistence.api.entity.policy.AccountPolicy) PasswordPolicyException(org.apache.syncope.core.provisioning.api.utils.policy.PasswordPolicyException) PasswordPolicy(org.apache.syncope.core.persistence.api.entity.policy.PasswordPolicy) Transactional(org.springframework.transaction.annotation.Transactional)

Example 2 with InvalidEntityException

use of org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException in project syncope by apache.

the class JPAUserDAO method doSave.

private Pair<User, Pair<Set<String>, Set<String>>> doSave(final User user) {
    // 1. save clear password value before save
    String clearPwd = user.getClearPassword();
    // 2. save and flush to trigger entity validation
    User merged = super.save(user);
    entityManager().flush();
    // 3. set back the sole clear password value
    JPAUser.class.cast(merged).setClearPassword(clearPwd);
    // 4. enforce password and account policies
    try {
        enforcePolicies(merged);
    } catch (InvalidEntityException e) {
        entityManager().remove(merged);
        throw e;
    }
    publisher.publishEvent(new AnyCreatedUpdatedEvent<>(this, merged, AuthContextUtils.getDomain()));
    roleDAO.refreshDynMemberships(merged);
    Pair<Set<String>, Set<String>> dynGroupMembs = groupDAO().refreshDynMemberships(merged);
    dynRealmDAO().refreshDynMemberships(merged);
    return Pair.of(merged, dynGroupMembs);
}
Also used : JPAUser(org.apache.syncope.core.persistence.jpa.entity.user.JPAUser) User(org.apache.syncope.core.persistence.api.entity.user.User) Set(java.util.Set) HashSet(java.util.HashSet) JPAUser(org.apache.syncope.core.persistence.jpa.entity.user.JPAUser) InvalidEntityException(org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException)

Example 3 with InvalidEntityException

use of org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException in project syncope by apache.

the class EntityValidationListener method validate.

@PrePersist
@PreUpdate
public void validate(final Object object) {
    final Validator validator = ApplicationContextProvider.getBeanFactory().getBean(Validator.class);
    Set<ConstraintViolation<Object>> violations = validator.validate(object);
    if (!violations.isEmpty()) {
        LOG.warn("Bean validation errors found: {}", violations);
        Class<?> entityInt = null;
        for (Class<?> interf : ClassUtils.getAllInterfaces(object.getClass())) {
            if (!Entity.class.equals(interf) && !AnnotatedEntity.class.equals(interf) && !ProvidedKeyEntity.class.equals(interf) && !Schema.class.equals(interf) && !Task.class.equals(interf) && !Policy.class.equals(interf) && !GroupableRelatable.class.equals(interf) && !Any.class.equals(interf) && !DynMembership.class.equals(interf) && Entity.class.isAssignableFrom(interf)) {
                entityInt = interf;
            }
        }
        throw new InvalidEntityException(entityInt == null ? "Entity" : entityInt.getSimpleName(), violations);
    }
}
Also used : ProvidedKeyEntity(org.apache.syncope.core.persistence.api.entity.ProvidedKeyEntity) Entity(org.apache.syncope.core.persistence.api.entity.Entity) AnnotatedEntity(org.apache.syncope.core.persistence.api.entity.AnnotatedEntity) ProvidedKeyEntity(org.apache.syncope.core.persistence.api.entity.ProvidedKeyEntity) Task(org.apache.syncope.core.persistence.api.entity.task.Task) GroupableRelatable(org.apache.syncope.core.persistence.api.entity.GroupableRelatable) DynMembership(org.apache.syncope.core.persistence.api.entity.DynMembership) ConstraintViolation(javax.validation.ConstraintViolation) Validator(javax.validation.Validator) InvalidEntityException(org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException) PrePersist(javax.persistence.PrePersist) PreUpdate(javax.persistence.PreUpdate)

Example 4 with InvalidEntityException

use of org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException in project syncope by apache.

the class UserTest method membershipWithAttrs.

@Test
public void membershipWithAttrs() {
    User user = userDAO.findByUsername("vivaldi");
    assertNotNull(user);
    assertTrue(user.getMemberships().isEmpty());
    // add 'obscure' to user (no membership): works because 'obscure' is from 'other', default class for USER
    UPlainAttr attr = entityFactory.newEntity(UPlainAttr.class);
    attr.setOwner(user);
    attr.setSchema(plainSchemaDAO.find("obscure"));
    attr.add("testvalue", anyUtilsFactory.getInstance(AnyTypeKind.USER));
    user.add(attr);
    // add 'obscure' to user (via 'artDirector' membership): does not work because 'obscure' is from 'other'
    // but 'artDirector' defines no type extension
    UMembership membership = entityFactory.newEntity(UMembership.class);
    membership.setLeftEnd(user);
    membership.setRightEnd(groupDAO.findByName("artDirector"));
    user.add(membership);
    attr = entityFactory.newEntity(UPlainAttr.class);
    attr.setOwner(user);
    attr.setMembership(membership);
    attr.setSchema(plainSchemaDAO.find("obscure"));
    attr.add("testvalue2", anyUtilsFactory.getInstance(AnyTypeKind.USER));
    user.add(attr);
    try {
        userDAO.save(user);
        fail("This should not happen");
    } catch (InvalidEntityException e) {
        assertNotNull(e);
    }
    // replace 'artDirector' with 'additional', which defines type extension with class 'other' and 'csv':
    // now it works
    membership = user.getMembership(groupDAO.findByName("artDirector").getKey()).get();
    user.remove(user.getPlainAttr("obscure", membership).get());
    user.getMemberships().remove(membership);
    membership.setLeftEnd(null);
    membership = entityFactory.newEntity(UMembership.class);
    membership.setLeftEnd(user);
    membership.setRightEnd(groupDAO.findByName("additional"));
    user.add(membership);
    attr = entityFactory.newEntity(UPlainAttr.class);
    attr.setOwner(user);
    attr.setMembership(membership);
    attr.setSchema(plainSchemaDAO.find("obscure"));
    attr.add("testvalue2", anyUtilsFactory.getInstance(AnyTypeKind.USER));
    user.add(attr);
    userDAO.save(user);
    userDAO.flush();
    user = userDAO.findByUsername("vivaldi");
    assertEquals(1, user.getMemberships().size());
    final UMembership newM = user.getMembership(groupDAO.findByName("additional").getKey()).get();
    assertEquals(1, user.getPlainAttrs(newM).size());
    assertNull(user.getPlainAttr("obscure").get().getMembership());
    assertEquals(2, user.getPlainAttrs("obscure").size());
    assertTrue(user.getPlainAttrs("obscure").contains(user.getPlainAttr("obscure").get()));
    assertTrue(user.getPlainAttrs("obscure").stream().anyMatch(plainAttr -> plainAttr.getMembership() == null));
    assertTrue(user.getPlainAttrs("obscure").stream().anyMatch(plainAttr -> newM.equals(plainAttr.getMembership())));
}
Also used : Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Date(java.util.Date) Assertions.assertNull(org.junit.jupiter.api.Assertions.assertNull) Autowired(org.springframework.beans.factory.annotation.Autowired) URelationship(org.apache.syncope.core.persistence.api.entity.user.URelationship) AnyTypeKind(org.apache.syncope.common.lib.types.AnyTypeKind) UPlainAttrValue(org.apache.syncope.core.persistence.api.entity.user.UPlainAttrValue) GroupDAO(org.apache.syncope.core.persistence.api.dao.GroupDAO) Assertions.assertFalse(org.junit.jupiter.api.Assertions.assertFalse) AnyObjectDAO(org.apache.syncope.core.persistence.api.dao.AnyObjectDAO) DerSchema(org.apache.syncope.core.persistence.api.entity.DerSchema) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) UMembership(org.apache.syncope.core.persistence.api.entity.user.UMembership) RelationshipTypeDAO(org.apache.syncope.core.persistence.api.dao.RelationshipTypeDAO) UserDAO(org.apache.syncope.core.persistence.api.dao.UserDAO) PlainSchemaDAO(org.apache.syncope.core.persistence.api.dao.PlainSchemaDAO) User(org.apache.syncope.core.persistence.api.entity.user.User) UUID(java.util.UUID) PlainAttrValueDAO(org.apache.syncope.core.persistence.api.dao.PlainAttrValueDAO) InvalidEntityException(org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException) Test(org.junit.jupiter.api.Test) List(java.util.List) DerSchemaDAO(org.apache.syncope.core.persistence.api.dao.DerSchemaDAO) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) AbstractTest(org.apache.syncope.core.persistence.jpa.AbstractTest) PlainAttrDAO(org.apache.syncope.core.persistence.api.dao.PlainAttrDAO) UPlainAttr(org.apache.syncope.core.persistence.api.entity.user.UPlainAttr) Transactional(org.springframework.transaction.annotation.Transactional) User(org.apache.syncope.core.persistence.api.entity.user.User) UMembership(org.apache.syncope.core.persistence.api.entity.user.UMembership) UPlainAttr(org.apache.syncope.core.persistence.api.entity.user.UPlainAttr) InvalidEntityException(org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException) Test(org.junit.jupiter.api.Test) AbstractTest(org.apache.syncope.core.persistence.jpa.AbstractTest)

Example 5 with InvalidEntityException

use of org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException in project syncope by apache.

the class DerSchemaTest method issueSYNCOPE418.

@Test
public void issueSYNCOPE418() {
    DerSchema schema = entityFactory.newEntity(DerSchema.class);
    schema.setKey("http://schemas.examples.org/security/authorization/organizationUnit");
    try {
        derSchemaDAO.save(schema);
        fail("This should not happen");
    } catch (InvalidEntityException e) {
        assertTrue(e.hasViolation(EntityViolationType.InvalidKey));
    }
}
Also used : DerSchema(org.apache.syncope.core.persistence.api.entity.DerSchema) InvalidEntityException(org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException) Test(org.junit.jupiter.api.Test) AbstractTest(org.apache.syncope.core.persistence.jpa.AbstractTest)

Aggregations

InvalidEntityException (org.apache.syncope.core.persistence.api.attrvalue.validation.InvalidEntityException)18 AbstractTest (org.apache.syncope.core.persistence.jpa.AbstractTest)13 Test (org.junit.jupiter.api.Test)13 User (org.apache.syncope.core.persistence.api.entity.user.User)6 Set (java.util.Set)4 PlainSchema (org.apache.syncope.core.persistence.api.entity.PlainSchema)4 Date (java.util.Date)3 Map (java.util.Map)2 ClientExceptionType (org.apache.syncope.common.lib.types.ClientExceptionType)2 EntityViolationType (org.apache.syncope.common.lib.types.EntityViolationType)2 DerSchema (org.apache.syncope.core.persistence.api.entity.DerSchema)2 Implementation (org.apache.syncope.core.persistence.api.entity.Implementation)2 Realm (org.apache.syncope.core.persistence.api.entity.Realm)2 ExternalResource (org.apache.syncope.core.persistence.api.entity.resource.ExternalResource)2 UPlainAttr (org.apache.syncope.core.persistence.api.entity.user.UPlainAttr)2 JPAUser (org.apache.syncope.core.persistence.jpa.entity.user.JPAUser)2 Transactional (org.springframework.transaction.annotation.Transactional)2 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1