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 / saml2 / 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.saml2;
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.saml2.core.AttributeQuery;
26 import org.opensaml.saml2.core.Response;
27 import org.opensaml.saml2.core.Statement;
28 import org.opensaml.saml2.core.StatusCode;
29 import org.opensaml.saml2.metadata.AssertionConsumerService;
30 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
31 import org.opensaml.saml2.metadata.Endpoint;
32 import org.opensaml.saml2.metadata.EntityDescriptor;
33 import org.opensaml.saml2.metadata.SPSSODescriptor;
34 import org.opensaml.saml2.metadata.provider.MetadataProvider;
35 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
36 import org.opensaml.ws.message.decoder.MessageDecodingException;
37 import org.opensaml.ws.transport.http.HTTPInTransport;
38 import org.opensaml.ws.transport.http.HTTPOutTransport;
39 import org.opensaml.xml.security.SecurityException;
40 import org.slf4j.Logger;
41 import org.slf4j.LoggerFactory;
42
43 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
44 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
45 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AttributeQueryConfiguration;
46
47 /** SAML 2.0 Attribute Query profile handler. */
48 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
49
50     /** Class logger. */
51     private static Logger log = LoggerFactory.getLogger(AttributeQueryProfileHandler.class);
52
53     /** Builder of assertion consumer service endpoints. */
54     private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
55
56     /** Constructor. */
57     public AttributeQueryProfileHandler() {
58         super();
59
60         acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
61                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
62     }
63
64     /** {@inheritDoc} */
65     public String getProfileId() {
66         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:query:attribute";
67     }
68
69     /** {@inheritDoc} */
70     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
71         Response samlResponse;
72
73         AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
74
75         try {
76             if (requestContext.getProfileConfiguration() == null) {
77                 log.error("SAML 2 Attribute Query profile is not configured for relying party "
78                         + requestContext.getInboundMessageIssuer());
79                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
80                         "SAML 2 Attribute Query profile is not configured for relying party "
81                                 + requestContext.getInboundMessageIssuer()));
82                 throw new ProfileException("SAML 2 Attribute Query profile is not configured for relying party "
83                         + requestContext.getInboundMessageIssuer());
84             }
85
86             checkSamlVersion(requestContext);
87
88             // Resolve attribute query name id to principal name and place in context
89             resolvePrincipal(requestContext);
90             resolveAttributes(requestContext);
91             requestContext.setReleasedAttributes(requestContext.getPrincipalAttributes().keySet());
92
93             // Lookup principal name and attributes, create attribute statement from information
94             ArrayList<Statement> statements = new ArrayList<Statement>();
95             statements.add(buildAttributeStatement(requestContext));
96
97             // create the SAML response
98             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches", statements);
99         } catch (ProfileException e) {
100             samlResponse = buildErrorResponse(requestContext);
101         }
102
103         requestContext.setOutboundSAMLMessage(samlResponse);
104         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
105         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
106
107         encodeResponse(requestContext);
108         writeAuditLogEntry(requestContext);
109     }
110
111     /**
112      * Decodes an incoming request and populates a created request context with the resultant information.
113      * 
114      * @param inTransport inbound message transport
115      * @param outTransport outbound message transport
116      * 
117      * @return the created request context
118      * 
119      * @throws ProfileException throw if there is a problem decoding the request
120      */
121     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
122             throws ProfileException {
123         log.debug("Decoding incomming request");
124
125         MetadataProvider metadataProvider = getMetadataProvider();
126
127         AttributeQueryContext requestContext = new AttributeQueryContext();
128         requestContext.setMetadataProvider(metadataProvider);
129         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
130
131         requestContext.setCommunicationProfileId(AttributeQueryConfiguration.PROFILE_ID);
132         requestContext.setInboundMessageTransport(inTransport);
133         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
134         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
135
136         requestContext.setOutboundMessageTransport(outTransport);
137         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
138
139         try {
140             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
141             requestContext.setMessageDecoder(decoder);
142             decoder.decode(requestContext);
143             log.debug("Decoded request");
144             return requestContext;
145         } catch (MessageDecodingException e) {
146             log.error("Error decoding attribute query message", e);
147             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
148             throw new ProfileException("Error decoding attribute query message");
149         } catch (SecurityException e) {
150             log.error("Message did not meet security requirements", e);
151             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
152                     "Message did not meet security requirements"));
153             throw new ProfileException("Message did not meet security requirements", e);
154         } finally {
155             // Set as much information as can be retrieved from the decoded message
156             AttributeQuery query = requestContext.getInboundSAMLMessage();
157             requestContext.setSubjectNameIdentifier(query.getSubject().getNameID());
158
159             String relyingPartyId = requestContext.getInboundMessageIssuer();
160             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
161             if (rpConfig == null) {
162                 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
163                 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
164                         + relyingPartyId);
165             }
166             requestContext.setRelyingPartyConfiguration(rpConfig);
167
168             AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
169                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
170             if (profileConfig != null) {
171                 requestContext.setProfileConfiguration(profileConfig);
172                 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
173                 if (profileConfig.getSigningCredential() != null) {
174                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
175                 } else if (rpConfig.getDefaultSigningCredential() != null) {
176                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
177                 }
178             }
179
180             requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
181
182             String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
183             requestContext.setLocalEntityId(assertingPartyId);
184             try {
185                 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
186                 if (localEntityDescriptor != null) {
187                     requestContext.setLocalEntityMetadata(localEntityDescriptor);
188                     requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
189                     requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
190                             .getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS));
191                 }
192             } catch (MetadataProviderException e) {
193                 log.error("Unable to locate metadata for asserting party");
194                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
195                         "Error locating asserting party metadata"));
196                 throw new ProfileException("Error locating asserting party metadata");
197             }
198         }
199     }
200
201     /**
202      * Selects the appropriate endpoint for the relying party and stores it in the request context.
203      * 
204      * @param requestContext current request context
205      * 
206      * @return Endpoint selected from the information provided in the request context
207      */
208     protected Endpoint selectEndpoint(AttributeQueryContext requestContext) {
209         Endpoint endpoint;
210
211         if (getInboundBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {
212             endpoint = acsEndpointBuilder.buildObject();
213             endpoint.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI);
214         } else {
215             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
216             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
217             endpointSelector.setMetadataProvider(getMetadataProvider());
218             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
219             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
220             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
221             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
222             endpoint = endpointSelector.selectEndpoint();
223         }
224
225         return endpoint;
226     }
227
228     /** Basic data structure used to accumulate information as a request is being processed. */
229     protected class AttributeQueryContext extends
230             BaseSAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
231
232     }
233 }