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