You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@cxf.apache.org by jb...@apache.org on 2015/03/23 15:39:12 UTC

cxf-fediz git commit: Fixing WebSphere Plugin NullpointerException + Adding Tests

Repository: cxf-fediz
Updated Branches:
  refs/heads/master fe8f240fd -> f7cf8d8cd


Fixing WebSphere Plugin NullpointerException + Adding Tests


Project: http://git-wip-us.apache.org/repos/asf/cxf-fediz/repo
Commit: http://git-wip-us.apache.org/repos/asf/cxf-fediz/commit/f7cf8d8c
Tree: http://git-wip-us.apache.org/repos/asf/cxf-fediz/tree/f7cf8d8c
Diff: http://git-wip-us.apache.org/repos/asf/cxf-fediz/diff/f7cf8d8c

Branch: refs/heads/master
Commit: f7cf8d8cde0c46f3f615044754c38beee246049c
Parents: fe8f240
Author: Jan Bernhardt <jb...@talend.com>
Authored: Mon Mar 23 15:38:54 2015 +0100
Committer: Jan Bernhardt <jb...@talend.com>
Committed: Mon Mar 23 15:38:54 2015 +0100

----------------------------------------------------------------------
 plugins/websphere/pom.xml                       |  6 ++
 .../was/mapper/FileBasedRoleToGroupMapper.java  |  4 +
 .../cxf/fediz/was/tai/FedizInterceptor.java     | 95 ++++++++++----------
 .../cxf/fediz/was/tai/FedizInterceptorTest.java | 74 +++++++++++++++
 .../src/test/resources/fediz_config.xml         | 40 +++++++++
 5 files changed, 173 insertions(+), 46 deletions(-)
----------------------------------------------------------------------


http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/f7cf8d8c/plugins/websphere/pom.xml
----------------------------------------------------------------------
diff --git a/plugins/websphere/pom.xml b/plugins/websphere/pom.xml
index 5f88527..18e1d80 100644
--- a/plugins/websphere/pom.xml
+++ b/plugins/websphere/pom.xml
@@ -102,6 +102,12 @@
             <version>${junit.version}</version>
             <scope>test</scope>
         </dependency>
