Search in sources :

Example 16 with ValuePolicyType

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

the class ModelInteractionServiceImpl method validateValue.

private <T, O extends ObjectType> boolean validateValue(PrismObject<O> object, ValuePolicyType policy, PolicyItemDefinitionType policyItemDefinition, Task task, OperationResult parentResult) throws ExpressionEvaluationException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, PolicyViolationException {
    ValuePolicyType stringPolicy = resolveValuePolicy(policyItemDefinition, policy, task, parentResult);
    RawType rawValue = (RawType) policyItemDefinition.getValue();
    String valueToValidate = null;
    List<String> valuesToValidate = new ArrayList<>();
    PolicyItemTargetType target = policyItemDefinition.getTarget();
    ItemPath path = null;
    if (target != null) {
        path = target.getPath().getItemPath();
    }
    if (rawValue != null) {
        valueToValidate = rawValue.getParsedRealValue(String.class);
        valuesToValidate.add(valueToValidate);
    } else {
        if (target == null || target.getPath() == null) {
            LOGGER.error("Target item path must be defined");
            parentResult.recordFatalError("Target item path must be defined");
            throw new SchemaException("Target item path must be defined");
        }
        path = target.getPath().getItemPath();
        PrismProperty<T> property = object.findProperty(path);
        if (property == null || property.isEmpty()) {
            LOGGER.error("Attribute {} has no value. Nothing to validate.", property);
            parentResult.recordFatalError("Attribute " + property + " has no value. Nothing to validate");
            throw new SchemaException("Attribute " + property + " has no value. Nothing to validate");
        }
        PrismPropertyDefinition<T> itemToValidateDefinition = property.getDefinition();
        QName definitionName = itemToValidateDefinition.getTypeName();
        if (!isSupportedType(definitionName)) {
            LOGGER.error("Trying to validate string policy on the property of type {} failed. Unsupported type.", itemToValidateDefinition);
            parentResult.recordFatalError("Trying to validate string policy on the property of type " + itemToValidateDefinition + " failed. Unsupported type.");
            throw new SchemaException("Trying to validate string policy on the property of type " + itemToValidateDefinition + " failed. Unsupported type.");
        }
        if (itemToValidateDefinition.isSingleValue()) {
            if (definitionName.equals(PolyStringType.COMPLEX_TYPE)) {
                valueToValidate = ((PolyString) property.getRealValue()).getOrig();
            } else if (definitionName.equals(ProtectedStringType.COMPLEX_TYPE)) {
                ProtectedStringType protectedString = ((ProtectedStringType) property.getRealValue());
                valueToValidate = getClearValue(protectedString);
            } else {
                valueToValidate = (String) property.getRealValue();
            }
            valuesToValidate.add(valueToValidate);
        } else {
            if (definitionName.equals(DOMUtil.XSD_STRING)) {
                valuesToValidate.addAll(property.getRealValues(String.class));
            } else if (definitionName.equals(ProtectedStringType.COMPLEX_TYPE)) {
                for (ProtectedStringType protectedString : property.getRealValues(ProtectedStringType.class)) {
                    valuesToValidate.add(getClearValue(protectedString));
                }
            } else {
                for (PolyString val : property.getRealValues(PolyString.class)) {
                    valuesToValidate.add(val.getOrig());
                }
            }
        }
    }
    for (String newValue : valuesToValidate) {
        OperationResult result = parentResult.createSubresult(OPERATION_VALIDATE_VALUE + ".value");
        if (path != null)
            result.addParam("path", path);
        result.addParam("valueToValidate", newValue);
        if (!policyProcessor.validateValue(newValue, stringPolicy, object, "validate value " + (path != null ? "for " + path : "") + " for " + object + " value " + valueToValidate, task, result)) {
            result.recordFatalError("Validation for value " + newValue + " against policy " + stringPolicy + " failed");
            LOGGER.error("Validation for value {} against policy {} failed", newValue, stringPolicy);
        }
        result.computeStatusIfUnknown();
    }
    parentResult.computeStatus();
    policyItemDefinition.setResult(parentResult.createOperationResultType());
    return parentResult.isAcceptable();
}
Also used : SchemaException(com.evolveum.midpoint.util.exception.SchemaException) QName(javax.xml.namespace.QName) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) PolyString(com.evolveum.midpoint.prism.polystring.PolyString) RawType(com.evolveum.prism.xml.ns._public.types_3.RawType) ProtectedStringType(com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType) PolicyItemTargetType(com.evolveum.midpoint.xml.ns._public.common.api_types_3.PolicyItemTargetType) ItemPath(com.evolveum.midpoint.prism.path.ItemPath)

Example 17 with ValuePolicyType

use of com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType 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 18 with ValuePolicyType

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

the class ValuePolicyProcessor method validateValue.

