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