Begin AA refactoring for multiple Name Formats and New SAML Name Identifier class.
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / aa / AAServlet.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;
51
52 import java.io.ByteArrayOutputStream;
53 import java.io.IOException;
54 import java.io.PrintStream;
55 import java.net.MalformedURLException;
56 import java.net.URI;
57 import java.net.URISyntaxException;
58 import java.net.URL;
59 import java.security.Principal;
60 import java.util.ArrayList;
61 import java.util.Arrays;
62 import java.util.Enumeration;
63 import java.util.Iterator;
64 import java.util.List;
65 import java.util.Properties;
66
67 import javax.servlet.ServletException;
68 import javax.servlet.UnavailableException;
69 import javax.servlet.http.HttpServlet;
70 import javax.servlet.http.HttpServletRequest;
71 import javax.servlet.http.HttpServletResponse;
72
73 import org.apache.log4j.Logger;
74 import org.apache.log4j.MDC;
75 import org.opensaml.QName;
76 import org.opensaml.SAMLAttribute;
77 import org.opensaml.SAMLAttributeQuery;
78 import org.opensaml.SAMLBinding;
79 import org.opensaml.SAMLException;
80 import org.opensaml.SAMLIdentifier;
81 import org.opensaml.SAMLRequest;
82
83 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
84 import edu.internet2.middleware.shibboleth.aa.arp.ArpException;
85 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
86 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolverException;
87 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
88 import edu.internet2.middleware.shibboleth.common.SAMLBindingFactory;
89 import edu.internet2.middleware.shibboleth.common.ShibResource;
90
91 /**
92  *  Attribute Authority & Release Policy
93  *  Handles Initialization and incoming requests to AA
94  *
95  * @author Parviz Dousti (dousti@cmu.edu)
96  * @author      Walter Hoehn (wassa@columbia.edu)
97  */
98
99 public class AAServlet extends HttpServlet {
100
101     protected AAResponder responder;
102         private SAMLBinding binding;
103
104     protected Properties configuration;
105     private static Logger log = Logger.getLogger(AAServlet.class.getName());    
106     
107         public void init() throws ServletException {
108                 super.init();
109
110                 MDC.put("serviceId", "[AA] Core");
111                 log.info("Initializing Attribute Authority.");
112
113                 try {
114
115                         configuration = loadConfiguration();
116
117                         ArpEngine arpEngine = new ArpEngine(configuration);
118                         AttributeResolver resolver = new AttributeResolver(configuration);
119
120                         handleRepository = HandleRepositoryFactory.getInstance(configuration);
121
122                         responder = new AAResponder(arpEngine, resolver);
123                         
124                         binding = SAMLBindingFactory.getInstance(SAMLBinding.SAML_SOAP_HTTPS);
125
126                         log.info("Attribute Authority initialization complete.");
127
128                 } catch (ArpException ae) {
129                         log.fatal("The AA could not be initialized due to a problem with the ARP Engine configuration: " + ae);
130                         throw new UnavailableException("Attribute Authority failed to initialize.");
131                 } catch (AttributeResolverException ne) {
132                         log.fatal("The AA could not be initialized due to a problem with the Attribute Resolver configuration: " + ne);
133                         throw new UnavailableException("Attribute Authority failed to initialize.");
134                 } catch (AAException ae) {
135                         log.fatal("The AA could not be initialized: " + ae);
136                         throw new UnavailableException("Attribute Authority failed to initialize.");
137                 } catch (HandleRepositoryException he) {
138                         log.fatal(
139                                 "The AA could not be initialized due to a problem with the Handle Repository configuration: " + he);
140                         throw new UnavailableException("Attribute Authority failed to initialize.");
141                 }
142         }
143         protected Properties loadConfiguration() throws AAException {
144
145                 //Set defaults
146                 Properties defaultProps = new Properties();
147                 defaultProps.setProperty(
148                         "edu.internet2.middleware.shibboleth.aa.arp.provider.FileSystemArpRepository.Path",
149                         "/conf/arps/");
150                 defaultProps.setProperty(
151                                         "edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver.ResolverConfig",
152                                         "/conf/resolver.xml");
153                 defaultProps.setProperty(
154                         "edu.internet2.middleware.shibboleth.aa.arp.ArpRepository.implementation",
155                         "edu.internet2.middleware.shibboleth.aa.arp.provider.FileSystemArpRepository");
156                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.audiences", "urn:mace:inqueue");
157                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.aa.AAServlet.passThruErrors", "false");
158
159                 //Load from file
160                 Properties properties = new Properties(defaultProps);
161                 String propertiesFileLocation = getInitParameter("OriginPropertiesFile");
162                 if (propertiesFileLocation == null) {
163                         propertiesFileLocation = "/conf/origin.properties";
164                 }
165                 try {
166                         log.debug("Loading Configuration from (" + propertiesFileLocation + ").");
167                         properties.load(new ShibResource(propertiesFileLocation, this.getClass()).getInputStream());
168
169                         //Make sure we have all required parameters
170                         StringBuffer missingProperties = new StringBuffer();
171                         String[] requiredProperties =
172                                 {
173                     "edu.internet2.middleware.shibboleth.hs.HandleServlet.siteName",
174                                         "edu.internet2.middleware.shibboleth.aa.AAServlet.authorityName",
175                                         "edu.internet2.middleware.shibboleth.aa.arp.ArpRepository.implementation",
176                                         "edu.internet2.middleware.shibboleth.audiences" };
177
178                         for (int i = 0; i < requiredProperties.length; i++) {
179                                 if (properties.getProperty(requiredProperties[i]) == null) {
180                                         missingProperties.append("\"");
181                                         missingProperties.append(requiredProperties[i]);
182                                         missingProperties.append("\" ");
183                                 }
184                         }
185                         if (missingProperties.length() > 0) {
186                                 log.error(
187                                         "Missing configuration data.  The following configuration properites have not been set: "
188                                                 + missingProperties.toString());
189                                 throw new AAException("Missing configuration data.");
190                         }
191
192                 } catch (IOException e) {
193                         log.error("Could not load AA servlet configuration: " + e);
194                         throw new AAException("Could not load AA servlet configuration.");
195                 }
196
197                 if (log.isDebugEnabled()) {
198                         ByteArrayOutputStream debugStream = new ByteArrayOutputStream();
199                         PrintStream debugPrinter = new PrintStream(debugStream);
200                         properties.list(debugPrinter);
201                         log.debug(
202                                 "Runtime configuration parameters: " + System.getProperty("line.separator") + debugStream.toString());
203                         try {
204                                 debugStream.close();
205                         } catch (IOException e) {
206                                 log.error("Encountered a problem cleaning up resources: could not close debug stream.");
207                         }
208                 }
209                 
210                 //Be nice and trim "extra" whitespace from config properties
211                 Enumeration propNames = properties.propertyNames();
212                 while (propNames.hasMoreElements()) {
213                         String propName = (String) propNames.nextElement();
214                         if (properties.getProperty(propName, "").matches(".+\\s$")) {
215                                 log.debug(
216                                         "The configuration property ("
217                                                 + propName
218                                                 + ") contains trailing whitespace.  Trimming... ");
219                                 properties.setProperty(propName, properties.getProperty(propName).trim());
220                         }
221                 }
222
223                 return properties;
224         }
225
226         public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
227
228                 MDC.put("serviceId", "[AA] " + new SAMLIdentifier().toString());
229                 MDC.put("remoteAddr", req.getRemoteAddr());
230                 log.info("Handling request.");
231
232                 StringBuffer credentialName = new StringBuffer();
233                 SAMLRequest samlRequest = binding.receive(req, credentialName);
234                 if (samlRequest.getQuery() == null || !(samlRequest.getQuery() instanceof SAMLAttributeQuery)) {
235                         //TODO better exception
236                         throw new SAMLException(
237                                 SAMLException.REQUESTER,
238                                 "AASaml.receive() can only respond to a SAML Attribute Query");
239                 }
240                 SAMLAttributeQuery attributeQuery = (SAMLAttributeQuery) samlRequest.getQuery();
241
242                 try {
243
244                         if (!configuration
245                                 .getProperty("edu.internet2.middleware.shibboleth.hs.HandleServlet.siteName")
246                                 .equals(saml.getNameQualifier())) {
247                                 log.error(
248                                         "The name qualifier on this handle ("
249                                                 + saml.getNameQualifier()
250                                                 + ") does not match this site name.");
251                                 throw new InvalidHandleException(
252                                         "The name qualifier on this handle ("
253                                                 + saml.getNameQualifier()
254                                                 + ") does not match this site name.");
255                         }
256
257                         log.info("Attribute Query Handle for this request: (" + saml.getHandle() + ").");
258                         Principal principal = null;
259                         if (saml.getHandle().equalsIgnoreCase("foo")) {
260                                 // for testing
261                                 principal = new AuthNPrincipal("test-handle");
262                         } else {
263                                 principal = handleRepository.getPrincipal(saml.getHandle(), saml.getFormat());
264                         }
265
266                         URL resource = null;
267                         try {
268                                 if (attributeQuery.getResource() != null)
269                                         resource = new URL(attributeQuery.getResource());
270                         } catch (MalformedURLException mue) {
271                                 log.error(
272                                         "Request contained an improperly formatted resource identifier.  Attempting to "
273                                                 + "handle request without one.");
274                         }
275
276                         if (credentialName == null || credentialName.toString().equals("")) {
277                                 //TODO update messages
278                                 log.info("Request is from an unauthenticated SHAR.");
279                         } else {
280                                 log.info("Request is from SHAR: (" + credentialName + ").");
281                         }
282
283                         List attrs;
284                         Iterator requestedAttrsIterator = attributeQuery.getDesignators();
285                         if (requestedAttrsIterator.hasNext()) {
286                                 log.info("Request designates specific attributes, resolving this set.");
287                                 ArrayList requestedAttrs = new ArrayList();
288                                 while (requestedAttrsIterator.hasNext()) {
289                                         SAMLAttribute attribute = (SAMLAttribute) requestedAttrsIterator.next();
290                                         try {
291                                                 log.debug("Designated attribute: (" + attribute.getName() + ")");
292                                                 requestedAttrs.add(new URI(attribute.getName()));
293                                         } catch (URISyntaxException use) {
294                                                 log.error(
295                                                         "Request designated an attribute name that does not conform to the required URI syntax ("
296                                                                 + attribute.getName()
297                                                                 + ").  Ignoring this attribute");
298                                         }
299                                 }
300                                 attrs =
301                                         Arrays.asList(
302                                                 responder.getReleaseAttributes(
303                                                         principal,
304                                                         credentialName.toString(),
305                                                         resource,
306                                                         (URI[]) requestedAttrs.toArray(new URI[0])));
307                         } else {
308                                 log.info("Request does not designate specific attributes, resolving all available.");
309                                 attrs = Arrays.asList(responder.getReleaseAttributes(principal, saml.getShar(), resource));
310                         }
311
312                         log.info("Found " + attrs.size() + " attribute(s) for " + principal.getName());
313                         saml.respond(resp, attrs, null);
314                         log.info("Successfully responded about " + principal.getName());
315
316                         //TODO place transaction log statement here
317
318                 } catch (InvalidHandleException e) {
319                         log.info("Could not associate the Attribute Query Handle with a principal: " + e);
320                         try {
321                                 QName[] codes =
322                                         {
323                                                 SAMLException.REQUESTER,
324                                                 new QName(edu.internet2.middleware.shibboleth.common.XML.SHIB_NS, "InvalidHandle")};
325                                 if (configuration
326                                         .getProperty("edu.internet2.middleware.shibboleth.aa.AAServlet.passThruErrors", "false")
327                                         .equals("true")) {
328                                         saml.fail(
329                                                 resp,
330                                                 new SAMLException(
331                                                         Arrays.asList(codes),
332                                                         "The supplied Attribute Query Handle was unrecognized or expired.",
333                                                         e));
334
335                                 } else {
336                                         saml.fail(
337                                                 resp,
338                                                 new SAMLException(
339                                                         Arrays.asList(codes),
340                                                         "The supplied Attribute Query Handle was unrecognized or expired."));
341                                 }
342                                 return;
343                         } catch (Exception ee) {
344                                 log.fatal("Could not construct a SAML error response: " + ee);
345                                 throw new ServletException("Attribute Authority response failure.");
346                         }
347
348                 } catch (Exception e) {
349                         log.error("Error while processing request: " + e);
350                         try {
351                                 if (configuration
352                                         .getProperty("edu.internet2.middleware.shibboleth.aa.AAServlet.passThruErrors", "false")
353                                         .equals("true")) {
354                                         saml.fail(resp, new SAMLException(SAMLException.RESPONDER, "General error processing request.", e));
355                                 } else {
356                                         saml.fail(resp, new SAMLException(SAMLException.RESPONDER, "General error processing request."));
357                                 }
358                                 return;
359                         } catch (Exception ee) {
360                                 log.fatal("Could not construct a SAML error response: " + ee);
361                                 throw new ServletException("Attribute Authority response failure.");
362                         }
363
364                 }
365         }
366
367
368 }