Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -74,8 +74,7 @@ public abstract class AbstractPolicyEvaluationCache implements PolicyEvaluationC
* Result. If the key is not in the cache or the result is invalidated, it will return null. Also it will remove
* the Policy EvaluationResult so that subsequent evaluations won't find the key in the cache.
*
* @param evalRequestkey
* The Policy Evaluation key to retrieve.
* @param evalRequestkey The Policy Evaluation key to retrieve.
* @return The Policy Evaluation Result if the key is in the cache and the result isn't invalidated, or null
*/
@Override
Expand All @@ -89,23 +88,25 @@ public PolicyEvaluationResult get(final PolicyEvaluationRequestCacheKey evalRequ
}
PolicyEvaluationResult cachedEvalResult = toPolicyEvaluationResult(cachedEvalResultString);

List<String> invalidationTimeStamps = new ArrayList<>();
invalidationTimeStamps.add(cachedEntries.getSubjectLastModified());
invalidationTimeStamps.addAll(cachedEntries.getPolicySetsLastModified());
List<String> attributeInvalidationTimeStamps = new ArrayList<>();
List<String> policyInvalidationTimeStamps = new ArrayList<>();
attributeInvalidationTimeStamps.add(cachedEntries.getSubjectLastModified());
policyInvalidationTimeStamps.addAll(cachedEntries.getPolicySetsLastModified());