+        <dependency>
+            <groupId>org.easymock</groupId>
+            <artifactId>easymock</artifactId>
+            <version>${easymock.version}</version>
+            <scope>test</scope>
+        </dependency>
     </dependencies>
     <build>
         <plugins>

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/f7cf8d8c/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/FileBasedRoleToGroupMapper.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/FileBasedRoleToGroupMapper.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/FileBasedRoleToGroupMapper.java
index 1bbd21a..03a497d 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/FileBasedRoleToGroupMapper.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/mapper/FileBasedRoleToGroupMapper.java
@@ -78,6 +78,10 @@ public class FileBasedRoleToGroupMapper implements RoleToGroupMapper {
 
     @Override
     public List<String> groupsFromRoles(List<String> roles) {
+        if (roles == null) {
+            return null;
+        }
+        
         List<String> groups = new ArrayList<String>(20);
         for (String key : roles) {
             List<String> groupList = mappings.get(key);

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/f7cf8d8c/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
index 6d8976c..1858369 100644
--- a/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
+++ b/plugins/websphere/src/main/java/org/apache/cxf/fediz/was/tai/FedizInterceptor.java
@@ -77,7 +77,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
     /**
      * @see org.apache.cxf.fediz.was.Constants#PROPERTY_KEY_DIRECT_GROUP_MAPPING
      */
-    private boolean directGrouMapping;
+    private boolean directGroupMapping;
 
     public String getConfigFile() {
         return configFile;
@@ -180,7 +180,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
                                                                  + Constants.PROPERTY_KEY_CONFIG_LOCATION);
                 }
 
-                directGrouMapping = Boolean.valueOf(props.getProperty(Constants.PROPERTY_KEY_DIRECT_GROUP_MAPPING));
+                directGroupMapping = Boolean.valueOf(props.getProperty(Constants.PROPERTY_KEY_DIRECT_GROUP_MAPPING));
             } catch (Throwable t) {
                 LOG.warn("Failed initializing TAI", t);
                 return 1;
@@ -189,7 +189,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         return 0;
     }
 
-    private FedizContext getFederationContext(HttpServletRequest req) {
+    protected FedizContext getFederationContext(HttpServletRequest req) {
         String contextPath = req.getContextPath();
         if (contextPath == null || contextPath.isEmpty()) {
             contextPath = "/";
@@ -427,7 +427,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         }
     }
 
-    private boolean checkSecurityToken(FedizResponse response) {
+    protected boolean checkSecurityToken(FedizResponse response) {
         if (response == null) {
             return false;
         }
@@ -435,51 +435,54 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
         return response.getTokenExpires().getTime() > currentTime;
     }
 
-    private List<String> groupIdsFromTokenRoles(FedizResponse federationResponse) {
+    protected List<String> groupIdsFromTokenRoles(FedizResponse federationResponse) {
 
         List<String> localGroups = mapper.groupsFromRoles(federationResponse.getRoles());
-        List<String> groupIds = new ArrayList<String>(localGroups.size());
-
-        if (directGrouMapping) {
-            LOG.debug("Direct Group Mapping was set in interceptor. Thus UserRegistry will not be invoked to get "
-                      + "GrouUID");
-            groupIds.addAll(localGroups);
-        } else {
-            InitialContext ctx = null;
-            try {
-                ctx = new InitialContext();
-                UserRegistry userRegistry = (UserRegistry)ctx.lookup(Constants.USER_REGISTRY_JNDI_NAME);
-
-                if (localGroups != null) {
-                    LOG.debug("Converting {} group names to uids", localGroups.size());
-                    for (String localGroup : localGroups) {
-                        try {
-                            String guid = convertGroupNameToUniqueId(userRegistry, localGroup);
-                            LOG.debug("Group '{}' maps to guid: {}", localGroup, guid);
-                            groupIds.add(guid);
-                        } catch (EntryNotFoundException e) {
-                            LOG.warn("Group entry '{}' could not be found in UserRegistry for user '{}'", localGroup,
-                                     federationResponse.getUsername());
+        int size = (localGroups == null) ? 0 : localGroups.size();
+        List<String> groupIds = new ArrayList<String>(size);
+
+        if (size > 0) {
+            if (directGroupMapping) {
+                LOG.debug("Direct Group Mapping was set in interceptor. Thus UserRegistry will not be invoked to get "
+                          + "GrouUID");
+                groupIds.addAll(localGroups);
+            } else {
+                InitialContext ctx = null;
+                try {
+                    ctx = new InitialContext();
+                    UserRegistry userRegistry = (UserRegistry)ctx.lookup(Constants.USER_REGISTRY_JNDI_NAME);
+
+                    if (localGroups != null) {
+                        LOG.debug("Converting {} group names to uids", size);
+                        for (String localGroup : localGroups) {
+                            try {
+                                String guid = convertGroupNameToUniqueId(userRegistry, localGroup);
+                                LOG.debug("Group '{}' maps to guid: {}", localGroup, guid);
+                                groupIds.add(guid);
+                            } catch (EntryNotFoundException e) {
+                                LOG.warn("Group entry '{}' could not be found in UserRegistry for user '{}'",
+                                         localGroup, federationResponse.getUsername());
+                            }
                         }
                     }
-                }
-            } catch (NamingException ex) {
-                LOG.error("User Registry could not be loaded via JNDI context.");
-                LOG.warn("Group mapping failed for user '{}'", federationResponse.getUsername());
-                LOG.info("To switch to direct GroupUID Mapping without UserRegistry being involved set "
-                         + "fedizDirectGroupMapping=\"true\"  in TAI Interceptor properties.");
-            } catch (RemoteException e) {
-                LOG.error("RemoteException in UserRegistry", e);
-                LOG.warn("Group mapping failed for user '{}'", federationResponse.getUsername());
-            } catch (CustomRegistryException e) {
-                LOG.error("CustomRegistryException in UserRegistry", e);
-                LOG.warn("Group mapping failed for user '{}'", federationResponse.getUsername());
-            } finally {
-                if (ctx != null) {
-                    try {
-                        ctx.close();
-                    } catch (NamingException e) {
-                        // Ignore
+                } catch (NamingException ex) {
+                    LOG.error("User Registry could not be loaded via JNDI context.");
+                    LOG.warn("Group mapping failed for user '{}'", federationResponse.getUsername());
+                    LOG.info("To switch to direct GroupUID Mapping without UserRegistry being involved set "
+                             + "fedizDirectGroupMapping=\"true\"  in TAI Interceptor properties.");
+                } catch (RemoteException e) {
+                    LOG.error("RemoteException in UserRegistry", e);
+                    LOG.warn("Group mapping failed for user '{}'", federationResponse.getUsername());
+                } catch (CustomRegistryException e) {
+                    LOG.error("CustomRegistryException in UserRegistry", e);
+                    LOG.warn("Group mapping failed for user '{}'", federationResponse.getUsername());
+                } finally {
+                    if (ctx != null) {
+                        try {
+                            ctx.close();
+                        } catch (NamingException e) {
+                            // Ignore
+                        }
                     }
                 }
             }
@@ -491,7 +494,7 @@ public class FedizInterceptor implements TrustAssociationInterceptor {
     /**
      * Creates the JAAS Subject so that WAS Runtime will not check the local registry
      */
-    private Subject createSubject(FedizResponse federationResponse, List<String> groups, String cacheKey) {
+    protected Subject createSubject(FedizResponse federationResponse, List<String> groups, String cacheKey) {
         String uniqueId = "user:defaultWIMFileBasedRealm/cn=" + federationResponse.getUsername()
                           + ",o=defaultWIMFileBasedRealm";
         String completeCacheKey = uniqueId + ':' + cacheKey;

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/f7cf8d8c/plugins/websphere/src/test/java/org/apache/cxf/fediz/was/tai/FedizInterceptorTest.java
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/test/java/org/apache/cxf/fediz/was/tai/FedizInterceptorTest.java b/plugins/websphere/src/test/java/org/apache/cxf/fediz/was/tai/FedizInterceptorTest.java
new file mode 100644
index 0000000..2159816
--- /dev/null
+++ b/plugins/websphere/src/test/java/org/apache/cxf/fediz/was/tai/FedizInterceptorTest.java
@@ -0,0 +1,74 @@
+/**
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements. See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership. The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License. You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing,
+ * software distributed under the License is distributed on an
+ * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+ * KIND, either express or implied. See the License for the
+ * specific language governing permissions and limitations
+ * under the License.
+ */
+
+package org.apache.cxf.fediz.was.tai;
+
+import java.util.Arrays;
+import java.util.List;
+import java.util.Properties;
+import com.ibm.websphere.security.WebTrustAssociationFailedException;
+
+import org.apache.cxf.fediz.core.processor.FedizResponse;
+import org.apache.cxf.fediz.was.Constants;
+import org.easymock.EasyMock;
+import org.junit.Test;
+
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+public class FedizInterceptorTest {
+
+    
+    @Test
+    public void testGroupMappingWithNull() throws WebTrustAssociationFailedException {
+        
+        FedizResponse resp = EasyMock.createMock(FedizResponse.class);
+        EasyMock.expect(resp.getRoles()).andReturn(null);
+        EasyMock.expect(resp.getUsername()).andReturn("Test-User").anyTimes();
+        EasyMock.replay(resp);
+        
+        FedizInterceptor fedizInterceptor = new FedizInterceptor();
+        Properties properties = new Properties();
+        properties.put(Constants.PROPERTY_KEY_CONFIG_LOCATION, "src/test/resources/fediz_config.xml");
+        fedizInterceptor.initialize(properties);
+        List<String> result = fedizInterceptor.groupIdsFromTokenRoles(resp);
+        assertNotNull(result);
+        assertEquals(0, result.size());
+    }
+    
+    @Test
+    public void testDirectGroupMapping() throws WebTrustAssociationFailedException {
+        
+        FedizResponse resp = EasyMock.createMock(FedizResponse.class);
+        EasyMock.expect(resp.getRoles()).andReturn(Arrays.asList("Admin", "Manager"));
+        EasyMock.expect(resp.getUsername()).andReturn("Test-User").anyTimes();
+        EasyMock.replay(resp);
+        
+        FedizInterceptor fedizInterceptor = new FedizInterceptor();
+        Properties properties = new Properties();
+        properties.put(Constants.PROPERTY_KEY_CONFIG_LOCATION, "src/test/resources/fediz_config.xml");
+        properties.put(Constants.PROPERTY_KEY_DIRECT_GROUP_MAPPING, "true");
+        
+        fedizInterceptor.initialize(properties);
+        List<String> result = fedizInterceptor.groupIdsFromTokenRoles(resp);
+        assertNotNull(result);
+        assertEquals(2, result.size());
+    }
+}

http://git-wip-us.apache.org/repos/asf/cxf-fediz/blob/f7cf8d8c/plugins/websphere/src/test/resources/fediz_config.xml
----------------------------------------------------------------------
diff --git a/plugins/websphere/src/test/resources/fediz_config.xml b/plugins/websphere/src/test/resources/fediz_config.xml
new file mode 100644
index 0000000..06c4b6b
--- /dev/null
+++ b/plugins/websphere/src/test/resources/fediz_config.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
+<!-- Place in Tomcat conf folder or other location as designated in this sample's file. 
+     Keystore referenced below must have IDP STS' public cert included in it.  This example uses the
+     ststrust Truststore (ststrust.jks) for this task.
+     In Fediz 1.0, one keystore was used for SSL and the STS public certificate.
+-->
+<FedizConfig>
+	<contextConfig name="/fedizhelloworld">
+		<audienceUris>
+			<audienceItem>urn:org:apache:cxf:fediz:fedizhelloworld</audienceItem>
+			<audienceItem>urn:org:apache:cxf:fediz:fedizhelloworld2</audienceItem>
+		</audienceUris>
+		<certificateStores>
+			<trustManager>
+				<keyStore file="ststrust.jks" password="storepass" type="JKS" />
+			</trustManager>
+		</certificateStores>
+		<trustedIssuers>
+			<issuer certificateValidation="PeerTrust" />
+		</trustedIssuers>
+		<tokenExpirationValidation>true</tokenExpirationValidation>
+		<maximumClockSkew>1000</maximumClockSkew>
+		<protocol xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+			xsi:type="federationProtocolType" version="1.0.0">
+			<realm>urn:org:apache:cxf:fediz:fedizhelloworld</realm>
+			<issuer>https://localhost:9443/fediz-idp/federation</issuer>
+			<roleDelimiter>,</roleDelimiter>
+			<roleURI>http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role</roleURI>
+			<claimTypesRequested>
+				<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/role" optional="false" />
+				<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/givenname" optional="true" />
+				<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/surname" optional="true" />
+				<claimType type="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress" optional="true" />
+			</claimTypesRequested>
+		</protocol>
+		<logoutURL>/secure/logout</logoutURL>
+        <logoutRedirectTo>/index.html</logoutRedirectTo>
+	</contextConfig>
+</FedizConfig>
+