Search in sources :

Example 6 with StringPolicyType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType in project midpoint by Evolveum.

the class GenerateExpressionEvaluator method evaluate.

/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.evolveum.midpoint.common.expression.ExpressionEvaluator#evaluate(java
	 * .util.Collection, java.util.Map, boolean, java.lang.String,
	 * com.evolveum.midpoint.schema.result.OperationResult)
	 */
@Override
public PrismValueDeltaSetTriple<V> evaluate(ExpressionEvaluationContext context) throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException {
    StringPolicyType stringPolicyType = null;
    ObjectReferenceType generateEvaluatorValuePolicyRef = generateEvaluatorType.getValuePolicyRef();
    if (generateEvaluatorValuePolicyRef != null) {
        if (generateEvaluatorType.getValuePolicyRef() != null) {
            ValuePolicyType valuePolicyType = objectResolver.resolve(generateEvaluatorValuePolicyRef, ValuePolicyType.class, null, "resolving value policy reference in generateExpressionEvaluator", context.getTask(), context.getResult());
            stringPolicyType = valuePolicyType.getStringPolicy();
        }
    }
    // would be generated
    if (stringPolicyType == null) {
        StringPolicyResolver stringPolicyResolver = context.getStringPolicyResolver();
        if (stringPolicyResolver != null) {
            stringPolicyType = stringPolicyResolver.resolve();
        }
    }
    elementStringPolicy = stringPolicyType;
    // } else {
    // stringPolicyType = elementStringPolicy;
    // }
    //
    String stringValue = null;
    GenerateExpressionEvaluatorModeType mode = generateEvaluatorType.getMode();
    Item<V, D> output = outputDefinition.instantiate();
    if (mode == null || mode == GenerateExpressionEvaluatorModeType.POLICY) {
        PrismObject<? extends ObjectType> object = getObject(context);
        // TODO: generate value based on stringPolicyType (if not null)
        if (stringPolicyType != null) {
            if (isNotEmptyMinLength(stringPolicyType)) {
                stringValue = valuePolicyGenerator.generate(output.getPath(), stringPolicyType, DEFAULT_LENGTH, true, object, context.getContextDescription(), context.getTask(), context.getResult());
            } else {
                stringValue = valuePolicyGenerator.generate(output.getPath(), stringPolicyType, DEFAULT_LENGTH, false, object, context.getContextDescription(), context.getTask(), context.getResult());
            }
            context.getResult().computeStatus();
            if (context.getResult().isError()) {
                throw new ExpressionEvaluationException("Failed to generate value according to policy: " + stringPolicyType.getDescription() + ". " + context.getResult().getMessage());
            }
        }
        if (stringValue == null) {
            int length = DEFAULT_LENGTH;
            RandomString randomString = new RandomString(length);
            stringValue = randomString.nextString();
        }
    } else if (mode == GenerateExpressionEvaluatorModeType.UUID) {
        UUID randomUUID = UUID.randomUUID();
        stringValue = randomUUID.toString();
    } else {
        throw new ExpressionEvaluationException("Unknown mode for generate expression: " + mode);
    }
    Object value = ExpressionUtil.convertToOutputValue(stringValue, outputDefinition, protector);
    if (output instanceof PrismProperty) {
        PrismPropertyValue<Object> pValue = new PrismPropertyValue<Object>(value);
        ((PrismProperty<Object>) output).add(pValue);
    } else {
        throw new UnsupportedOperationException("Can only generate values of property, not " + output.getClass());
    }
    return ItemDelta.toDeltaSetTriple(output, null);
}
Also used : StringPolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType) ExpressionEvaluationException(com.evolveum.midpoint.util.exception.ExpressionEvaluationException) ValuePolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType) UUID(java.util.UUID) RandomString(com.evolveum.midpoint.util.RandomString) StringPolicyResolver(com.evolveum.midpoint.repo.common.expression.StringPolicyResolver) RandomString(com.evolveum.midpoint.util.RandomString) ObjectReferenceType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType) PrismProperty(com.evolveum.midpoint.prism.PrismProperty) PrismObject(com.evolveum.midpoint.prism.PrismObject) UUID(java.util.UUID) GenerateExpressionEvaluatorModeType(com.evolveum.midpoint.xml.ns._public.common.common_3.GenerateExpressionEvaluatorModeType) PrismPropertyValue(com.evolveum.midpoint.prism.PrismPropertyValue)

