use of org.codice.ddf.security.policy.context.ContextPolicy in project ddf by codice.
the class AuthenticationEndpointTest method testMultiRealm.
@Test
public void testMultiRealm() throws SecurityServiceException {
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.isSecure()).thenReturn(true);
ContextPolicy policy = mock(ContextPolicy.class);
ContextPolicy anotherPolicy = mock(ContextPolicy.class);
when(policy.getRealm()).thenReturn(REALM);
when(anotherPolicy.getRealm()).thenReturn("ANOTHER_REALM");
when(policyManager.getContextPolicy(PATH)).thenReturn(policy);
when(policyManager.getContextPolicy("/anotherPath")).thenReturn(anotherPolicy);
mockUser("another", "another", "ANOTHER_REALM");
authEndpoint.login(request, USER_NAME, PASSWORD, PATH);
authEndpoint.login(request, "another", "another", "/anotherPath");
}
use of org.codice.ddf.security.policy.context.ContextPolicy in project ddf by codice.
the class WebSSOFilterTest method testDoFilterWhiteListed.
@Test
public void testDoFilterWhiteListed() throws IOException, AuthenticationException {
ContextPolicy testPolicy = mock(ContextPolicy.class);
ContextPolicyManager policyManager = mock(ContextPolicyManager.class);
when(policyManager.getContextPolicy(anyString())).thenReturn(testPolicy);
when(policyManager.isWhiteListed(anyString())).thenReturn(true);
when(policyManager.getSessionAccess()).thenReturn(false);
WebSSOFilter filter = new WebSSOFilter();
// set handlers
AuthenticationHandler handler1 = mock(AuthenticationHandler.class);
HandlerResult noActionResult = mock(HandlerResult.class);
when(noActionResult.getStatus()).thenReturn(Status.NO_ACTION);
HandlerResult completedResult = mock(HandlerResult.class);
when(completedResult.getStatus()).thenReturn(Status.COMPLETED);
when(completedResult.getToken()).thenReturn(null);
when(handler1.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(SecurityFilterChain.class), eq(true))).thenReturn(completedResult);
when(handler1.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(SecurityFilterChain.class), eq(false))).thenReturn(noActionResult);
filter.setHandlerList(Collections.singletonList(handler1));
filter.setContextPolicyManager(policyManager);
SecurityFilterChain filterChain = mock(SecurityFilterChain.class);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getRequestURI()).thenReturn(MOCK_CONTEXT);
HttpServletResponse response = mock(HttpServletResponse.class);
filter.doFilter(request, response, filterChain);
verify(request, times(1)).setAttribute(ContextPolicy.NO_AUTH_POLICY, true);
verify(filterChain).doFilter(request, response);
verify(handler1, never()).getNormalizedToken(any(HttpServletRequest.class), any(HttpServletResponse.class), any(SecurityFilterChain.class), anyBoolean());
}
use of org.codice.ddf.security.policy.context.ContextPolicy in project ddf by codice.
the class WebSSOFilterTest method testDoFilterSessionStorageDisabled.
@Test
public void testDoFilterSessionStorageDisabled() throws Exception {
PrincipalCollection principalCollectionMock = mock(PrincipalCollection.class);
PrincipalHolder principalHolderMock = mock(PrincipalHolder.class);
when(principalHolderMock.getPrincipals()).thenReturn(principalCollectionMock);
HttpSession sessionMock = mock(HttpSession.class);
when(sessionMock.getAttribute(SECURITY_TOKEN_KEY)).thenReturn(principalHolderMock);
HttpServletRequest requestMock = mock(HttpServletRequest.class);
when(requestMock.getSession(any(Boolean.class))).thenReturn(sessionMock);
when(requestMock.getRequestURI()).thenReturn(MOCK_CONTEXT);
HttpServletResponse responseMock = mock(HttpServletResponse.class);
ContextPolicyManager policyManager = mock(ContextPolicyManager.class);
when(policyManager.getSessionAccess()).thenReturn(false);
when(policyManager.isWhiteListed(MOCK_CONTEXT)).thenReturn(false);
ContextPolicy testPolicy = mock(ContextPolicy.class);
when(testPolicy.getAuthenticationMethods()).thenReturn(Collections.singletonList("basic"));
when(policyManager.getContextPolicy(MOCK_CONTEXT)).thenReturn(testPolicy);
AuthenticationHandler handlerMock = mock(AuthenticationHandler.class);
when(handlerMock.getAuthenticationType()).thenReturn("basic");
HandlerResult completedResult = mock(HandlerResult.class);
when(completedResult.getStatus()).thenReturn(Status.COMPLETED);
when(completedResult.getToken()).thenReturn(mock(BaseAuthenticationToken.class));
when(handlerMock.getNormalizedToken(any(ServletRequest.class), any(ServletResponse.class), any(SecurityFilterChain.class), anyBoolean())).thenReturn(completedResult);
SecurityFilterChain filterChain = mock(SecurityFilterChain.class);
WebSSOFilter filter = new WebSSOFilter();
filter.setContextPolicyManager(policyManager);
filter.setHandlerList(Collections.singletonList(handlerMock));
filter.doFilter(requestMock, responseMock, filterChain);
verify(sessionMock, times(0)).getAttribute(SECURITY_TOKEN_KEY);
verify(handlerMock, times(1)).getNormalizedToken(any(), any(), any(), anyBoolean());
verify(requestMock, times(1)).setAttribute(eq(AUTHENTICATION_TOKEN_KEY), any());
}
use of org.codice.ddf.security.policy.context.ContextPolicy in project ddf by codice.
the class AuthorizationFilter method doFilter.
@SuppressWarnings("PackageAccessibility")
@Override
public void doFilter(ServletRequest request, ServletResponse response, SecurityFilterChain chain) throws IOException, AuthenticationException {
HttpServletRequest httpRequest = (HttpServletRequest) request;
HttpServletResponse httpResponse = (HttpServletResponse) response;
Subject subject = null;
if (request.getAttribute(ContextPolicy.NO_AUTH_POLICY) != null) {
LOGGER.debug("NO_AUTH_POLICY header was found, skipping authorization filter.");
chain.doFilter(request, response);
} else {
try {
subject = SecurityUtils.getSubject();
} catch (Exception e) {
LOGGER.debug("Unable to retrieve user from request.", e);
}
boolean permitted = true;
final String path = httpRequest.getRequestURI();
ContextPolicy policy = contextPolicyManager.getContextPolicy(path);
CollectionPermission permissions = null;
if (policy != null && subject != null) {
permissions = policy.getAllowedAttributePermissions();
if (!permissions.isEmpty()) {
permitted = subject.isPermitted(permissions);
}
} else {
LOGGER.warn("Unable to determine policy for path {}. User is not permitted to continue. Check policy configuration!", LogSanitizer.sanitize(path));
permitted = false;
}
if (!permitted) {
securityLogger.audit("Subject not authorized to view resource {}", path);
LOGGER.debug("Subject not authorized.");
returnNotAuthorized(httpResponse);
} else {
if (!permissions.isEmpty()) {
securityLogger.audit("Subject is authorized to view resource {}", path);
}
LOGGER.debug("Subject is authorized!");
chain.doFilter(request, response);
}
}
}
use of org.codice.ddf.security.policy.context.ContextPolicy in project ddf by codice.
the class PolicyManager method setPolicies.
/**
* Initializes the policy store. This method will be called every time the policy attributes
* change. This will happen after the component has been initialized (see {@link #configure()} and
* when an update is made to the {@code org.codice.ddf.security.policy.context.impl.PolicyManager}
* configuration pid. <br>
* See https://osgi.org/javadoc/r6/cmpn/org/osgi/service/cm/ManagedService.html for more details
* on how and when this method may be called.
*
* @param properties map of properties to use to initialize the policy store. Since there is no
* configuration file bound to these properties by default, this map may be {@code null}.
*/
public void setPolicies(Map<String, Object> properties) {
if (properties == null) {
LOGGER.debug("setPolicies() called with null properties map. " + "Policy store should have already been initialized so ignoring.");
LOGGER.debug("Policy Store already contains {} items", policyStore.size());
return;
}
LOGGER.debug("setPolicies called: {}", properties);
Map<String, ContextPolicy> originalPolicyStore = getPolicyStore();
setGuestAccess((boolean) properties.get(GUEST_ACCESS));
setSessionAccess((boolean) properties.get(SESSION_ACCESS));
String webAuthTypes = (String) properties.get(WEB_AUTH_TYPES);
String endpointAuthTypes = (String) properties.get(ENDPOINT_AUTH_TYPES);
String[] attrContexts = (String[]) properties.get(REQ_ATTRS);
String[] whiteList = (String[]) properties.get(WHITE_LIST);
if (whiteList != null) {
setWhiteListContexts(Arrays.asList(whiteList));
}
if (webAuthTypes != null && endpointAuthTypes != null && attrContexts != null) {
Map<String, List<ContextAttributeMapping>> contextToAttr = new HashMap<>();
List<String> attrContextList = new ArrayList<>();
Collections.addAll(attrContextList, attrContexts);
for (String attr : attrContextList) {
int index = attr.indexOf('=');
if (index < 1) {
throw new IllegalArgumentException("Invalid attribute context: " + attr);
}
String context = attr.substring(0, index);
String value = attr.substring(index + 1);
if (StringUtils.isNotEmpty(context) && value != null) {
if (value.startsWith("{") && value.endsWith("}")) {
if (value.length() == 2) {
value = "";
} else {
value = value.substring(1, value.length() - 1);
}
}
String[] attributes = value.split(";");
List<ContextAttributeMapping> attrMaps = new ArrayList<>();
for (String attribute : attributes) {
String[] parts = attribute.split("=");
if (parts.length == 2) {
attrMaps.add(new DefaultContextAttributeMapping(context, parts[0], parts[1]));
}
}
contextToAttr.put(context, attrMaps);
}
}
this.contextToAttr = contextToAttr;
if (contextToAuthFile == null) {
Map<String, List<String>> contextToAuthMap = new HashMap<>();
contextToAuthMap.put(ROOT_CONTEXT, Arrays.asList(webAuthTypes.split("\\|")));
contextToAuthMap.put(SERVICES_CONTEXT, Arrays.asList(endpointAuthTypes.split("\\|")));
contextToAuthConfig = contextToAuthMap;
setPolicyStore(contextToAuthMap, contextToAttr);
} else {
setPolicyStore(contextToAuthFile, contextToAttr);
}
}
LOGGER.debug("Policy store initialized, now contains {} entries", policyStore.size());
securityLogger.audit("Policy store changed from:\n{} \nto:\n{}", originalPolicyStore, getPolicyStore());
}
Aggregations