use of com.evolveum.midpoint.model.impl.lens.LensFocusContext in project midpoint by Evolveum.
the class ProjectionCredentialsProcessor method processProjectionPasswordMapping.
private <F extends FocusType> void processProjectionPasswordMapping(LensContext<F> context, final LensProjectionContext projCtx, final ValuePolicyType passwordPolicy, XMLGregorianCalendar now, Task task, OperationResult result) throws ExpressionEvaluationException, ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException {
LensFocusContext<F> focusContext = context.getFocusContext();
PrismObject<F> userNew = focusContext.getObjectNew();
if (userNew == null) {
// This must be a user delete or something similar. No point in proceeding
LOGGER.trace("userNew is null, skipping credentials processing");
return;
}
PrismObjectDefinition<ShadowType> accountDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(ShadowType.class);
PrismPropertyDefinition<ProtectedStringType> projPasswordPropertyDefinition = accountDefinition.findPropertyDefinition(SchemaConstants.PATH_PASSWORD_VALUE);
ResourceShadowDiscriminator rsd = projCtx.getResourceShadowDiscriminator();
RefinedObjectClassDefinition refinedProjDef = projCtx.getStructuralObjectClassDefinition();
if (refinedProjDef == null) {
LOGGER.trace("No RefinedObjectClassDefinition, therefore also no password outbound definition, skipping credentials processing for projection {}", rsd);
return;
}
List<MappingType> outboundMappingTypes = refinedProjDef.getPasswordOutbound();
if (outboundMappingTypes == null || outboundMappingTypes.isEmpty()) {
LOGGER.trace("No outbound password mapping for {}, skipping credentials processing", rsd);
return;
}
// HACK
if (!projCtx.isDoReconciliation() && !projCtx.isAdd() && !isActivated(outboundMappingTypes, focusContext.getDelta())) {
LOGGER.trace("Outbound password mappings not activated for type {}, skipping credentials processing", rsd);
return;
}
final ObjectDelta<ShadowType> projDelta = projCtx.getDelta();
final PropertyDelta<ProtectedStringType> projPasswordDelta;
if (projDelta != null && projDelta.getChangeType() == MODIFY) {
projPasswordDelta = projDelta.findPropertyDelta(SchemaConstants.PATH_PASSWORD_VALUE);
} else {
projPasswordDelta = null;
}
checkExistingDeltaSanity(projCtx, projPasswordDelta);
boolean evaluateWeak = getEvaluateWeak(projCtx);
final ItemDeltaItem<PrismPropertyValue<PasswordType>, PrismPropertyDefinition<ProtectedStringType>> userPasswordIdi = focusContext.getObjectDeltaObject().findIdi(SchemaConstants.PATH_PASSWORD_VALUE);
StringPolicyResolver stringPolicyResolver = new StringPolicyResolver() {
@Override
public void setOutputPath(ItemPath outputPath) {
}
@Override
public void setOutputDefinition(ItemDefinition outputDefinition) {
}
@Override
public StringPolicyType resolve() {
if (passwordPolicy == null) {
return null;
}
return passwordPolicy.getStringPolicy();
}
};
MappingInitializer<PrismPropertyValue<ProtectedStringType>, PrismPropertyDefinition<ProtectedStringType>> initializer = (builder) -> {
builder.defaultTargetDefinition(projPasswordPropertyDefinition);
builder.defaultSource(new Source<>(userPasswordIdi, ExpressionConstants.VAR_INPUT));
builder.stringPolicyResolver(stringPolicyResolver);
return builder;
};
MappingOutputProcessor<PrismPropertyValue<ProtectedStringType>> processor = (mappingOutputPath, outputStruct) -> {
PrismValueDeltaSetTriple<PrismPropertyValue<ProtectedStringType>> outputTriple = outputStruct.getOutputTriple();
if (outputTriple == null) {
LOGGER.trace("Credentials 'password' expression resulted in null output triple, skipping credentials processing for {}", rsd);
return false;
}
boolean projectionIsNew = projDelta != null && (projDelta.getChangeType() == ChangeType.ADD || projCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.ADD);
Collection<PrismPropertyValue<ProtectedStringType>> newValues = outputTriple.getPlusSet();
if (projectionIsNew) {
newValues = outputTriple.getNonNegativeValues();
} else {
newValues = outputTriple.getPlusSet();
}
if (!canGetCleartext(newValues)) {
ObjectDelta<ShadowType> projectionPrimaryDelta = projCtx.getPrimaryDelta();
if (projectionPrimaryDelta != null) {
PropertyDelta<ProtectedStringType> passwordPrimaryDelta = projectionPrimaryDelta.findPropertyDelta(SchemaConstants.PATH_PASSWORD_VALUE);
if (passwordPrimaryDelta != null) {
// We have only hashed value coming from the mapping. There are not very useful
// for provisioning. But we have primary projection delta - and that is very likely
// to be better.
// Skip all password mappings in this case. Primary delta trumps everything.
// No weak, normal or even strong mapping can change that.
// We need to disregard even strong mapping in this case. If we would heed the strong
// mapping then account initialization won't be possible.
LOGGER.trace("We have primary password delta in projection, skipping credentials processing");
return false;
}
}
}
return true;
};
mappingEvaluator.evaluateOutboundMapping(context, projCtx, outboundMappingTypes, SchemaConstants.PATH_PASSWORD_VALUE, SchemaConstants.PATH_PASSWORD_VALUE, initializer, processor, now, true, evaluateWeak, "password mapping", task, result);
}
use of com.evolveum.midpoint.model.impl.lens.LensFocusContext in project midpoint by Evolveum.
the class AssignmentProcessor method setReferences.
private <F extends ObjectType> void setReferences(LensFocusContext<F> focusContext, QName itemName, Collection<PrismReferenceValue> targetState) throws SchemaException {
PrismObject<F> focusOld = focusContext.getObjectOld();
if (focusOld == null) {
if (targetState.isEmpty()) {
return;
}
} else {
PrismReference existingState = focusOld.findReference(itemName);
if (existingState == null || existingState.isEmpty()) {
if (targetState.isEmpty()) {
return;
}
} else {
// we don't use QNameUtil.match here, because we want to ensure we store qualified values there
// (and newValues are all qualified)
Comparator<PrismReferenceValue> comparator = (a, b) -> 2 * a.getOid().compareTo(b.getOid()) + (Objects.equals(a.getRelation(), b.getRelation()) ? 0 : 1);
if (MiscUtil.unorderedCollectionCompare(targetState, existingState.getValues(), comparator)) {
return;
}
}
}
PrismReferenceDefinition itemDef = focusContext.getObjectDefinition().findItemDefinition(itemName, PrismReferenceDefinition.class);
ReferenceDelta itemDelta = new ReferenceDelta(itemName, itemDef, focusContext.getObjectDefinition().getPrismContext());
itemDelta.setValuesToReplace(targetState);
focusContext.swallowToSecondaryDelta(itemDelta);
}
use of com.evolveum.midpoint.model.impl.lens.LensFocusContext in project midpoint by Evolveum.
the class ContextLoader method loadFullShadow.
public <F extends ObjectType> void loadFullShadow(LensContext<F> context, LensProjectionContext projCtx, String reason, Task task, OperationResult result) throws ObjectNotFoundException, CommunicationException, SchemaException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException {
if (projCtx.isFullShadow()) {
// already loaded
return;
}
if (projCtx.isAdd() && projCtx.getOid() == null) {
// nothing to load yet
return;
}
if (projCtx.isThombstone()) {
// loading is futile
return;
}
ResourceShadowDiscriminator discr = projCtx.getResourceShadowDiscriminator();
if (discr != null && discr.getOrder() > 0) {
// It may be just too early to load the projection
if (LensUtil.hasLowerOrderContext(context, projCtx) && (context.getExecutionWave() < projCtx.getWave())) {
// We cannot reliably load the context now
return;
}
}
GetOperationOptions getOptions = GetOperationOptions.createAllowNotFound();
getOptions.setPointInTimeType(PointInTimeType.FUTURE);
if (SchemaConstants.CHANGE_CHANNEL_DISCOVERY_URI.equals(context.getChannel())) {
LOGGER.trace("Loading full resource object {} from provisioning - with doNotDiscover to avoid loops; reason: {}", projCtx, reason);
// Avoid discovery loops
getOptions.setDoNotDiscovery(true);
} else {
LOGGER.trace("Loading full resource object {} from provisioning (discovery enabled), reason: {}, channel: {}", projCtx, reason, context.getChannel());
}
try {
Collection<SelectorOptions<GetOperationOptions>> options = SelectorOptions.createCollection(getOptions);
applyAttributesToGet(projCtx, options);
PrismObject<ShadowType> objectCurrent = provisioningService.getObject(ShadowType.class, projCtx.getOid(), options, task, result);
Validate.notNull(objectCurrent.getOid());
// TODO: use setLoadedObject() instead?
projCtx.setObjectCurrent(objectCurrent);
ShadowType oldShadow = objectCurrent.asObjectable();
projCtx.determineFullShadowFlag(oldShadow.getFetchResult());
// The getObject may return different OID than we have requested in case that compensation happened
// TODO: this probably need to be fixed in the consistency mechanism
// TODO: the following line is a temporary fix
projCtx.setOid(objectCurrent.getOid());
} catch (ObjectNotFoundException ex) {
LOGGER.trace("Load of full resource object {} ended with ObjectNotFoundException (options={})", projCtx, getOptions);
if (projCtx.isDelete()) {
//this is OK, shadow was deleted, but we will continue in processing with old shadow..and set it as full so prevent from other full loading
projCtx.setFullShadow(true);
} else {
boolean compensated = false;
if (!GetOperationOptions.isDoNotDiscovery(getOptions)) {
// The account might have been re-created by the discovery.
// Reload focus, try to find out if there is a new matching link (and the old is gone)
LensFocusContext<F> focusContext = context.getFocusContext();
if (focusContext != null) {
Class<F> focusClass = focusContext.getObjectTypeClass();
if (FocusType.class.isAssignableFrom(focusClass)) {
LOGGER.trace("Reloading focus to check for new links");
PrismObject<F> focusCurrent = cacheRepositoryService.getObject(focusContext.getObjectTypeClass(), focusContext.getOid(), null, result);
FocusType focusType = (FocusType) focusCurrent.asObjectable();
for (ObjectReferenceType linkRef : focusType.getLinkRef()) {
if (linkRef.getOid().equals(projCtx.getOid())) {
// The deleted shadow is still in the linkRef. This should not happen, but it obviously happens sometimes.
// Maybe some strange race condition? Anyway, we want a robust behavior and this linkeRef should NOT be there.
// So simple remove it.
LOGGER.warn("The OID " + projCtx.getOid() + " of deleted shadow still exists in the linkRef after discovery (" + focusCurrent + "), removing it");
ReferenceDelta unlinkDelta = ReferenceDelta.createModificationDelete(FocusType.F_LINK_REF, focusContext.getObjectDefinition(), linkRef.asReferenceValue().clone());
focusContext.swallowToSecondaryDelta(unlinkDelta);
continue;
}
boolean found = false;
for (LensProjectionContext pCtx : context.getProjectionContexts()) {
if (linkRef.getOid().equals(pCtx.getOid())) {
found = true;
break;
}
}
if (!found) {
// This link is new, it is not in the existing lens context
PrismObject<ShadowType> newLinkRepoShadow = cacheRepositoryService.getObject(ShadowType.class, linkRef.getOid(), null, result);
if (ShadowUtil.matches(newLinkRepoShadow, projCtx.getResourceShadowDiscriminator())) {
LOGGER.trace("Found new matching link: {}, updating projection context", newLinkRepoShadow);
// MID-3317
LOGGER.trace("Applying definition from provisioning first.");
provisioningService.applyDefinition(newLinkRepoShadow, task, result);
projCtx.setObjectCurrent(newLinkRepoShadow);
projCtx.setOid(newLinkRepoShadow.getOid());
projCtx.recompute();
compensated = true;
break;
} else {
LOGGER.trace("Found new link: {}, but skipping it because it does not match the projection context", newLinkRepoShadow);
}
}
}
}
}
}
if (!compensated) {
LOGGER.trace("ObjectNotFound error is not compensated, setting context to thombstone");
projCtx.getResourceShadowDiscriminator().setThombstone(true);
projCtx.setExists(false);
projCtx.setFullShadow(false);
}
}
}
projCtx.recompute();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Loaded full resource object:\n{}", projCtx.debugDump(1));
}
}
use of com.evolveum.midpoint.model.impl.lens.LensFocusContext in project midpoint by Evolveum.
the class MiscDataUtil method generateFocusOidIfNeeded.
public void generateFocusOidIfNeeded(ModelContext<?> modelContext, ObjectDelta<? extends ObjectType> change) {
if (modelContext.getFocusContext().getOid() != null) {
return;
}
String newOid = OidUtil.generateOid();
LOGGER.trace("This is ADD operation with no focus OID provided. Generated new OID to be used: {}", newOid);
if (change.getChangeType() != ADD) {
throw new IllegalStateException("Change type is not ADD for no-oid focus situation: " + change);
} else if (change.getObjectToAdd() == null) {
throw new IllegalStateException("Object to add is null for change: " + change);
} else if (change.getObjectToAdd().getOid() != null) {
throw new IllegalStateException("Object to add has already an OID present: " + change);
}
change.getObjectToAdd().setOid(newOid);
((LensFocusContext<?>) modelContext.getFocusContext()).setOid(newOid);
}
use of com.evolveum.midpoint.model.impl.lens.LensFocusContext in project midpoint by Evolveum.
the class WfPrepareRootOperationTaskHandler method run.
//endregion
//region run method
@Override
public TaskRunResult run(Task task) {
TaskRunResultStatus status = TaskRunResultStatus.FINISHED;
try {
OperationResult result = task.getResult();
WfTask rootWfTask = wfTaskController.recreateRootWfTask(task);
List<WfTask> children = rootWfTask.listChildren(result);
LensContext rootContext = (LensContext) rootWfTask.retrieveModelContext(result);
boolean changed = false;
for (WfTask child : children) {
if (child.getTaskExecutionStatus() != TaskExecutionStatus.CLOSED) {
throw new IllegalStateException("Child task " + child + " is not in CLOSED state; its state is " + child.getTaskExecutionStatus());
}
if (child.hasModelContext()) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Child job {} has model context present - skipping fetching deltas from it.", child);
}
} else {
ObjectTreeDeltas deltas = child.retrieveResultingDeltas();
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Child job {} returned {} deltas", child, deltas != null ? deltas.getDeltaList().size() : 0);
}
if (deltas != null) {
LensFocusContext focusContext = rootContext.getFocusContext();
ObjectDelta focusDelta = deltas.getFocusChange();
if (focusDelta != null) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Adding delta from job {} to root model context; delta = {}", child, focusDelta.debugDump(0));
}
if (focusContext.getPrimaryDelta() != null && !focusContext.getPrimaryDelta().isEmpty()) {
focusContext.addPrimaryDelta(focusDelta);
} else {
focusContext.setPrimaryDelta(focusDelta);
}
changed = true;
}
Set<Map.Entry<ResourceShadowDiscriminator, ObjectDelta<ShadowType>>> entries = deltas.getProjectionChangeMapEntries();
for (Map.Entry<ResourceShadowDiscriminator, ObjectDelta<ShadowType>> entry : entries) {
if (LOGGER.isTraceEnabled()) {
LOGGER.trace("Adding projection delta from job {} to root model context; rsd = {}, delta = {}", child, entry.getKey(), entry.getValue().debugDump());
}
ModelProjectionContext projectionContext = rootContext.findProjectionContext(entry.getKey());
if (projectionContext == null) {
// TODO more liberal treatment?
throw new IllegalStateException("No projection context for " + entry.getKey());
}
if (projectionContext.getPrimaryDelta() != null && !projectionContext.getPrimaryDelta().isEmpty()) {
projectionContext.addPrimaryDelta(entry.getValue());
} else {
projectionContext.setPrimaryDelta(entry.getValue());
}
changed = true;
}
}
}
}
if (!rootContext.hasAnyPrimaryChange()) {
// deletes the model context
rootContext = null;
// regardless of whether rootContext was changed or not
changed = true;
}
if (changed) {
rootWfTask.storeModelContext(rootContext);
rootWfTask.commitChanges(result);
}
} catch (SchemaException | ObjectNotFoundException | ObjectAlreadyExistsException | ConfigurationException | ExpressionEvaluationException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't aggregate resulting deltas from child workflow-monitoring tasks due to schema exception", e);
status = TaskRunResultStatus.PERMANENT_ERROR;
} catch (CommunicationException e) {
LoggingUtils.logUnexpectedException(LOGGER, "Couldn't aggregate resulting deltas from child workflow-monitoring tasks", e);
status = TaskRunResultStatus.TEMPORARY_ERROR;
}
TaskRunResult runResult = new TaskRunResult();
runResult.setRunResultStatus(status);
return runResult;
}
Aggregations