Example 7 with StringPolicyType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType in project midpoint by Evolveum.

the class StringPolicyUtils method normalize.

public static StringPolicyType normalize(StringPolicyType sp) {
    if (null == sp) {
        throw new IllegalArgumentException("Providide string policy cannot be null");
    }
    if (null == sp.getLimitations()) {
        LimitationsType sl = new LimitationsType();
        sl.setCheckAgainstDictionary(false);
        sl.setCheckPattern("");
        sl.setMaxLength(-1);
        sl.setMinLength(0);
        sl.setMinUniqueChars(0);
        sp.setLimitations(sl);
    }
    // Add default char class
    if (null == sp.getCharacterClass()) {
        CharacterClassType cct = new CharacterClassType();
        cct.setValue(ASCII7_CHARS);
        sp.setCharacterClass(cct);
    }
    return sp;
}
Also used : CharacterClassType(com.evolveum.midpoint.xml.ns._public.common.common_3.CharacterClassType) LimitationsType(com.evolveum.midpoint.xml.ns._public.common.common_3.LimitationsType)

Example 8 with StringPolicyType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType in project midpoint by Evolveum.

the class ValuePolicyProcessor method generateAttempt.

private String generateAttempt(StringPolicyType policy, int defaultLength, boolean generateMinimalSize, OperationResult result) {
    // if (policy.getLimitations() != null &&
    // policy.getLimitations().getMinLength() != null){
    // generateMinimalSize = true;
    // }
    // setup default values where missing
    // PasswordPolicyUtils.normalize(pp);
    // Optimize usage of limits ass hashmap of limitas and key is set of
    // valid chars for each limitation
    Map<StringLimitType, List<String>> lims = new HashMap<StringLimitType, List<String>>();
    int minLen = defaultLength;
    int maxLen = defaultLength;
    int unique = defaultLength / 2;
    if (policy != null) {
        for (StringLimitType l : policy.getLimitations().getLimit()) {
            if (null != l.getCharacterClass().getValue()) {
                lims.put(l, StringPolicyUtils.stringTokenizer(l.getCharacterClass().getValue()));
            } else {
                lims.put(l, StringPolicyUtils.stringTokenizer(StringPolicyUtils.collectCharacterClass(policy.getCharacterClass(), l.getCharacterClass().getRef())));
            }
        }
        // Get global limitations
        minLen = policy.getLimitations().getMinLength() == null ? 0 : policy.getLimitations().getMinLength().intValue();
        if (minLen != 0 && minLen > defaultLength) {
            defaultLength = minLen;
        }
        maxLen = (policy.getLimitations().getMaxLength() == null ? 0 : policy.getLimitations().getMaxLength().intValue());
        unique = policy.getLimitations().getMinUniqueChars() == null ? minLen : policy.getLimitations().getMinUniqueChars().intValue();
    }
    // test correctness of definition
    if (unique > minLen) {
        minLen = unique;
        OperationResult reportBug = new OperationResult("Global limitation check");
        reportBug.recordWarning("There is more required uniq characters then definied minimum. Raise minimum to number of required uniq chars.");
    }
    if (minLen == 0 && maxLen == 0) {
        minLen = defaultLength;
        maxLen = defaultLength;
        generateMinimalSize = true;
    }
    if (maxLen == 0) {
        if (minLen > defaultLength) {
            maxLen = minLen;
        } else {
            maxLen = defaultLength;
        }
    }
    // Initialize generator
    StringBuilder password = new StringBuilder();
    /*
		 * ********************************** Try to find best characters to be
		 * first in password
		 */
    Map<StringLimitType, List<String>> mustBeFirst = new HashMap<StringLimitType, List<String>>();
    for (StringLimitType l : lims.keySet()) {
        if (l.isMustBeFirst() != null && l.isMustBeFirst()) {
            mustBeFirst.put(l, lims.get(l));
        }
    }
    // If any limitation was found to be first
    if (!mustBeFirst.isEmpty()) {
        Map<Integer, List<String>> posibleFirstChars = cardinalityCounter(mustBeFirst, null, false, false, result);
        int intersectionCardinality = mustBeFirst.keySet().size();
        List<String> intersectionCharacters = posibleFirstChars.get(intersectionCardinality);
        // If no intersection was found then raise error
        if (null == intersectionCharacters || intersectionCharacters.size() == 0) {
            result.recordFatalError("No intersection for required first character sets in value policy:" + policy.getDescription());
            // Log error
            if (LOGGER.isErrorEnabled()) {
                LOGGER.error("Unable to generate value for " + getPath() + ": No intersection for required first character sets in value policy: [" + policy.getDescription() + "] following character limitation and sets are used:");
                for (StringLimitType l : mustBeFirst.keySet()) {
                    StrBuilder tmp = new StrBuilder();
                    tmp.appendSeparator(", ");
                    tmp.appendAll(mustBeFirst.get(l));
                    LOGGER.error("L:" + l.getDescription() + " -> [" + tmp + "]");
                }
            }
            // EXIT
            return null;
        } else {
            if (LOGGER.isDebugEnabled()) {
                StrBuilder tmp = new StrBuilder();
                tmp.appendSeparator(", ");
                tmp.appendAll(intersectionCharacters);
                LOGGER.trace("Generate first character intersection items [" + tmp + "] into " + getPath() + ".");
            }
            // Generate random char into password from intersection
            password.append(intersectionCharacters.get(RAND.nextInt(intersectionCharacters.size())));
        }
    }
    /*
		 * ************************************** Generate rest to fulfill
		 * minimal criteria
		 */
    boolean uniquenessReached = false;
    // Count cardinality of elements
    Map<Integer, List<String>> chars;
    for (int i = 0; i < minLen; i++) {
        // Check if still unique chars are needed
        if (password.length() >= unique) {
            uniquenessReached = true;
        }
        // Find all usable characters
        chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), false, uniquenessReached, result);
        // If something goes badly then go out
        if (null == chars) {
            return null;
        }
        if (chars.isEmpty()) {
            LOGGER.trace("Minimal criterias was met. No more characters");
            break;
        }
        // Find lowest possible cardinality and then generate char
        for (int card = 1; card < lims.keySet().size(); card++) {
            if (chars.containsKey(card)) {
                List<String> validChars = chars.get(card);
                password.append(validChars.get(RAND.nextInt(validChars.size())));
                break;
            }
        }
    }
    // test if maximum is not exceeded
    if (password.length() > maxLen) {
        result.recordFatalError("Unable to meet minimal criteria and not exceed maximxal size of " + getPath() + ".");
        return null;
    }
    for (int i = 0; i < minLen; i++) {
        // test if max is reached
        if (password.length() == maxLen) {
            // no more characters maximal size is reached
            break;
        }
        if (password.length() >= minLen && generateMinimalSize) {
            // no more characters are needed
            break;
        }
        // Check if still unique chars are needed
        if (password.length() >= unique) {
            uniquenessReached = true;
        }
        // find all usable characters
        chars = cardinalityCounter(lims, StringPolicyUtils.stringTokenizer(password.toString()), true, uniquenessReached, result);
        // If something goes badly then go out
        if (null == chars) {
            // we hope this never happend.
            result.recordFatalError("No valid characters to generate, but no all limitation are reached");
            return null;
        }
        // our work
        if (chars.isEmpty()) {
            if (i == 0) {
                password.append(RandomStringUtils.randomAlphanumeric(minLen));
            }
            break;
        // if (!StringUtils.isBlank(password.toString()) &&
        // password.length() >= minLen) {
        // break;
        // }
        // check uf this is a firs cycle and if we need to user some
        // default (alphanum) character class.
        }
        // Find lowest possible cardinality and then generate char
        for (int card = 1; card <= lims.keySet().size(); card++) {
            if (chars.containsKey(card)) {
                List<String> validChars = chars.get(card);
                password.append(validChars.get(RAND.nextInt(validChars.size())));
                break;
            }
        }
    }
    if (password.length() < minLen) {
        result.recordFatalError("Unable to generate value for " + getPath() + " and meet minimal size of " + getPath() + ". Actual lenght: " + password.length() + ", required: " + minLen);
        LOGGER.trace("Unable to generate value for " + getPath() + " and meet minimal size of " + getPath() + ". Actual lenght: {}, required: {}", password.length(), minLen);
        return null;
    }
    result.recordSuccess();
    // Shuffle output to solve pattern like output
    StrBuilder sb = new StrBuilder(password.substring(0, 1));
    List<String> shuffleBuffer = StringPolicyUtils.stringTokenizer(password.substring(1));
    Collections.shuffle(shuffleBuffer);
    sb.appendAll(shuffleBuffer);
    return sb.toString();
}
Also used : HashMap(java.util.HashMap) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) StringLimitType(com.evolveum.midpoint.xml.ns._public.common.common_3.StringLimitType) ArrayList(java.util.ArrayList) List(java.util.List) StrBuilder(org.apache.commons.lang.text.StrBuilder)

