[jboss-cvs] JBossAS SVN: r92035 - in projects/security/security-jboss-sx/trunk: jbosssx/src/main/java/org/jboss/security/mapping/providers and 7 other directories.

jboss-cvs-commits at lists.jboss.org jboss-cvs-commits at lists.jboss.org
Wed Aug 5 17:42:31 EDT 2009


Author: anil.saldhana at jboss.com
Date: 2009-08-05 17:42:30 -0400 (Wed, 05 Aug 2009)
New Revision: 92035

Added:
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/config/AttributeMappingInfo.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/DefaultAttributeMappingProvider.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/MappingProvidersDecodeAction.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestsAdapter.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/mapping/LdapAttributeMappingProviderUnitTestCase.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/test/resources/ldap/ldapAttributes.ldif
Modified:
   projects/security/security-jboss-sx/trunk/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java
   projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java
Log:
SECURITY-427: mapping type attribute

Modified: projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java	2009-08-05 21:41:22 UTC (rev 92034)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/config/ApplicationPolicy.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -275,6 +275,7 @@
     */
    public void setMappingInfo(String mappingType, MappingInfo info)
    {
+      mappingType = mappingType.toLowerCase();
       // if there is a registered info for the specified type, merge the modules.
       if(this.mappingInfos.containsKey(mappingType))
          this.mappingInfos.get(mappingType).add(info.getModuleEntries());

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/config/AttributeMappingInfo.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/config/AttributeMappingInfo.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/config/AttributeMappingInfo.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -0,0 +1,34 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.config;
+
+/**
+ * Mapping Info for Attributes
+ * @author Anil.Saldhana at redhat.com
+ */
+public class AttributeMappingInfo extends MappingInfo
+{ 
+   public AttributeMappingInfo(String name)
+   {
+      super(name); 
+   } 
+}

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/DefaultAttributeMappingProvider.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/DefaultAttributeMappingProvider.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/DefaultAttributeMappingProvider.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -0,0 +1,84 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.mapping.providers.attribute;
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.identity.Attribute;
+import org.jboss.security.identity.AttributeFactory;
+import org.jboss.security.mapping.MappingProvider;
+import org.jboss.security.mapping.MappingResult;
+ 
+
+/**
+ * Generates an attribute array from the passed options
+ * @author Anil.Saldhana at redhat.com
+ */
+public class DefaultAttributeMappingProvider implements MappingProvider<List<Attribute<String>>>
+{
+   private MappingResult<List<Attribute<String>>> result = new MappingResult<List<Attribute<String>>>();
+   
+   private Map<String,Object> options = new HashMap<String,Object>();
+   
+   public void init(Map<String,Object> options)
+   {
+      this.options.putAll(options);
+   }
+
+   public void performMapping(Map<String, Object> map, List<Attribute<String>> mappedObject)
+   {
+      List<Attribute<String>> attList = new ArrayList<Attribute<String>>();
+      
+      //Get the Principal
+      Principal principal = (Principal) map.get(SecurityConstants.PRINCIPAL_IDENTIFIER);
+      
+      if(principal != null)
+      {
+         String principalName = principal.getName(); 
+         
+         //Get the email address
+         String emailAddress = (String) options.get(principalName + ".email"); 
+         
+         Attribute<String> att = AttributeFactory.createEmailAddress(emailAddress);
+         attList.add(att);
+      }
+      mappedObject.addAll(attList);
+      result.setMappedObject(mappedObject);
+   }
+
+   public void setMappingResult(MappingResult<List<Attribute<String>>> result)
+   {    
+      this.result = result;
+   }
+
+   public boolean supports(Class<?> clazz)
+   {
+      if(Attribute.class.isAssignableFrom(clazz)) 
+        return true;
+      return false;
+   }
+}
\ No newline at end of file

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/LdapAttributeMappingProvider.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -0,0 +1,343 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.security.mapping.providers.attribute;
+
+import java.security.Principal;
+import java.util.ArrayList;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Properties;
+import java.util.StringTokenizer;
+import java.util.Map.Entry;
+
+import javax.management.ObjectName;
+import javax.naming.Context;
+import javax.naming.NamingEnumeration;
+import javax.naming.NamingException;
+import javax.naming.directory.Attributes;
+import javax.naming.directory.SearchControls;
+import javax.naming.directory.SearchResult;
+import javax.naming.ldap.InitialLdapContext;
+
+import org.jboss.logging.Logger;
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.identity.Attribute;
+import org.jboss.security.identity.AttributeFactory;
+import org.jboss.security.mapping.MappingProvider;
+import org.jboss.security.mapping.MappingResult;
+
+/**
+ * Maps attributes from LDAP
+ * 
+ * The options include whatever options your LDAP JNDI provider
+ supports. Examples of standard property names are:
+
+ * Context.INITIAL_CONTEXT_FACTORY = "java.naming.factory.initial"
+ * Context.SECURITY_PROTOCOL = "java.naming.security.protocol"
+ * Context.PROVIDER_URL = "java.naming.provider.url"
+ * Context.SECURITY_AUTHENTICATION = "java.naming.security.authentication"
+ * 
+ * Other Module Options:-
+ * 
+ * bindDN:The DN used to bind against the ldap server for the user and
+ roles queries. This is some DN with read/search permissions on the baseCtxDN and
+ rolesCtxDN values.
+ * 
+ * bindCredential: The password for the bindDN. This can be encrypted if the
+ jaasSecurityDomain is specified.
+ * 
+ * baseCtxDN: The fixed DN of the context to start the user search from.
+ * 
+ * baseFilter:A search filter used to locate the context of the user to
+ authenticate. The input username/userDN as obtained from the login module
+ callback will be substituted into the filter anywhere a "{0}" expression is
+ seen. This substituion behavior comes from the standard
+ __DirContext.search(Name, String, Object[], SearchControls cons)__ method. An
+ common example search filter is "(uid={0})".
+ 
+ * searchTimeLimit:The timeout in milliseconds for the user/role searches.
+ Defaults to 10000 (10 seconds).
+ 
+ * attributeList: A comma-separated list of attributes for the user 
+ * (Example:  mail,cn,sn,employeeType,employeeNumber)
+ * 
+ * jaasSecurityDomain: The JMX ObjectName of the JaasSecurityDomain to use
+ to decrypt the java.naming.security.principal. The encrypted form of the
+ password is that returned by the JaasSecurityDomain#encrypt64(byte[]) method.
+ The org.jboss.security.plugins.PBEUtils can also be used to generate the
+ encrypted form.
+ * 
+ * @author Anil.Saldhana at redhat.com
+ * @since August 5, 2009
+ */
+public class LdapAttributeMappingProvider implements MappingProvider<List<Attribute<String>>>
+{
+   private Map<String, Object> options;
+   
+   private static Logger log = Logger.getLogger(LdapAttributeMappingProvider.class);
+   private boolean trace = log.isTraceEnabled();
+   
+   protected int searchTimeLimit = 10000;
+   
+   private static final String BIND_DN = "bindDN";
+
+   private static final String BIND_CREDENTIAL = "bindCredential";
+
+   private static final String BASE_CTX_DN = "baseCtxDN";
+
+   private static final String BASE_FILTER_OPT = "baseFilter"; 
+
+   private static final String SEARCH_TIME_LIMIT_OPT = "searchTimeLimit";
+   
+   private static final String ATTRIBUTE_LIST_OPT = "attributeList"; 
+
+   private static final String SECURITY_DOMAIN_OPT = "jaasSecurityDomain";
+
+   private MappingResult<List<Attribute<String>>> mappingResult;
+
+   public void init(Map<String, Object> options)
+   {
+      this.options = options;
+   }
+
+   @SuppressWarnings("unchecked")
+   public void performMapping(Map<String, Object> map, List<Attribute<String>> mappedObject)
+   {
+      List<Attribute<String>> attributeList = new ArrayList<Attribute<String>>();
+      
+      Principal principal = (Principal) map.get(SecurityConstants.PRINCIPAL_IDENTIFIER);
+      if(principal != null)
+      {
+         String user = principal.getName();
+         
+         String bindDN = (String) options.get(BIND_DN);
+         if(bindDN == null || bindDN.length() == 0)
+         {
+            log.trace("bindDN is not found");
+            return;
+         }
+         String bindCredential = (String) options.get(BIND_CREDENTIAL);
+         if (bindCredential.startsWith("{EXT}"))
+            try
+            {
+               bindCredential = new String(org.jboss.security.Util.loadPassword(bindCredential));
+            }
+            catch (Exception e1)
+            {
+               log.error("Exception in decrypting bindCredential:",e1);
+               return;
+            }
+         String securityDomain = (String) options.get(SECURITY_DOMAIN_OPT);
+         if (securityDomain != null)
+         {
+            try
+            {
+               ObjectName serviceName = new ObjectName(securityDomain);
+               char[] tmp = MappingProvidersDecodeAction.decode(bindCredential, serviceName);
+               bindCredential = new String(tmp);
+            } 
+            catch (Exception e)
+            {
+               log.error("Exception in decrypting bindCredential:",e);
+               return;
+            }
+         }
+         
+         InitialLdapContext ctx;
+         try
+         {
+            ctx = this.constructInitialLdapContext(bindDN, bindCredential);
+         }
+         catch (NamingException e)
+         {
+            throw new RuntimeException(e);
+         } 
+         
+         String timeLimit = (String) options.get(SEARCH_TIME_LIMIT_OPT);
+         if (timeLimit != null)
+         {
+            try
+            {
+               searchTimeLimit = Integer.parseInt(timeLimit);
+            }
+            catch (NumberFormatException e)
+            {
+               if (trace)
+                  log.trace("Failed to parse: " + timeLimit + ", using searchTimeLimit=" + searchTimeLimit, e);
+            }
+         }
+         if(searchTimeLimit == 0)
+            searchTimeLimit = 10000;
+         
+         String baseDN = (String) options.get(BASE_CTX_DN); 
+         String baseFilter = (String) options.get(BASE_FILTER_OPT);
+         
+         SearchControls constraints = new SearchControls();
+         constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
+         
+         constraints.setTimeLimit(searchTimeLimit);
+         
+         String attributePattern = (String) options.get(ATTRIBUTE_LIST_OPT);
+         
+         //Take care of the attributes we want
+         String neededAttributes[] = getNeededAttributes(attributePattern);
+         
+         constraints.setReturningAttributes(neededAttributes);
+
+         NamingEnumeration results = null;
+
+         Object[] filterArgs = {user};
+         try
+         {
+            if(baseDN == null)
+               throw new NamingException(BASE_CTX_DN + " is null");
+            results = ctx.search(baseDN, baseFilter, filterArgs, constraints);
+            if (results.hasMore() == false)
+            {
+               results.close();
+               throw new NamingException("Search of baseDN(" + baseDN + ") found no matches");
+            } 
+            SearchResult sr = (SearchResult) results.next();
+            String name = sr.getName();
+            String userDN = null;
+            if (sr.isRelative() == true)
+               userDN = name + "," + baseDN;
+            else
+               throw new NamingException("Can't follow referal for authentication: " + name);
+
+            results.close();
+            
+            //Finished Authentication.  Lets look for the attributes
+            filterArgs = new Object[]{user, userDN};
+            results = ctx.search(userDN, baseFilter, filterArgs, constraints);
+            try
+            {
+               while (results.hasMore())
+               {
+                  sr = (SearchResult) results.next(); 
+                  Attributes attributes = sr.getAttributes();
+                  NamingEnumeration<? extends javax.naming.directory.Attribute> ne = attributes.getAll();
+                  
+                  while(ne != null && ne.hasMoreElements())
+                  {
+                     javax.naming.directory.Attribute ldapAtt = ne.next();
+                     if("mail".equalsIgnoreCase(ldapAtt.getID()))
+                     {
+                        attributeList.add(AttributeFactory.createEmailAddress((String) ldapAtt.get()));   
+                     }
+                     else
+                        attributeList.add(AttributeFactory.createAttribute(ldapAtt.getID(), 
+                              (String)ldapAtt.get())); 
+                  } 
+               }       
+            }
+            finally
+            {
+               if (results != null)
+                  results.close();
+            }            
+         }catch(NamingException ne)
+         {
+            log.error(ne);
+            return;
+         } 
+         results = null;
+      }
+      
+      mappedObject.addAll(attributeList);
+      mappingResult.setMappedObject(mappedObject);   
+   }
+
+   public void setMappingResult(MappingResult<List<Attribute<String>>> result)
+   {
+      this.mappingResult = result;
+   }
+
+   public boolean supports(Class<?> clazz)
+   { 
+      if(Attribute.class.isAssignableFrom(clazz))
+        return true;
+      
+      return false;
+   } 
+   
+   
+   @SuppressWarnings("unchecked")
+   private InitialLdapContext constructInitialLdapContext(String dn, Object credential) throws NamingException
+   {
+      Properties env = new Properties();
+      Iterator iter = options.entrySet().iterator();
+      while (iter.hasNext())
+      {
+         Entry entry = (Entry) iter.next();
+         env.put(entry.getKey(), entry.getValue());
+      }
+
+      // Set defaults for key values if they are missing
+      String factoryName = env.getProperty(Context.INITIAL_CONTEXT_FACTORY);
+      if (factoryName == null)
+      {
+         factoryName = "com.sun.jndi.ldap.LdapCtxFactory";
+         env.setProperty(Context.INITIAL_CONTEXT_FACTORY, factoryName);
+      }
+      String authType = env.getProperty(Context.SECURITY_AUTHENTICATION);
+      if (authType == null)
+         env.setProperty(Context.SECURITY_AUTHENTICATION, "simple");
+      String protocol = env.getProperty(Context.SECURITY_PROTOCOL);
+      String providerURL = (String) options.get(Context.PROVIDER_URL);
+      if (providerURL == null)
+         providerURL = "ldap://localhost:" + ((protocol != null && protocol.equals("ssl")) ? "636" : "389");
+
+      env.setProperty(Context.PROVIDER_URL, providerURL);
+      // JBAS-3555, allow anonymous login with no bindDN and bindCredential
+      if (dn != null)
+         env.setProperty(Context.SECURITY_PRINCIPAL, dn);
+      if (credential != null)
+         env.put(Context.SECURITY_CREDENTIALS, credential);
+      traceLdapEnv(env);
+      return new InitialLdapContext(env, null);
+   }
+   
+   private void traceLdapEnv(Properties env)
+   {
+      if (trace)
+      {
+         Properties tmp = new Properties();
+         tmp.putAll(env);
+         tmp.setProperty(Context.SECURITY_CREDENTIALS, "***");
+         log.trace("Logging into LDAP server, env=" + tmp.toString());
+      }
+   }
+   
+   private String[] getNeededAttributes(String commaSeparatedList)
+   {
+      ArrayList<String> arrayList = new ArrayList<String>();
+      StringTokenizer st = new StringTokenizer(commaSeparatedList,",");
+      while(st.hasMoreTokens())
+      {
+         arrayList.add(st.nextToken());
+      }
+      String[] strArr = new String[arrayList.size()];
+      return arrayList.toArray(strArr); 
+   }
+}
\ No newline at end of file

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/MappingProvidersDecodeAction.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/MappingProvidersDecodeAction.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/mapping/providers/attribute/MappingProvidersDecodeAction.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -0,0 +1,100 @@
+/*
+* JBoss, Home of Professional Open Source
+* Copyright 2005, JBoss Inc., and individual contributors as indicated
+* by the @authors tag. See the copyright.txt in the distribution for a
+* full listing of individual contributors.
+*
+* This is free software; you can redistribute it and/or modify it
+* under the terms of the GNU Lesser General Public License as
+* published by the Free Software Foundation; either version 2.1 of
+* the License, or (at your option) any later version.
+*
+* This software is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* Lesser General Public License for more details.
+*
+* You should have received a copy of the GNU Lesser General Public
+* License along with this software; if not, write to the Free
+* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+*/
+package org.jboss.security.mapping.providers.attribute;
+
+import java.security.AccessController;
+import java.security.PrivilegedActionException;
+import java.security.PrivilegedExceptionAction;
+
+import javax.management.MBeanServer;
+import javax.management.ObjectName;
+
+import org.jboss.mx.util.MBeanServerLocator;
+
+/**
+ * PriviledgedActions used by login modules for decoding passwords
+ * 
+ * @author Scott.Stark at jboss.org
+ * @version $Revision: 92021 $
+ */
+class MappingProvidersDecodeAction implements PrivilegedExceptionAction<Object>
+{
+   /** The permission required to access decode, decode64 */
+   private static final RuntimePermission decodePermission =
+      new RuntimePermission("org.jboss.security.auth.spi.DecodeAction.decode"); 
+   
+   String password;
+   ObjectName serviceName;
+
+   MappingProvidersDecodeAction(String password, ObjectName serviceName)
+   {
+      this.password = password;
+      this.serviceName = serviceName;
+   }
+
+   /**
+    * 
+    * @return
+    * @throws Exception
+    */
+   public Object run() throws Exception
+   {  
+      // Invoke the decodeb64 op
+      byte[] secret = decode64(password);
+      // Convert to UTF-8 base char array
+      String secretPassword = new String(secret, "UTF-8");
+      return secretPassword.toCharArray();
+   }
+   
+   /** Decrypt the secret using the cipherKey.
+   *
+   * @param secret - the encrypted secret to decrypt.
+   * @return the decrypted secret
+   * @throws Exception
+   */
+  private byte[] decode64(String secret)
+     throws Exception
+  {
+     SecurityManager sm = System.getSecurityManager();
+     if( sm != null )
+        sm.checkPermission(decodePermission);
+
+     MBeanServer server = MBeanServerLocator.locateJBoss();
+     return (byte[]) server.invoke(serviceName, "decode64", new Object[] {secret}, 
+           new String[] {String.class.getName()});
+  }
+  
+   static char[] decode(String password, ObjectName serviceName)
+      throws Exception
+   {
+      MappingProvidersDecodeAction action = new MappingProvidersDecodeAction(password, serviceName);
+      try
+      {
+         char[] decode = (char[]) AccessController.doPrivileged(action);
+         return decode;
+      }
+      catch(PrivilegedActionException e)
+      {
+         throw e.getException();
+      }
+   }
+}

Modified: projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java	2009-08-05 21:41:22 UTC (rev 92034)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/main/java/org/jboss/security/plugins/mapping/JBossMappingManager.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -54,9 +54,38 @@
      this.securityDomain = domain;   
    }
    
