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