Attempt to fix some NPEs when information is not available from the decoder or metada...
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / AttributeQueryProfileHandler.java
1 /*
2  * Copyright [2006] [University Corporation for Advanced Internet Development, Inc.]
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16
17 package edu.internet2.middleware.shibboleth.idp.profile.saml1;
18
19 import java.util.ArrayList;
20
21 import org.opensaml.common.SAMLObjectBuilder;
22 import org.opensaml.common.binding.BasicEndpointSelector;
23 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
24 import org.opensaml.common.xml.SAMLConstants;
25 import org.opensaml.saml1.core.AttributeQuery;
26 import org.opensaml.saml1.core.Request;
27 import org.opensaml.saml1.core.Response;
28 import org.opensaml.saml1.core.Statement;
29 import org.opensaml.saml1.core.StatusCode;
30 import org.opensaml.saml2.metadata.AssertionConsumerService;
31 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
32 import org.opensaml.saml2.metadata.Endpoint;
33 import org.opensaml.saml2.metadata.EntityDescriptor;
34 import org.opensaml.saml2.metadata.SPSSODescriptor;
35 import org.opensaml.saml2.metadata.provider.MetadataProvider;
36 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
37 import org.opensaml.ws.message.decoder.MessageDecodingException;
38 import org.opensaml.ws.transport.http.HTTPInTransport;
39 import org.opensaml.ws.transport.http.HTTPOutTransport;
40 import org.opensaml.xml.security.SecurityException;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
45 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
46 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.AttributeQueryConfiguration;
47
48 /**
49  * SAML 1 Attribute Query profile handler.
50  */
51 public class AttributeQueryProfileHandler extends AbstractSAML1ProfileHandler {
52
53     /** Class logger. */
54     private final Logger log = LoggerFactory.getLogger(AttributeQueryProfileHandler.class);
55
56     /** Builder of assertion consumer service endpoints. */
57     private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
58
59     /** Constructor. */
60     public AttributeQueryProfileHandler() {
61         super();
62
63         acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
64                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
65     }
66
67     /** {@inheritDoc} */
68     public String getProfileId() {
69         return "urn:mace:shibboleth:2.0:idp:profiles:saml1:query:attribute";
70     }
71
72     /** {@inheritDoc} */
73     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
74         AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
75
76         Response samlResponse;
77         try {
78             if (requestContext.getProfileConfiguration() == null) {
79                 log.error("SAML 1 Attribute Query profile is not configured for relying party "
80                         + requestContext.getInboundMessageIssuer());
81                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
82                         "SAML 1 Attribute Query profile is not configured for relying party "
83                                 + requestContext.getInboundMessageIssuer()));
84                 samlResponse = buildErrorResponse(requestContext);
85             } else {
86                 resolvePrincipal(requestContext);
87                 resolveAttributes(requestContext);
88                 requestContext.setReleasedAttributes(requestContext.getPrincipalAttributes().keySet());
89
90                 ArrayList<Statement> statements = new ArrayList<Statement>();
91                 statements
92                         .add(buildAttributeStatement(requestContext, "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
93
94                 samlResponse = buildResponse(requestContext, statements);
95             }
96         } catch (ProfileException e) {
97             samlResponse = buildErrorResponse(requestContext);
98         }
99
100         requestContext.setOutboundSAMLMessage(samlResponse);
101         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
102         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
103         encodeResponse(requestContext);
104         writeAuditLogEntry(requestContext);
105     }
106
107     /**
108      * Decodes an incoming request and populates a created request context with the resultant information.
109      * 
110      * @param inTransport inbound message transport
111      * @param outTransport outbound message transport
112      * 
113      * @return the created request context
114      * 
115      * @throws ProfileException throw if there is a problem decoding the request
116      */
117     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
118             throws ProfileException {
119         log.debug("Decoding incomming request");
120
121         MetadataProvider metadataProvider = getMetadataProvider();
122
123         AttributeQueryContext requestContext = new AttributeQueryContext();
124         requestContext.setMetadataProvider(metadataProvider);
125         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
126
127         requestContext.setCommunicationProfileId(AttributeQueryConfiguration.PROFILE_ID);
128         requestContext.setInboundMessageTransport(inTransport);
129         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
130         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
131
132         requestContext.setOutboundMessageTransport(outTransport);
133         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
134
135         try {
136             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
137             if (decoder == null) {
138                 throw new ProfileException("No message decoder configured for inbound binding " + getInboundBinding());
139             }
140             requestContext.setMessageDecoder(decoder);
141             decoder.decode(requestContext);
142             log.debug("Decoded request");
143             return requestContext;
144         } catch (MessageDecodingException e) {
145             log.error("Error decoding attribute query message", e);
146             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
147             throw new ProfileException("Error decoding attribute query message");
148         } catch (SecurityException e) {
149             log.error("Message did not meet security requirements", e);
150             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
151                     "Message did not meet security requirements"));
152             throw new ProfileException("Message did not meet security policy requirements", e);
153         } finally {
154             // Set as much information as can be retrieved from the decoded message
155
156             Request request = requestContext.getInboundSAMLMessage();
157             if (request == null) {
158                 log.error("Decoder did not contain an attribute query, an error occured decoding the message");
159                 throw new ProfileException("Unable to decode message.");
160             }
161             AttributeQuery query = request.getAttributeQuery();
162             requestContext.setSubjectNameIdentifier(query.getSubject().getNameIdentifier());
163
164             String relyingPartyId = requestContext.getInboundMessageIssuer();
165             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
166             if (rpConfig == null) {
167                 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
168                 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
169                         + relyingPartyId);
170             }
171             requestContext.setRelyingPartyConfiguration(rpConfig);
172
173             AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
174                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
175             if (profileConfig != null) {
176                 requestContext.setProfileConfiguration(profileConfig);
177                 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
178                 if (profileConfig.getSigningCredential() != null) {
179                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
180                 } else if (rpConfig.getDefaultSigningCredential() != null) {
181                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
182                 }
183             }
184             requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
185
186             String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
187             requestContext.setLocalEntityId(assertingPartyId);
188             try {
189                 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
190                 if (localEntityDescriptor != null) {
191                     requestContext.setLocalEntityMetadata(localEntityDescriptor);
192                     requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
193                     requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
194                             .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
195                 }
196             } catch (MetadataProviderException e) {
197                 log.error("Unable to locate metadata for asserting party");
198                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
199                         "Error locating asserting party metadata"));
200                 throw new ProfileException("Error locating asserting party metadata");
201             }
202         }
203     }
204
205     /**
206      * Selects the appropriate endpoint for the relying party and stores it in the request context.
207      * 
208      * @param requestContext current request context
209      * 
210      * @return Endpoint selected from the information provided in the request context
211      */
212     protected Endpoint selectEndpoint(AttributeQueryContext requestContext) {
213         Endpoint endpoint;
214
215         if (getInboundBinding().equals(SAMLConstants.SAML1_SOAP11_BINDING_URI)) {
216             endpoint = acsEndpointBuilder.buildObject();
217             endpoint.setBinding(SAMLConstants.SAML1_SOAP11_BINDING_URI);
218         } else {
219             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
220             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
221             endpointSelector.setMetadataProvider(getMetadataProvider());
222             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
223             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
224             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
225             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
226             endpoint = endpointSelector.selectEndpoint();
227         }
228
229         return endpoint;
230     }
231
232     /** Basic data structure used to accumulate information as a request is being processed. */
233     protected class AttributeQueryContext extends
234             BaseSAML1ProfileRequestContext<Request, Response, AttributeQueryConfiguration> {}
235 }