public <O extends ObjectType> boolean validateValue(String newValue, ValuePolicyType pp, PrismObject<O> object, StringBuilder message, String shortDesc, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException {
    Validate.notNull(pp, "Value policy must not be null.");
    OperationResult result = parentResult.createSubresult(OPERATION_STRING_POLICY_VALIDATION);
    result.addParam("policyName", pp.getName());
    normalize(pp);
    if (newValue == null && (pp.getMinOccurs() == null || XsdTypeMapper.multiplicityToInteger(pp.getMinOccurs()) == 0)) {
        // No password is allowed
        result.recordSuccess();
        return true;
    }
    if (newValue == null) {
        newValue = "";
    }
    LimitationsType lims = pp.getStringPolicy().getLimitations();
    testMinimalLength(newValue, lims, result, message);
    testMaximalLength(newValue, lims, result, message);
    testMinimalUniqueCharacters(newValue, lims, result, message);
    if (lims.getLimit() == null || lims.getLimit().isEmpty()) {
        if (message.toString() == null || message.toString().isEmpty()) {
            result.computeStatus();
        } else {
            result.computeStatus(message.toString());
        }
        return result.isAcceptable();
    }
    // check limitation
    HashSet<String> validChars = null;
    HashSet<String> allValidChars = new HashSet<>();
    List<String> passwd = StringPolicyUtils.stringTokenizer(newValue);
    for (StringLimitType stringLimitationType : lims.getLimit()) {
        OperationResult limitResult = new OperationResult("Tested limitation: " + stringLimitationType.getDescription());
        validChars = getValidCharacters(stringLimitationType.getCharacterClass(), pp);
        int count = countValidCharacters(validChars, passwd);
        allValidChars.addAll(validChars);
        testMinimalOccurence(stringLimitationType, count, limitResult, message);
        testMaximalOccurence(stringLimitationType, count, limitResult, message);
        testMustBeFirst(stringLimitationType, count, limitResult, message, newValue, validChars);
        limitResult.computeStatus();
        result.addSubresult(limitResult);
    }
    testInvalidCharacters(passwd, allValidChars, result, message);
    testCheckExpression(newValue, lims, object, shortDesc, task, result, message);
    if (message.toString() == null || message.toString().isEmpty()) {
        result.computeStatus();
    } else {
        result.computeStatus(message.toString());
    }
    return result.isAcceptable();
}
Also used : StringLimitType(com.evolveum.midpoint.xml.ns._public.common.common_3.StringLimitType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) LimitationsType(com.evolveum.midpoint.xml.ns._public.common.common_3.LimitationsType) HashSet(java.util.HashSet)

Example 19 with ValuePolicyType

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

the class RValuePolicy method toJAXB.

@Override
public ValuePolicyType toJAXB(PrismContext prismContext, Collection<SelectorOptions<GetOperationOptions>> options) throws DtoTranslationException {
    ValuePolicyType policy = new ValuePolicyType();
    RUtil.revive(policy, prismContext);
    RValuePolicy.copyToJAXB(this, policy, prismContext, options);
    return policy;
}
Also used : ValuePolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType)

Example 20 with ValuePolicyType

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

the class TestPasswordPolicy method passwordGeneratorTest.

public void passwordGeneratorTest(final String TEST_NAME, String policyFilename) throws JAXBException, SchemaException, IOException, ExpressionEvaluationException, ObjectNotFoundException {
    TestUtil.displayTestTile(TEST_NAME);
    Task task = createTask(TEST_NAME);
    OperationResult result = task.getResult();
    File file = new File(TEST_DIR, policyFilename);
    LOGGER.info("Positive testing {}: {}", TEST_NAME, policyFilename);
    ValuePolicyType pp = (ValuePolicyType) PrismTestUtil.parseObject(file).asObjectable();
    String psswd;
    // generate minimal size passwd
    for (int i = 0; i < 100; i++) {
        psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp.getStringPolicy(), 10, true, null, TEST_NAME, task, result);
        LOGGER.info("Generated password:" + psswd);
        result.computeStatus();
        if (!result.isSuccess()) {
            LOGGER.info("Result:" + result.debugDump());
            AssertJUnit.fail("Password generator failed:\n" + result.debugDump());
        }
        assertNotNull(psswd);
        assertPassword(psswd, pp);
    }
    // genereata to meet as possible
    LOGGER.info("-------------------------");
    // Generate up to possible
    for (int i = 0; i < 100; i++) {
        psswd = valuePolicyProcessor.generate(SchemaConstants.PATH_PASSWORD_VALUE, pp.getStringPolicy(), 10, false, null, TEST_NAME, task, result);
        LOGGER.info("Generated password:" + psswd);
        result.computeStatus();
        if (!result.isSuccess()) {
            LOGGER.info("Result:" + result.debugDump());
        }
        AssertJUnit.assertTrue(result.isSuccess());
        assertNotNull(psswd);
    }
}
Also used : Task(com.evolveum.midpoint.task.api.Task) ValuePolicyType(com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType) OperationResult(com.evolveum.midpoint.schema.result.OperationResult) File(java.io.File)

Aggregations

ValuePolicyType (com.evolveum.midpoint.xml.ns._public.common.common_3.ValuePolicyType)35 OperationResult (com.evolveum.midpoint.schema.result.OperationResult)19 Test (org.testng.annotations.Test)14 Task (com.evolveum.midpoint.task.api.Task)12 AbstractInternalModelIntegrationTest (com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest)10 ItemPath (com.evolveum.midpoint.prism.path.ItemPath)8 ObjectReferenceType (com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType)8 SchemaException (com.evolveum.midpoint.util.exception.SchemaException)7 File (java.io.File)7 ExpressionEvaluationException (com.evolveum.midpoint.util.exception.ExpressionEvaluationException)6 ObjectNotFoundException (com.evolveum.midpoint.util.exception.ObjectNotFoundException)6 StringPolicyType (com.evolveum.midpoint.xml.ns._public.common.common_3.StringPolicyType)6 PrismObject (com.evolveum.midpoint.prism.PrismObject)5 UserType (com.evolveum.midpoint.xml.ns._public.common.common_3.UserType)5 PrismPropertyValue (com.evolveum.midpoint.prism.PrismPropertyValue)4 PolyString (com.evolveum.midpoint.prism.polystring.PolyString)4 StringPolicyResolver (com.evolveum.midpoint.repo.common.expression.StringPolicyResolver)4 ProtectedStringType (com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType)4 ItemDefinition (com.evolveum.midpoint.prism.ItemDefinition)3 PrismContext (com.evolveum.midpoint.prism.PrismContext)3