Example 9 with StringPolicyType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType in project midpoint by Evolveum.

the class OutboundProcessor method evaluateMapping.

private <F extends FocusType, V extends PrismValue, D extends ItemDefinition> Mapping<V, D> evaluateMapping(final Mapping.Builder<V, D> mappingBuilder, QName mappingQName, D targetDefinition, ObjectDeltaObject<F> focusOdo, ObjectDeltaObject<ShadowType> projectionOdo, String operation, RefinedObjectClassDefinition rOcDef, RefinedObjectClassDefinition assocTargetObjectClassDefinition, LensContext<F> context, LensProjectionContext projCtx, final Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException {
    if (!mappingBuilder.isApplicableToChannel(context.getChannel())) {
        LOGGER.trace("Skipping outbound mapping for {} because the channel does not match", mappingQName);
        return null;
    }
    // TODO: check access
    // This is just supposed to be an optimization. The consolidation should deal with the weak mapping
    // even if it is there. But in that case we do not need to evaluate it at all.
    // Edit 2017-02-16 pmed: It's not quite true. If the attribute is non-tolerant, it will get removed if we would
    // skip evaluation of this mapping. So we really need to do this.
    //		if (mappingBuilder.getStrength() == MappingStrengthType.WEAK && projCtx.hasValueForAttribute(mappingQName)) {
    //			LOGGER.trace("Skipping outbound mapping for {} because it is weak", mappingQName);
    //			return null;
    //		}
    mappingBuilder.setDefaultTargetDefinition(targetDefinition);
    mappingBuilder.setSourceContext(focusOdo);
    mappingBuilder.setMappingQName(mappingQName);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_USER, focusOdo);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_FOCUS, focusOdo);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ACCOUNT, projectionOdo);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_SHADOW, projectionOdo);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_PROJECTION, projectionOdo);
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_CONFIGURATION, context.getSystemConfiguration());
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ITERATION, LensUtil.getIterationVariableValue(projCtx));
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ITERATION_TOKEN, LensUtil.getIterationTokenVariableValue(projCtx));
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_RESOURCE, projCtx.getResource());
    mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_OPERATION, operation);
    if (assocTargetObjectClassDefinition != null) {
        mappingBuilder.addVariableDefinition(ExpressionConstants.VAR_ASSOCIATION_TARGET_OBJECT_CLASS_DEFINITION, assocTargetObjectClassDefinition);
    }
    mappingBuilder.setRootNode(focusOdo);
    mappingBuilder.setOriginType(OriginType.OUTBOUND);
    mappingBuilder.setRefinedObjectClassDefinition(rOcDef);
    StringPolicyResolver stringPolicyResolver = new StringPolicyResolver() {

        private ItemPath outputPath;

        private ItemDefinition outputDefinition;

        @Override
        public void setOutputPath(ItemPath outputPath) {
            this.outputPath = outputPath;
        }

        @Override
        public void setOutputDefinition(ItemDefinition outputDefinition) {
            this.outputDefinition = outputDefinition;
        }

        @Override
        public StringPolicyType resolve() {
            if (mappingBuilder.getMappingType().getExpression() != null) {
                List<JAXBElement<?>> evaluators = mappingBuilder.getMappingType().getExpression().getExpressionEvaluator();
                for (JAXBElement jaxbEvaluator : evaluators) {
                    Object object = jaxbEvaluator.getValue();
                    if (object instanceof GenerateExpressionEvaluatorType && ((GenerateExpressionEvaluatorType) object).getValuePolicyRef() != null) {
                        ObjectReferenceType ref = ((GenerateExpressionEvaluatorType) object).getValuePolicyRef();
                        try {
                            ValuePolicyType valuePolicyType = mappingBuilder.getObjectResolver().resolve(ref, ValuePolicyType.class, null, "resolving value policy for generate attribute " + outputDefinition.getName() + "value", task, new OperationResult("Resolving value policy"));
                            if (valuePolicyType != null) {
                                return valuePolicyType.getStringPolicy();
                            }
                        } catch (CommonException ex) {
                            throw new SystemException(ex.getMessage(), ex);
                        }
                    }
                }
            }
            return null;
        }
    };
    mappingBuilder.setStringPolicyResolver(stringPolicyResolver);
    // (e.g. in old values in ADD situations and new values in DELETE situations).
    if (focusOdo.getOldObject() == null) {
        mappingBuilder.setConditionMaskOld(false);
    }
    if (focusOdo.getNewObject() == null) {
        mappingBuilder.setConditionMaskNew(false);
    }
    Mapping<V, D> mapping = mappingBuilder.build();
    mappingEvaluator.evaluateMapping(mapping, context, projCtx, task, result);
    return mapping;
}
Also used : ValuePolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType) ItemDefinition(com.evolveum.midpoint.prism.ItemDefinition) StringPolicyResolver(com.evolveum.midpoint.repo.common.expression.StringPolicyResolver) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) JAXBElement(javax.xml.bind.JAXBElement) ObjectReferenceType(com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType) ObjectDeltaObject(com.evolveum.midpoint.repo.common.expression.ObjectDeltaObject) GenerateExpressionEvaluatorType(com.evolveum.midpoint.xml.ns._public.common.common_3.GenerateExpressionEvaluatorType) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 10 with StringPolicyType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType in project midpoint by Evolveum.