Set<String> cachedResolvedResourceUris = cachedEvalResult.getResolvedResourceUris();
//is requested resource id same as resolved resource uri ?
if (cachedResolvedResourceUris.size() == 1
&& cachedResolvedResourceUris.iterator().next().equals(evalRequestkey.getResourceId())) {
invalidationTimeStamps.add(cachedEntries.getRequestedResourceLastModified());
if (cachedResolvedResourceUris.size() == 1 && cachedResolvedResourceUris.iterator().next()
.equals(evalRequestkey.getResourceId())) {
attributeInvalidationTimeStamps.add(cachedEntries.getRequestedResourceLastModified());
} else {
List<String> cacheResolvedResourceKeys = cachedResolvedResourceUris.stream()
.map(resolvedResourceUri -> resourceKey(evalRequestkey.getZoneId(), resolvedResourceUri))
.collect(Collectors.toList());
invalidationTimeStamps.addAll(multiGet(cacheResolvedResourceKeys));
attributeInvalidationTimeStamps.addAll(multiGet(cacheResolvedResourceKeys));
}

if (isCachedRequestInvalid(invalidationTimeStamps, new DateTime(cachedEvalResult.getTimestamp()))) {
if (isCachedRequestInvalid(attributeInvalidationTimeStamps, policyInvalidationTimeStamps,
new DateTime(cachedEvalResult.getTimestamp()))) {
delete(cachedEntries.getDecisionKey());
LOGGER.debug("Cached decision for key '{}' is not valid.", cachedEntries.getDecisionKey());
return null;
Expand Down Expand Up @@ -136,7 +137,7 @@ private final class DecisionCacheEntries {
DecisionCacheEntries(final PolicyEvaluationRequestCacheKey evalRequestKey) {
//Get all values with a batch get
this.decisionKey = evalRequestKey.toDecisionKey();
this.entryKeys = prepareKeys(evalRequestKey);
this.entryKeys = prepareKeys(evalRequestKey);
this.entryValues = multiGet(this.entryKeys);
this.lastValueIndex = this.entryValues.size() - 1;

Expand Down Expand Up @@ -190,16 +191,15 @@ String getRequestedResourceLastModified() {
List<String> getPolicySetsLastModified() {
return this.policySetTimestamps;
}
}

}

private void logCacheGetDebugMessages(final PolicyEvaluationRequestCacheKey key, final String redisKey,
final List<String> keys, final List<String> values) {
if (LOGGER.isDebugEnabled()) {
LinkedHashSet<String> policySetIds = key.getPolicySetIds();
policySetIds.forEach(policySetId -> LOGGER
.debug(String.format("Getting timestamp for policy set: '%s', key: '%s', timestamp:'%s'.",
policySetId, keys.get(0), values.get(0))));
policySetIds.forEach(policySetId -> LOGGER.debug(String
.format("Getting timestamp for policy set: '%s', key: '%s', timestamp:'%s'.", policySetId,
keys.get(0), values.get(0))));
LOGGER.debug("Getting timestamp for resource: '{}', key: '{}', timestamp:'{}'.", key.getResourceId(),
keys.get(1), values.get(1));
LOGGER.debug("Getting timestamp for subject: '{}', key: '{}', timestamp:'{}'.", key.getSubjectId(),
Expand Down Expand Up @@ -278,7 +278,7 @@ public void resetForPolicySet(final String zoneId, final String policySetId) {
resetForEntity(zoneId, policySetId, EntityType.POLICY_SET, AbstractPolicyEvaluationCache::policySetKey);
}

public void setPolicySetIfNotExists(final String zoneId, final String policySetId) {
private void setPolicySetIfNotExists(final String zoneId, final String policySetId) {
setEntityIfNotExists(zoneId, policySetId, AbstractPolicyEvaluationCache::policySetKey);
}

Expand All @@ -287,7 +287,7 @@ public void resetForResource(final String zoneId, final String resourceId) {
resetForEntity(zoneId, resourceId, EntityType.RESOURCE, AbstractPolicyEvaluationCache::resourceKey);
}

public void setResourceIfNotExists(final String zoneId, final String resourceId) {
private void setResourceIfNotExists(final String zoneId, final String resourceId) {
setEntityIfNotExists(zoneId, resourceId, AbstractPolicyEvaluationCache::resourceKey);
}

Expand Down Expand Up @@ -316,7 +316,7 @@ public void resetForSubject(final String zoneId, final String subjectId) {
resetForEntity(zoneId, subjectId, EntityType.SUBJECT, AbstractPolicyEvaluationCache::subjectKey);
}

public void setSubjectIfNotExists(final String zoneId, final String subjectId) {
private void setSubjectIfNotExists(final String zoneId, final String subjectId) {
setEntityIfNotExists(zoneId, subjectId, AbstractPolicyEvaluationCache::subjectKey);
}

Expand Down Expand Up @@ -348,13 +348,17 @@ private void createMutliSetEntityMap(final String zoneId, final Map<String, Stri
map.put(key, timestamp);
}

private boolean isCachedRequestInvalid(final List<String> values, final DateTime policyEvalTimestamp) {
private boolean isCachedRequestInvalid(final List<String> attributeInvalidationTimeStamps,
final List<String> policyInvalidationTimeStamps, final DateTime policyEvalTimestamp) {
DateTime policyEvalTimestampUTC = policyEvalTimestamp.withZone(DateTimeZone.UTC);
if (haveEntitiesChanged(policyInvalidationTimeStamps, policyEvalTimestampUTC)) {
return true;
}
if (this.connectorService.isResourceAttributeConnectorConfigured() || this.connectorService
.isSubjectAttributeConnectorConfigured()) {
return haveConnectorCacheIntervalsLapsed(this.connectorService, policyEvalTimestampUTC);
} else {
return havePrivilegeServiceAttributesChanged(values, policyEvalTimestampUTC);
return haveEntitiesChanged(attributeInvalidationTimeStamps, policyEvalTimestampUTC);
}
}

Expand All @@ -367,7 +371,7 @@ private boolean isCachedRequestInvalid(final List<String> values, final DateTime
* @return true or false depending on whether any of the objects in values has a timestamp after
* policyEvalTimestampUTC.
*/
boolean havePrivilegeServiceAttributesChanged(final List<String> values, final DateTime policyEvalTimestampUTC) {
boolean haveEntitiesChanged(final List<String> values, final DateTime policyEvalTimestampUTC) {
for (String value : values) {
if (null == value) {
return true;
Expand Down Expand Up @@ -395,11 +399,11 @@ boolean haveConnectorCacheIntervalsLapsed(final AttributeConnectorService localC

boolean hasResourceConnectorIntervalLapsed = localConnectorService.isResourceAttributeConnectorConfigured()
&& decisionAgeMinutes >= localConnectorService.getResourceAttributeConnector()
.getMaxCachedIntervalMinutes();
.getMaxCachedIntervalMinutes();

boolean hasSubjectConnectorIntervalLapsed = localConnectorService.isSubjectAttributeConnectorConfigured()
&& decisionAgeMinutes >= localConnectorService.getSubjectAttributeConnector()
.getMaxCachedIntervalMinutes();
.getMaxCachedIntervalMinutes();

return hasResourceConnectorIntervalLapsed || hasSubjectConnectorIntervalLapsed;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,7 @@
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertNull;

import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Expand All @@ -51,16 +49,16 @@

public class AbstractPolicyEvaluationCacheTest {

public static final String ZONE_NAME = "testzone1";
public static final ZoneEntity ZONE_ENTITY = new ZoneEntity(1L, ZONE_NAME);
public static final String ACTION_GET = "GET";
public static final PolicySet POLICY_ONE = new PolicySet("policyOne");
public static final PolicySet POLICY_TWO = new PolicySet("policyTwo");
public static final LinkedHashSet<String> EVALUATION_ORDER_POLICYONE_POLICYTWO = Stream.of("policyOne", "policyTwo")
.collect(Collectors.toCollection(LinkedHashSet::new));
public static final LinkedHashSet<String> EVALUATION_ORDER_POLICYTWO_POLICYONE = Stream.of("policyTwo", "policyOne")
.collect(Collectors.toCollection(LinkedHashSet::new));
public static final LinkedHashSet<String> EVALUATION_ORDER_POLICYONE = Stream.of("policyOne")
private static final String ZONE_NAME = "testzone1";
private static final ZoneEntity ZONE_ENTITY = new ZoneEntity(1L, ZONE_NAME);
private static final String ACTION_GET = "GET";
private static final PolicySet POLICY_ONE = new PolicySet("policyOne");
private static final PolicySet POLICY_TWO = new PolicySet("policyTwo");
private static final LinkedHashSet<String> EVALUATION_ORDER_POLICYONE_POLICYTWO = Stream
.of("policyOne", "policyTwo").collect(Collectors.toCollection(LinkedHashSet::new));
private static final LinkedHashSet<String> EVALUATION_ORDER_POLICYTWO_POLICYONE = Stream
.of("policyTwo", "policyOne").collect(Collectors.toCollection(LinkedHashSet::new));
private static final LinkedHashSet<String> EVALUATION_ORDER_POLICYONE = Stream.of("policyOne")
.collect(Collectors.toCollection(LinkedHashSet::new));

private final InMemoryPolicyEvaluationCache cache = new InMemoryPolicyEvaluationCache();
Expand Down Expand Up @@ -274,8 +272,7 @@ public void testGetWithResetForResources() throws Exception {
assertEquals(cachedResult.getEffect(), result.getEffect());

Thread.sleep(1);
this.cache.resetForResources(ZONE_NAME,
Arrays.asList(new ResourceEntity[] { new ResourceEntity(ZONE_ENTITY, XFILES_ID) }));
this.cache.resetForResources(ZONE_NAME, Collections.singletonList(new ResourceEntity(ZONE_ENTITY, XFILES_ID)));
assertNull(this.cache.get(key));
}

Expand All @@ -301,7 +298,7 @@ public void testGetWithResetForResolvedResources() throws Exception {

Thread.sleep(1);
this.cache.resetForResources(ZONE_NAME,
Arrays.asList(new ResourceEntity[] { new ResourceEntity(ZONE_ENTITY, resolvedResourceUri) }));
Collections.singletonList(new ResourceEntity(ZONE_ENTITY, resolvedResourceUri)));
assertNull(this.cache.get(key));
}

Expand All @@ -324,7 +321,7 @@ public void testGetWithResetForResourcesByIds() throws Exception {
assertEquals(cachedResult.getEffect(), result.getEffect());

Thread.sleep(1);
this.cache.resetForResourcesByIds(ZONE_NAME, new HashSet<>(Arrays.asList(XFILES_ID)));
this.cache.resetForResourcesByIds(ZONE_NAME, Collections.singleton(XFILES_ID));
assertNull(this.cache.get(key));
}

Expand Down Expand Up @@ -370,7 +367,7 @@ public void testGetWithResetForSubjectsByIds() throws Exception {
assertEquals(cachedResult.getEffect(), result.getEffect());

Thread.sleep(1);
this.cache.resetForSubjectsByIds(ZONE_NAME, new HashSet<>(Arrays.asList(AGENT_MULDER)));
this.cache.resetForSubjectsByIds(ZONE_NAME, Collections.singleton(AGENT_MULDER));
assertNull(this.cache.get(key));
}

Expand All @@ -393,8 +390,7 @@ public void testGetWithResetForSubjects() throws Exception {
assertEquals(cachedResult.getEffect(), result.getEffect());

Thread.sleep(1);
this.cache.resetForSubjects(ZONE_NAME,
Arrays.asList(new SubjectEntity[] { new SubjectEntity(ZONE_ENTITY, AGENT_MULDER) }));
this.cache.resetForSubjects(ZONE_NAME, Collections.singletonList(new SubjectEntity(ZONE_ENTITY, AGENT_MULDER)));
assertNull(this.cache.get(key));
}

Expand Down Expand Up @@ -428,6 +424,7 @@ public void testHaveConnectorIntervalsLapsed(final AttributeConnector resourceCo

Mockito.doReturn(resourceConnector).when(connectorService).getResourceAttributeConnector();
Mockito.doReturn(subjectConnector).when(connectorService).getSubjectAttributeConnector();
this.cache.resetForPolicySet(ZONE_NAME, POLICY_ONE.getName());

boolean isResourceConnectorConfigured = resourceConnector != null;
boolean isSubjectConnectorConfigured = subjectConnector != null;
Expand All @@ -441,24 +438,30 @@ public void testHaveConnectorIntervalsLapsed(final AttributeConnector resourceCo
request.setAction(ACTION_GET);
request.setSubjectIdentifier(AGENT_MULDER);
request.setResourceIdentifier(XFILES_ID);
request.setPolicySetsEvaluationOrder(EVALUATION_ORDER_POLICYONE);
PolicyEvaluationRequestCacheKey key = new PolicyEvaluationRequestCacheKey.Builder().zoneId(ZONE_NAME)
.request(request).build();

PolicyEvaluationResult result = mockPermitResult();
spiedCache.set(key, result);
spiedCache.get(key);
Mockito.verify(spiedCache, Mockito.times(isResourceConnectorConfigured || isSubjectConnectorConfigured ? 0 : 1))
.havePrivilegeServiceAttributesChanged(Mockito.any(), Mockito.any());
PolicyEvaluationResult expectedResult = mockPermitResult();
spiedCache.set(key, expectedResult);

PolicyEvaluationResult actualResult = spiedCache.get(key);
Assert.assertEquals(actualResult.getEffect(), expectedResult.getEffect());
Assert.assertEquals(actualResult.getResourceAttributes(), expectedResult.getResourceAttributes());
Assert.assertEquals(actualResult.getSubjectAttributes(), expectedResult.getSubjectAttributes());

Mockito.verify(spiedCache, Mockito.times(isResourceConnectorConfigured || isSubjectConnectorConfigured ? 1 : 2))
.haveEntitiesChanged(Mockito.any(), Mockito.any());
Mockito.verify(spiedCache, Mockito.times(isResourceConnectorConfigured || isSubjectConnectorConfigured ? 1 : 0))
.haveConnectorCacheIntervalsLapsed(Mockito.any(), Mockito.any());
Assert.assertEquals(this.cache.haveConnectorCacheIntervalsLapsed(connectorService, currentTime),
haveConnectorCacheIntervalsLapsed);

}

public static PolicyEvaluationResult mockPermitResult() {
private static PolicyEvaluationResult mockPermitResult() {
PolicyEvaluationResult result = new PolicyEvaluationResult(Effect.PERMIT);
result.setResolvedResourceUris(new HashSet<>(Arrays.asList(new String[] { XFILES_ID })));
result.setResolvedResourceUris(Collections.singleton(XFILES_ID));
return result;
}

Expand Down Expand Up @@ -511,10 +514,7 @@ private Object[] onlySubjectConnectorConfiguredAndElapsed() {
}

private Object[] connectorsNotConfigured() {
AttributeConnector resourceConnector = new AttributeConnector();
AttributeConnector subjectConnector = new AttributeConnector();

return new Object[] { resourceConnector, subjectConnector, DateTime.now().minusMinutes(3), false };
return new Object[] { null, null, DateTime.now().minusMinutes(3), false };
}

}