+   
+   public <T> MappingContext<T> getMappingContext(String mappingType)
+   {
+      //Apply Mapping Logic  
+      ApplicationPolicy aPolicy = SecurityConfiguration.getApplicationPolicy(securityDomain);
+      
+      if(aPolicy == null)
+      {
+         String defaultDomain = SecurityConstants.DEFAULT_APPLICATION_POLICY;
+         if(trace)
+            log.trace("Application Policy not found for domain=" + securityDomain +
+                  ".Mapping framework will use the default domain:" + defaultDomain);
+         aPolicy = SecurityConfiguration.getApplicationPolicy(defaultDomain); 
+      } 
+      if(aPolicy == null )
+         throw new IllegalStateException("Application Policy is null for the security domain:" 
+               + securityDomain);
+      
+      MappingContext<T> mc = null;
+      MappingInfo rmi = aPolicy.getMappingInfo(mappingType);  
+
+      if( rmi != null)
+         mc = generateMappingContext(mc, rmi);
+      
+      return mc; 
+   }
+   
+   
    /**
     * @see SecurityContext#getMappingContext(String)
     */
+   @SuppressWarnings("deprecation")
    public <T> MappingContext<T> getMappingContext(Class<T> mappingType)
    { 
       //Apply Mapping Logic  
@@ -76,22 +105,25 @@
       
       MappingContext<T> mc = null;
       MappingInfo rmi = aPolicy.getMappingInfo(mappingType); 
+      if( rmi != null)
+        mc = generateMappingContext(mc, rmi);
       
-      if(rmi != null)
-      {
-         MappingModuleEntry[] mpe = rmi.getMappingModuleEntry();
-         ArrayList<MappingProvider<T>> al = new ArrayList<MappingProvider<T>>();
-         
-         for(int i = 0 ; i < mpe.length; i++)
-         { 
-            MappingProvider<T> mp = getMappingProvider(mpe[i]);
-            if(mp != null)
-               al.add(mp); 
-         }
-         mc = new MappingContext<T>(al); 
+      return mc; 
+   }
+
+
+   private <T> MappingContext<T> generateMappingContext(MappingContext<T> mc, MappingInfo rmi)
+   {
+      MappingModuleEntry[] mpe = rmi.getMappingModuleEntry();
+      ArrayList<MappingProvider<T>> al = new ArrayList<MappingProvider<T>>();
+
+      for(int i = 0 ; i < mpe.length; i++)
+      { 
+         MappingProvider<T> mp = getMappingProvider(mpe[i]);
+         if(mp != null)
+            al.add(mp); 
       }
-      
-      return mc; 
+      return new MappingContext<T>(al); 
    } 
     
    public String getSecurityDomain()

Modified: projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java	2009-08-05 21:41:22 UTC (rev 92034)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestCase.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -88,6 +88,8 @@
       
       opends = new OpenDS();
       opends.intialize(openDSDir);
+      if(opends.isRunning())
+         opends.stopServer();
       opends.startServer();
       assertTrue(opends.isRunning()); 
    }

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestsAdapter.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestsAdapter.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/ldap/OpenDSUnitTestsAdapter.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -0,0 +1,41 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.ldap;
+
+/**
+ * Adapter for the OpenDS unit tests
+ * @author Anil.Saldhana at redhat.com
+ */
+public class OpenDSUnitTestsAdapter extends OpenDSUnitTestCase
+{
+   public OpenDSUnitTestsAdapter(String name)
+   {
+      super(name);
+   }
+   
+
+   @Override
+   public void testLDAPAddDelete() throws Exception
+   {  
+   }  
+
+}
\ No newline at end of file

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/mapping/LdapAttributeMappingProviderUnitTestCase.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/mapping/LdapAttributeMappingProviderUnitTestCase.java	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/security/mapping/LdapAttributeMappingProviderUnitTestCase.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -0,0 +1,138 @@
+/*
+ * JBoss, Home of Professional Open Source.
+ * Copyright 2008, Red Hat Middleware LLC, and individual contributors
+ * as indicated by the @author tags. See the copyright.txt file in the
+ * distribution for a full listing of individual contributors. 
+ *
+ * This is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU Lesser General Public License as
+ * published by the Free Software Foundation; either version 2.1 of
+ * the License, or (at your option) any later version.
+ *
+ * This software is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ * Lesser General Public License for more details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this software; if not, write to the Free
+ * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
+ * 02110-1301 USA, or see the FSF site: http://www.fsf.org.
+ */
+package org.jboss.test.security.mapping;
+
+import java.io.File;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+
+import junit.framework.Test;
+import junit.framework.TestSuite;
+
+import org.jboss.security.SecurityConstants;
+import org.jboss.security.SecurityContext;
+import org.jboss.security.SecurityContextFactory;
+import org.jboss.security.SimplePrincipal;
+import org.jboss.security.config.ApplicationPolicy;
+import org.jboss.security.config.MappingInfo;
+import org.jboss.security.config.ModuleOption;
+import org.jboss.security.config.SecurityConfiguration;
+import org.jboss.security.identity.Attribute;
+import org.jboss.security.mapping.MappingContext;
+import org.jboss.security.mapping.MappingManager;
+import org.jboss.security.mapping.MappingType;
+import org.jboss.security.mapping.config.MappingModuleEntry;
+import org.jboss.security.mapping.providers.attribute.LdapAttributeMappingProvider;
+import org.jboss.test.security.ldap.OpenDSUnitTestsAdapter;
+
+/**
+ * LdapAttributeMappingProvider tests
+ * @author Anil.Saldhana at redhat.com
+ */
+public class LdapAttributeMappingProviderUnitTestCase extends OpenDSUnitTestsAdapter
+{
+   public static Test suite() throws Exception
+   {
+      TestSuite suite = new TestSuite();
+      suite.addTest(new LdapAttributeMappingProviderUnitTestCase("testLDAPAttributes")); 
+      return suite;
+   }
+   
+   public LdapAttributeMappingProviderUnitTestCase(String name)
+   {
+      super(name); 
+   }
+
+   protected void setUp() throws Exception
+   {
+      super.setUp();
+      ApplicationPolicy ap = new ApplicationPolicy("test"); 
+      SecurityConfiguration.addApplicationPolicy(ap);
+      
+      //Let us add the ldapAttributes.ldif
+      String fileName = targetDir + "ldap" + fs + "ldapAttributes.ldif";
+      boolean op = util.addLDIF(serverHost, port, adminDN, adminPW, new File(fileName).toURL());
+      assertTrue(op);
+   }
+   
+   public void testLDAPAttributes() throws Exception
+   {  
+      ApplicationPolicy ap = SecurityConfiguration.getApplicationPolicy("test"); 
+      MappingModuleEntry mme = new MappingModuleEntry(LdapAttributeMappingProvider.class.getName());
+      
+      String attributeList = "mail,cn,commonname,givenname,surname,employeeType," +
+                       "employeeNumber,facsimileTelephoneNumber";
+      mme.add(new ModuleOption("bindDN",this.adminDN));
+      mme.add(new ModuleOption("bindCredential",this.adminPW));
+      mme.add(new ModuleOption("baseFilter","(uid={0})"));
+      mme.add(new ModuleOption("java.naming.provider.url", "ldap://" + serverHost  + ":" + port));
+      mme.add(new ModuleOption("baseCtxDN", "ou=People,dc=jboss,dc=org"));
+      mme.add(new ModuleOption("attributeList", attributeList));
+
+      MappingInfo attributeMappingInfo = new MappingInfo();
+      attributeMappingInfo.add(mme);
+      ap.setMappingInfo(MappingType.ATTRIBUTE.name(),attributeMappingInfo); 
+      
+      SecurityContext sc = SecurityContextFactory.createSecurityContext("test");
+      MappingManager mm = sc.getMappingManager();
+      assertNotNull("MappingManager != null", mm);
+      
+      MappingContext<List<Attribute<String>>> mc = mm.getMappingContext(MappingType.ATTRIBUTE.name());
+      assertNotNull("MappingContext != null", mc);
+      HashMap<String,Object> map = new HashMap<String,Object>();
+     
+      map.put(SecurityConstants.PRINCIPAL_IDENTIFIER, new SimplePrincipal("jduke"));
+      
+      List<Attribute<String>> attList = new ArrayList<Attribute<String>>();
+      
+      mc.performMapping(map, attList);
+      attList = (List<Attribute<String>>) mc.getMappingResult().getMappedObject(); 
+      
+      boolean foundEmail = false;
+      boolean foundEmployeeType = false;
+      boolean foundEmployeeNumber = false;
+      
+      for(Attribute<String> att: attList)
+      {
+         String attName = att.getName();
+         if(attName.equals(Attribute.TYPE.EMAIL_ADDRESS.get()))
+         {
+            assertEquals("theduke at somecastle.man",att.getValue());
+            foundEmail = true;
+         }
+         if(attName.equals("employeeType"))
+         {
+            assertEquals("permanent",att.getValue());
+            foundEmployeeType = true;
+         }
+         if(attName.equals("employeeNumber"))
+         {
+            assertEquals("007",att.getValue());
+            foundEmployeeNumber = true;
+         }
+      }
+      assertTrue("Found Email", foundEmail);
+      assertTrue("Found Emp Type", foundEmployeeType);
+      assertTrue("Found Emp Number", foundEmployeeNumber);
+   } 
+}
\ No newline at end of file