the class TestPasswordPolicy method stringPolicyUtilsMinimalTest.

@Test
public void stringPolicyUtilsMinimalTest() throws JAXBException, SchemaException, IOException {
    File file = new File(TEST_DIR, "password-policy-minimal.xml");
    ValuePolicyType pp = (ValuePolicyType) PrismTestUtil.parseObject(file).asObjectable();
    StringPolicyType sp = pp.getStringPolicy();
    StringPolicyUtils.normalize(sp);
    AssertJUnit.assertNotNull(sp.getCharacterClass());
    AssertJUnit.assertNotNull(sp.getLimitations().getLimit());
    AssertJUnit.assertTrue(-1 == sp.getLimitations().getMaxLength());
    AssertJUnit.assertTrue(0 == sp.getLimitations().getMinLength());
    AssertJUnit.assertTrue(0 == " !\"#$%&'()*+,-.01234567890:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~".compareTo(sp.getCharacterClass().getValue()));
}
Also used : StringPolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType) ValuePolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType) File(java.io.File) Test(org.testng.annotations.Test) AbstractInternalModelIntegrationTest(com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest)

Aggregations

StringPolicyType (com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType)8 ValuePolicyType (com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType)8 PrismPropertyValue (com.evolveum.midpoint.prism.PrismPropertyValue)7 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)7 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)7 PrismPropertyDefinition (com.evolveum.midpoint.prism.PrismPropertyDefinition)6 StringPolicyResolver (com.evolveum.midpoint.repo.common.expression.StringPolicyResolver)6 File (java.io.File)6 ItemDefinition (com.evolveum.midpoint.prism.ItemDefinition)5 PrismObject (com.evolveum.midpoint.prism.PrismObject)3 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)3 ObjectDeltaObject (com.evolveum.midpoint.repo.common.expression.ObjectDeltaObject)3 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)3 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)3 MappingType (com.evolveum.midpoint.xml.ns._public.common.common_3.MappingType)3 ObjectReferenceType (com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType)3 Test (org.testng.annotations.Test)3 AbstractInternalModelIntegrationTest (com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest)2 PrismProperty (com.evolveum.midpoint.prism.PrismProperty)2 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)2