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