Modified: projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java	2009-08-05 21:41:22 UTC (rev 92034)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/securitycontext/MappingContextTestCase.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -21,18 +21,21 @@
   */
 package org.jboss.test.securitycontext; 
 
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 
 import org.jboss.security.SecurityConstants;
 import org.jboss.security.SecurityContext;
 import org.jboss.security.config.SecurityConfiguration;
+import org.jboss.security.identity.Attribute;
 import org.jboss.security.identity.RoleGroup;
 import org.jboss.security.identity.plugins.SimpleRole;
 import org.jboss.security.identity.plugins.SimpleRoleGroup;
 import org.jboss.security.mapping.MappingContext;
+import org.jboss.security.mapping.MappingType;
 
-//$Id$
 
 /**
  *  Test the various mapping providers
@@ -42,6 +45,7 @@
  */
 public class MappingContextTestCase extends SecurityContextBaseTest
 { 
+   @SuppressWarnings("deprecation")
    public void testDeploymentRolesProvider()
    {
       SecurityConfiguration.addApplicationPolicy(createApplicationPolicy(securityDomain));
@@ -59,8 +63,9 @@
       
       RoleGroup grp = new SimpleRoleGroup(SecurityConstants.ROLES_IDENTIFIER);
       grp.addRole(new SimpleRole("oldRole"));
-      //grp.addMember(new SimplePrincipal("oldRole"));
+
       MappingContext<RoleGroup> mc = sc.getMappingManager().getMappingContext(RoleGroup.class);
+      assertNotNull("Mapping Context is not null", mc);
       mc.performMapping(map, grp);
       
       grp = (RoleGroup) mc.getMappingResult().getMappedObject();
@@ -69,4 +74,36 @@
       assertTrue("t1 exists?",grp.containsRole(new SimpleRole("t1")));
       assertTrue("t2 exists?",grp.containsRole(new SimpleRole("t2")));
    }
+   
+   public void testAttributeProvider()
+   {
+      SecurityConfiguration.addApplicationPolicy(createApplicationPolicy(securityDomain));
+      SecurityContext sc= getSC(securityDomain);
+      HashSet<String> hs = new HashSet<String>();
+      hs.add("t1");
+      hs.add("t2");
+      
+      HashMap<String,Object> rolesMap = new HashMap<String,Object>();
+      rolesMap.put(principal.getName(), hs );
+      
+      HashMap<String,Object> map = new HashMap<String,Object>();
+      map.put(SecurityConstants.PRINCIPAL_IDENTIFIER, principal); 
+      
+      List<Attribute<String>> attrList = new ArrayList<Attribute<String>>(); 
+
+      MappingContext<List<Attribute<String>>> mc = sc.getMappingManager().getMappingContext(MappingType.ATTRIBUTE.name());
+      assertNotNull("Mapping Context is not null", mc);
+      mc.performMapping(map, attrList);
+      
+      attrList = (List<Attribute<String>>) mc.getMappingResult().getMappedObject();
+      
+      assertNotNull("Attribute List not null", attrList); 
+      
+      for(Attribute<?> att: attrList)
+      {
+         //Email address 
+         if(Attribute.TYPE.EMAIL_ADDRESS.get().equals(att.getName()))
+            assertEquals("anil at test", att.getValue());
+      }
+   }
 }
