Improved error message for malformed property values on JNDI Directory Data Connector.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / aa / attrresolv / provider / JNDIDirectoryDataConnector.java
1 /* 
2  * The Shibboleth License, Version 1. 
3  * Copyright (c) 2002 
4  * University Corporation for Advanced Internet Development, Inc. 
5  * All rights reserved
6  * 
7  * 
8  * Redistribution and use in source and binary forms, with or without 
9  * modification, are permitted provided that the following conditions are met:
10  * 
11  * Redistributions of source code must retain the above copyright notice, this 
12  * list of conditions and the following disclaimer.
13  * 
14  * Redistributions in binary form must reproduce the above copyright notice, 
15  * this list of conditions and the following disclaimer in the documentation 
16  * and/or other materials provided with the distribution, if any, must include 
17  * the following acknowledgment: "This product includes software developed by 
18  * the University Corporation for Advanced Internet Development 
19  * <http://www.ucaid.edu>Internet2 Project. Alternately, this acknowledegement 
20  * may appear in the software itself, if and wherever such third-party 
21  * acknowledgments normally appear.
22  * 
23  * Neither the name of Shibboleth nor the names of its contributors, nor 
24  * Internet2, nor the University Corporation for Advanced Internet Development, 
25  * Inc., nor UCAID may be used to endorse or promote products derived from this 
26  * software without specific prior written permission. For written permission, 
27  * please contact shibboleth@shibboleth.org
28  * 
29  * Products derived from this software may not be called Shibboleth, Internet2, 
30  * UCAID, or the University Corporation for Advanced Internet Development, nor 
31  * may Shibboleth appear in their name, without prior written permission of the 
32  * University Corporation for Advanced Internet Development.
33  * 
34  * 
35  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 
36  * AND WITH ALL FAULTS. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
37  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 
38  * PARTICULAR PURPOSE, AND NON-INFRINGEMENT ARE DISCLAIMED AND THE ENTIRE RISK 
39  * OF SATISFACTORY QUALITY, PERFORMANCE, ACCURACY, AND EFFORT IS WITH LICENSEE. 
40  * IN NO EVENT SHALL THE COPYRIGHT OWNER, CONTRIBUTORS OR THE UNIVERSITY 
41  * CORPORATION FOR ADVANCED INTERNET DEVELOPMENT, INC. BE LIABLE FOR ANY DIRECT, 
42  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES 
43  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
44  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND 
45  * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
46  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS 
47  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
48  */
49
50 package edu.internet2.middleware.shibboleth.aa.attrresolv.provider;
51
52 import java.security.Principal;
53 import java.util.Properties;
54
55 import javax.naming.CommunicationException;
56 import javax.naming.NamingEnumeration;
57 import javax.naming.NamingException;
58 import javax.naming.directory.Attributes;
59 import javax.naming.directory.InitialDirContext;
60 import javax.naming.directory.SearchControls;
61 import javax.naming.directory.SearchResult;
62
63 import org.apache.log4j.Logger;
64 import org.w3c.dom.Element;
65 import org.w3c.dom.NodeList;
66
67 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
68 import edu.internet2.middleware.shibboleth.aa.attrresolv.DataConnectorPlugIn;
69 import edu.internet2.middleware.shibboleth.aa.attrresolv.Dependencies;
70 import edu.internet2.middleware.shibboleth.aa.attrresolv.ResolutionPlugInException;
71
72 /**
73  * <code>DataConnectorPlugIn</code> implementation that utilizes a user-specified JNDI 
74  * <code>DirContext</code> to retrieve attribute data.
75  * 
76  * @author Walter Hoehn (wassa@columbia.edu)
77  *
78  */
79 public class JNDIDirectoryDataConnector extends BaseDataConnector implements DataConnectorPlugIn {
80
81         private static Logger log = Logger.getLogger(JNDIDirectoryDataConnector.class.getName());
82         protected String searchFilter;
83         protected Properties properties;
84         protected SearchControls controls;
85     protected String failover = null;
86
87     /**
88      * Constructs a DataConnector based on DOM configuration.
89      * 
90      * @param e a &lt;JNDIDirectoryDataConnector /&gt; DOM Element as specified by 
91      * urn:mace:shibboleth:resolver:1.0
92      * 
93      * @throws ResolutionPlugInException if the PlugIn cannot be initialized
94      */
95         public JNDIDirectoryDataConnector(Element e) throws ResolutionPlugInException {
96
97                 super(e);
98         
99                 NodeList searchNodes = e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "Search");
100                 if (searchNodes.getLength() != 1) {
101                         log.error("JNDI Directory Data Connector requires a \"Search\" specification.");
102                         throw new ResolutionPlugInException("JNDI Directory Data Connector requires a \"Search\" specification.");
103                 }
104
105                 String searchFilterSpec = ((Element) searchNodes.item(0)).getAttribute("filter");
106                 if (searchFilterSpec != null && !searchFilterSpec.equals("")) {
107                         searchFilter = searchFilterSpec;
108                         log.debug("Search Filter: (" + searchFilter + ").");
109                 } else {
110                         log.error("Search spec requires a filter attribute.");
111                         throw new ResolutionPlugInException("Search spec requires a filter attribute.");
112                 }
113
114                 defineSearchControls(((Element) searchNodes.item(0)));
115
116                 NodeList propertyNodes = e.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "Property");
117                 properties = new Properties(System.getProperties());
118                 for (int i = 0; propertyNodes.getLength() > i; i++) {
119                         Element property = (Element) propertyNodes.item(i);
120                         String propName = property.getAttribute("name");
121                         String propValue = property.getAttribute("value");
122
123                         log.debug("Property: (" + propName + ").");
124                         log.debug("   Value: (" + propValue + ").");
125
126                         if (propName == null || propName.equals("")) {
127                                 log.error("Property (" + propName + ") is malformed.  Connot accept empty property name.");
128                                 throw new ResolutionPlugInException("Property is malformed.");
129                         } else if (propValue == null || propValue.equals("")) {
130                                 log.error("Property (" + propName + ") is malformed.  Cannot accept empty property value.");
131                                 throw new ResolutionPlugInException("Property is malformed.");
132                         } else {
133                                 properties.setProperty(propName, propValue);
134                         }
135                 }
136
137         //Fail-fast connection test
138                 InitialDirContext context = null;
139                 try {
140                         context = new InitialDirContext(properties);
141                         log.debug("JNDI Directory context activated.");
142                         
143                 } catch (NamingException e1) {
144                         log.error("Failed to startup directory context: " + e1);
145                         throw new ResolutionPlugInException("Failed to startup directory context.");
146                 } finally {
147                         try {
148                                 if (context != null) {
149                                         context.close();
150                                 }
151                         } catch (NamingException ne) {
152                                 log.error("An error occured while closing the JNDI context: " + e);
153                         }
154
155                 }
156         }
157
158     /**
159      * Create JNDI search controls based on DOM configuration
160      * @param searchNode a &lt;Controls /&gt; DOM Element as specified by 
161      * urn:mace:shibboleth:resolver:1.0
162      */
163         protected void defineSearchControls(Element searchNode) {
164
165                 controls = new SearchControls();
166
167                 NodeList controlNodes = searchNode.getElementsByTagNameNS(AttributeResolver.resolverNamespace, "Controls");
168                 if (controlNodes.getLength() < 1) {
169                         log.debug("No Search Control spec found.");
170                 } else {
171                         if (controlNodes.getLength() > 1) {
172                                 log.error("Found multiple Search Control specs for a Connector.  Ignoring all but the first.");
173                         }
174
175                         String searchScopeSpec = ((Element) controlNodes.item(0)).getAttribute("searchScope");
176                         if (searchScopeSpec != null && !searchScopeSpec.equals("")) {
177                                 if (searchScopeSpec.equals("OBJECT_SCOPE")) {
178                                         controls.setSearchScope(SearchControls.OBJECT_SCOPE);
179                                 } else if (searchScopeSpec.equals("ONELEVEL_SCOPE")) {
180                                         controls.setSearchScope(SearchControls.ONELEVEL_SCOPE);
181                                 } else if (searchScopeSpec.equals("SUBTREE_SCOPE")) {
182                                         controls.setSearchScope(SearchControls.SUBTREE_SCOPE);
183                                 } else {
184                                         try {
185                                                 controls.setSearchScope(Integer.parseInt(searchScopeSpec));
186                                         } catch (NumberFormatException nfe) {
187                                                 log.error("Control spec included an invalid (searchScope) attribute value.");
188                                         }
189                                 }
190                         }
191
192                         String timeLimitSpec = ((Element) controlNodes.item(0)).getAttribute("timeLimit");
193                         if (timeLimitSpec != null && !timeLimitSpec.equals("")) {
194                                 try {
195                                         controls.setTimeLimit(Integer.parseInt(timeLimitSpec));
196                                 } catch (NumberFormatException nfe) {
197                                         log.error("Control spec included an invalid (timeLimit) attribute value.");
198                                 }
199                         }
200
201                         String returningObjectsSpec = ((Element) controlNodes.item(0)).getAttribute("returningObjects");
202                         if (returningObjectsSpec != null && !returningObjectsSpec.equals("")) {
203                                 controls.setReturningObjFlag(new Boolean(returningObjectsSpec).booleanValue());
204                         }
205
206                         String linkDereferencingSpec = ((Element) controlNodes.item(0)).getAttribute("linkDereferencing");
207                         if (linkDereferencingSpec != null && !linkDereferencingSpec.equals("")) {
208                                 if (linkDereferencingSpec != null && !linkDereferencingSpec.equals("")) {
209                                         controls.setDerefLinkFlag(new Boolean(linkDereferencingSpec).booleanValue());
210                                 }
211                         }
212
213                         String countLimitSpec = ((Element) controlNodes.item(0)).getAttribute("countLimit");
214                         if (countLimitSpec != null && !countLimitSpec.equals("")) {
215                                 try {
216                                         controls.setCountLimit(Long.parseLong(countLimitSpec));
217                                 } catch (NumberFormatException nfe) {
218                                         log.error("Control spec included an invalid (countLimit) attribute value.");
219                                 }
220                         }
221                 }
222
223                 if (log.isDebugEnabled()) {
224                         log.debug("Search Control (searchScope): " + controls.getSearchScope());
225                         log.debug("Search Control (timeLimit): " + controls.getTimeLimit());
226                         log.debug("Search Control (returningObjects): " + controls.getReturningObjFlag());
227                         log.debug("Search Control (linkDereferencing): " + controls.getDerefLinkFlag());
228                         log.debug("Search Control (countLimit): " + controls.getCountLimit());
229                 }
230         }
231
232         /**
233          * @see edu.internet2.middleware.shibboleth.aa.attrresolv.DataConnectorPlugIn#resolve(java.security.Principal)
234          */
235         public Attributes resolve(Principal principal, String requester, Dependencies depends)
236                 throws ResolutionPlugInException {
237
238                 InitialDirContext context = null;
239                 try {
240                         context = new InitialDirContext(properties);
241                         NamingEnumeration nEnumeration = null;
242
243                         try {
244                                 nEnumeration = context.search("", searchFilter.replaceAll("%PRINCIPAL%", principal.getName()), controls);
245                         } catch (CommunicationException e) {
246                                 log.debug(e);
247                                 log.warn(
248                                         "Encountered a connection problem while querying for attributes.  Re-initializing JNDI context and retrying...");
249                                 context = new InitialDirContext(context.getEnvironment());
250                                 nEnumeration = context.search("", searchFilter.replaceAll("%PRINCIPAL%", principal.getName()), controls);
251                         }
252
253                         if (nEnumeration == null || !nEnumeration.hasMore()) {
254                                 log.error("Could not locate a principal with the name (" + principal.getName() + ").");
255                                 throw new ResolutionPlugInException("No data available for this principal.");
256                         }
257
258                         SearchResult result = (SearchResult) nEnumeration.next();
259                         Attributes attributes = result.getAttributes();
260
261                         if (nEnumeration.hasMore()) {
262                                 log.error("Unable to disambiguate date for principal (" + principal.getName() + ") in search.");
263                                 throw new ResolutionPlugInException("Cannot disambiguate data for this principal.");
264                         }
265
266                         return attributes;
267
268                 } catch (NamingException e) {
269                         log.error(
270                                 "An error occurred while retieving data for principal ("
271                                         + principal.getName()
272                                         + ") :"
273                                         + e.getMessage());
274                         throw new ResolutionPlugInException("Error retrieving data for principal.");
275                 } finally {
276                         try {
277                                 if (context != null) {
278                                         context.close();
279                                 }
280                         } catch (NamingException e) {
281                                 log.error("An error occured while closing the JNDI context: " + e);
282                         }
283                 }
284         }
285 }