cd70a0e376e8becaadb334be94baefc9f49d54fd
[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.URL;
57 import java.security.Principal;
58 import java.util.Arrays;
59 import java.util.List;
60 import java.util.Properties;
61
62 import javax.servlet.ServletException;
63 import javax.servlet.UnavailableException;
64 import javax.servlet.http.HttpServlet;
65 import javax.servlet.http.HttpServletRequest;
66 import javax.servlet.http.HttpServletResponse;
67
68 import org.apache.log4j.Logger;
69 import org.apache.log4j.MDC;
70 import org.opensaml.QName;
71 import org.opensaml.SAMLException;
72 import org.opensaml.SAMLIdentifier;
73
74 import edu.internet2.middleware.shibboleth.aa.arp.ArpEngine;
75 import edu.internet2.middleware.shibboleth.aa.arp.ArpException;
76 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver;
77 import edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolverException;
78 import edu.internet2.middleware.shibboleth.common.AuthNPrincipal;
79 import edu.internet2.middleware.shibboleth.common.ShibResource;
80 import edu.internet2.middleware.shibboleth.hs.HandleRepository;
81 import edu.internet2.middleware.shibboleth.hs.HandleRepositoryException;
82 import edu.internet2.middleware.shibboleth.hs.HandleRepositoryFactory;
83 import edu.internet2.middleware.shibboleth.hs.InvalidHandleException;
84
85 /**
86  *  Attribute Authority & Release Policy
87  *  Handles Initialization and incoming requests to AA
88  *
89  * @author Parviz Dousti (dousti@cmu.edu)
90  * @author      Walter Hoehn (wassa@columbia.edu)
91  */
92
93 public class AAServlet extends HttpServlet {
94
95     protected AAResponder responder;
96     protected HandleRepository handleRepository;
97     protected Properties configuration;
98     private static Logger log = Logger.getLogger(AAServlet.class.getName());    
99     
100         public void init() throws ServletException {
101                 super.init();
102
103                 MDC.put("serviceId", "[AA] Core");
104                 log.info("Initializing Attribute Authority.");
105
106                 try {
107
108                         configuration = loadConfiguration();
109
110                         ArpEngine arpEngine = new ArpEngine(configuration);
111                         AttributeResolver resolver = new AttributeResolver(configuration);
112
113                         handleRepository = HandleRepositoryFactory.getInstance(configuration);
114
115                         responder = new AAResponder(arpEngine, resolver);
116
117                         log.info("Attribute Authority initialization complete.");
118
119                 } catch (ArpException ae) {
120                         log.fatal("The AA could not be initialized due to a problem with the ARP Engine configuration: " + ae);
121                         throw new UnavailableException("Attribute Authority failed to initialize.");
122                 } catch (AttributeResolverException ne) {
123                         log.fatal("The AA could not be initialized due to a problem with the Attribute Resolver configuration: " + ne);
124                         throw new UnavailableException("Attribute Authority failed to initialize.");
125                 } catch (AAException ae) {
126                         log.fatal("The AA could not be initialized: " + ae);
127                         throw new UnavailableException("Attribute Authority failed to initialize.");
128                 } catch (HandleRepositoryException he) {
129                         log.fatal(
130                                 "The AA could not be initialized due to a problem with the Handle Repository configuration: " + he);
131                         throw new UnavailableException("Attribute Authority failed to initialize.");
132                 }
133         }
134         protected Properties loadConfiguration() throws AAException {
135
136                 //Set defaults
137                 Properties defaultProps = new Properties();
138                 defaultProps.setProperty(
139                         "edu.internet2.middleware.shibboleth.aa.arp.provider.FileSystemArpRepository.Path",
140                         "/conf/arps/");
141                 defaultProps.setProperty(
142                                         "edu.internet2.middleware.shibboleth.aa.attrresolv.AttributeResolver.ResolverConfig",
143                                         "/conf/resolver.xml");
144                 defaultProps.setProperty(
145                         "edu.internet2.middleware.shibboleth.aa.arp.ArpRepository.implementation",
146                         "edu.internet2.middleware.shibboleth.aa.arp.provider.FileSystemArpRepository");
147                 defaultProps.setProperty(
148                         "edu.internet2.middleware.shibboleth.hs.provider.CryptoHandleRepository.keyStorePath",
149                         "/conf/handle.jks");
150                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.audiences", "urn:mace:InCommon:pilot:2003");
151                 defaultProps.setProperty("edu.internet2.middleware.shibboleth.aa.AAServlet.passThruErrors", "false");
152
153                 //Load from file
154                 Properties properties = new Properties(defaultProps);
155                 String propertiesFileLocation = getInitParameter("OriginPropertiesFile");
156                 if (propertiesFileLocation == null) {
157                         propertiesFileLocation = "/conf/origin.properties";
158                 }
159                 try {
160                         log.debug("Loading Configuration from (" + propertiesFileLocation + ").");
161                         properties.load(new ShibResource(propertiesFileLocation, this.getClass()).getInputStream());
162
163                         //Make sure we have all required parameters
164                         StringBuffer missingProperties = new StringBuffer();
165                         String[] requiredProperties =
166                                 {
167                                         "edu.internet2.middleware.shibboleth.aa.AAServlet.authorityName",
168                                         "edu.internet2.middleware.shibboleth.aa.arp.ArpRepository.implementation",
169                                         "edu.internet2.middleware.shibboleth.audiences" };
170
171                         for (int i = 0; i < requiredProperties.length; i++) {
172                                 if (properties.getProperty(requiredProperties[i]) == null) {
173                                         missingProperties.append("\"");
174                                         missingProperties.append(requiredProperties[i]);
175                                         missingProperties.append("\" ");
176                                 }
177                         }
178                         if (missingProperties.length() > 0) {
179                                 log.error(
180                                         "Missing configuration data.  The following configuration properites have not been set: "
181                                                 + missingProperties.toString());
182                                 throw new AAException("Missing configuration data.");
183                         }
184
185                 } catch (IOException e) {
186                         log.error("Could not load AA servlet configuration: " + e);
187                         throw new AAException("Could not load AA servlet configuration.");
188                 }
189
190                 if (log.isDebugEnabled()) {
191                         ByteArrayOutputStream debugStream = new ByteArrayOutputStream();
192                         PrintStream debugPrinter = new PrintStream(debugStream);
193                         properties.list(debugPrinter);
194                         log.debug(
195                                 "Runtime configuration parameters: " + System.getProperty("line.separator") + debugStream.toString());
196                         try {
197                                 debugStream.close();
198                         } catch (IOException e) {
199                                 log.error("Encountered a problem cleaning up resources: could not close debug stream.");
200                         }
201                 }
202
203                 return properties;
204         }
205
206         public void doPost(HttpServletRequest req, HttpServletResponse resp)
207                 throws ServletException, IOException {
208
209                 MDC.put("serviceId", "[AA] " + new SAMLIdentifier().toString());
210                 MDC.put("remoteAddr", req.getRemoteAddr());
211                 log.info("Handling request.");
212
213                 AASaml saml = null;
214
215                 try {
216                         saml =
217                                 new AASaml(
218                                         configuration.getProperty(
219                                                 "edu.internet2.middleware.shibboleth.aa.AAServlet.authorityName"),
220                                         configuration.getProperty("edu.internet2.middleware.shibboleth.audiences").replaceAll(
221                                                 "\\s",
222                                                 "").split(
223                                                 ","));
224                         saml.receive(req);
225
226                         log.info("Attribute Query Handle for this request: (" + saml.getHandle() + ").");
227                         Principal principal = null;
228                         if (saml.getHandle().equalsIgnoreCase("foo")) {
229                                 // for testing
230                                 principal = new AuthNPrincipal("test-handle");
231                         } else {
232                                 principal = handleRepository.getPrincipal(saml.getHandle());
233                         }
234
235                         URL resource = null;
236                         try {
237                                 resource = new URL(saml.getResource());
238                         } catch (MalformedURLException mue) {
239                                 log.error(
240                                         "Request contained an improperly formatted resource identifier.  Attempting to "
241                                                 + "handle request without one.");
242                         }
243
244                         if (saml.getShar() == null || saml.getShar().equals("")) {
245                                 log.info("Request is from an unauthenticated SHAR.");
246                         } else {
247                                 log.info("Request is from SHAR: (" + saml.getShar() + ").");
248                         }
249
250                         List attrs =
251                                 Arrays.asList(
252                                         responder.getReleaseAttributes(
253                                                 principal,
254                                                 saml.getShar(),
255                                                 resource));
256                         log.info("Found " + attrs.size() + " attribute(s) for " + principal.getName());
257                         saml.respond(resp, attrs, null);
258                         log.info("Successfully responded about " + principal.getName());
259
260                 } catch (InvalidHandleException e) {
261                         log.info("Could not associate the Attribute Query Handle with a principal: " + e);
262                         try {
263                                 QName[] codes =
264                                         {
265                                                 SAMLException.REQUESTER,
266                                                 new QName(edu.internet2.middleware.shibboleth.common.XML.SHIB_NS, "InvalidHandle")};
267                                 if (configuration
268                                         .getProperty("edu.internet2.middleware.shibboleth.aa.AAServlet.passThruErrors", "false")
269                                         .equals("true")) {
270                                         saml.fail(
271                                                 resp,
272                                                 new SAMLException(
273                                                         Arrays.asList(codes),
274                                                         "The supplied Attribute Query Handle was unrecognized or expired.",
275                                                         e));
276
277                                 } else {
278                                         saml.fail(
279                                                 resp,
280                                                 new SAMLException(
281                                                         Arrays.asList(codes),
282                                                         "The supplied Attribute Query Handle was unrecognized or expired."));
283                                 }
284                                 return;
285                         } catch (Exception ee) {
286                                 log.fatal("Could not construct a SAML error response: " + ee);
287                                 throw new ServletException("Attribute Authority response failure.");
288                         }
289
290                 } catch (Exception e) {
291                         log.error("Error while processing request: " + e);
292                         try {
293                                 if (configuration
294                                         .getProperty("edu.internet2.middleware.shibboleth.aa.AAServlet.passThruErrors", "false")
295                                         .equals("true")) {
296                                         saml.fail(
297                                                 resp,
298                                                 new SAMLException(SAMLException.RESPONDER, "General error processing request.", e));
299                                 } else {
300                                         saml.fail(
301                                                 resp,
302                                                 new SAMLException(SAMLException.RESPONDER, "General error processing request."));
303                                 }
304                                 return;
305                         } catch (Exception ee) {
306                                 log.fatal("Could not construct a SAML error response: " + ee);
307                                 throw new ServletException("Attribute Authority response failure.");
308                         }
309
310                 }
311         }
312
313
314 }