\ No newline at end of file

Modified: projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java	2009-08-05 21:41:22 UTC (rev 92034)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/test/java/org/jboss/test/securitycontext/SecurityContextBaseTest.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -28,9 +28,14 @@
 
 import org.jboss.security.SimplePrincipal;
 import org.jboss.security.config.ApplicationPolicy;
+import org.jboss.security.config.AttributeMappingInfo;
+import org.jboss.security.config.ModuleOption;
 import org.jboss.security.config.RoleMappingInfo;
 import org.jboss.security.config.SecurityConfiguration;
+import org.jboss.security.mapping.MappingType;
 import org.jboss.security.mapping.config.MappingModuleEntry;
+import org.jboss.security.mapping.providers.DeploymentRolesMappingProvider;
+import org.jboss.security.mapping.providers.attribute.DefaultAttributeMappingProvider;
 import org.jboss.security.plugins.JBossSecurityContext;
 
 //$Id$
@@ -47,7 +52,8 @@
    protected Object cred = "hello";
    protected String securityDomain = "other";
    
-   private String mappingModule = "org.jboss.security.mapping.providers.DeploymentRolesMappingProvider";
+   private String roleMappingModule = DeploymentRolesMappingProvider.class.getName();
+   private String attrMappingModule = DefaultAttributeMappingProvider.class.getName();
    
    public void testSecurityConfiguration()
    {
@@ -66,24 +72,36 @@
    protected ApplicationPolicy createApplicationPolicy(String domain)
    {
       ApplicationPolicy ap = new ApplicationPolicy(domain);
-      ap.setRoleMappingInfo(createRoleMappingInfo(domain));
+      ap.setMappingInfo(MappingType.ROLE.name(), createRoleMappingInfo(domain)); 
+      ap.setMappingInfo(MappingType.ATTRIBUTE.name(), this.createAttributeMappingInfo(domain));
       return ap; 
    }
    
    protected ApplicationPolicy createApplicationPolicy(String domain, RoleMappingInfo rmi)
    {
       ApplicationPolicy ap = new ApplicationPolicy(domain);
-      ap.setRoleMappingInfo(rmi);
+      ap.setMappingInfo(MappingType.ROLE.name(), rmi); 
       return ap; 
    }
    
    protected RoleMappingInfo createRoleMappingInfo(String domain)
    { 
       RoleMappingInfo rmi = new RoleMappingInfo(domain);
-      rmi.add(new MappingModuleEntry(this.mappingModule));
+      rmi.add(new MappingModuleEntry(this.roleMappingModule));
       return rmi;
    }
    
+   protected AttributeMappingInfo createAttributeMappingInfo(String domain)
+   { 
+      AttributeMappingInfo rmi = new AttributeMappingInfo(domain);
+      MappingModuleEntry mme = new MappingModuleEntry(this.attrMappingModule); 
+      
+      ModuleOption option = new ModuleOption("anil.email", "anil at test");
+      mme.add(option);
+      rmi.add(mme);
+      return rmi;
+   }
+   
    protected RoleMappingInfo createRoleMappingInfo(String domain, List<String> moduleNames)
    {
       RoleMappingInfo rmi = new RoleMappingInfo(domain);

Added: projects/security/security-jboss-sx/trunk/jbosssx/src/test/resources/ldap/ldapAttributes.ldif
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx/src/test/resources/ldap/ldapAttributes.ldif	                        (rev 0)
+++ projects/security/security-jboss-sx/trunk/jbosssx/src/test/resources/ldap/ldapAttributes.ldif	2009-08-05 21:42:30 UTC (rev 92035)
@@ -0,0 +1,23 @@
+dn: dc=jboss,dc=org
+objectclass: dcObject
+objectclass: organization
+o: JBoss
+dc: JBoss
+
+dn: ou=People,dc=jboss,dc=org
+objectclass: top
+objectclass: organizationalUnit
+ou: People
+
+dn: uid=jduke,ou=People,dc=jboss,dc=org
+objectclass: top
+objectclass: uidObject
+objectclass: person
+objectclass: inetOrgPerson
+uid: jduke
+cn: Java Duke
+sn: Duke
+userPassword: theduke
+mail: theduke at somecastle.man
+employeeType:  permanent
+employeeNumber: 007

Modified: projects/security/security-jboss-sx/trunk/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java
===================================================================
--- projects/security/security-jboss-sx/trunk/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java	2009-08-05 21:41:22 UTC (rev 92034)
+++ projects/security/security-jboss-sx/trunk/jbosssx-mc-int/src/test/java/org/jboss/test/security/microcontainer/metadata/support/MockMappingManager.java	2009-08-05 21:42:30 UTC (rev 92035)
@@ -61,6 +61,16 @@
    /*
     * (non-Javadoc)
     * 
+    * @see org.jboss.security.mapping.MappingManager#getMappingContext(java.lang.Class)
+    */
+   public <T> MappingContext<T> getMappingContext(String type)
+   {
+      return null;
+   }
+   
+   /*
+    * (non-Javadoc)
+    * 
     * @see org.jboss.security.BaseSecurityManager#getSecurityDomain()
     */
    public String getSecurityDomain()




More information about the jboss-cvs-commits mailing list