Don't create empty attribute statements when no attributes are released. Fixed bug...
[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                 if (!requestContext.getPrincipalAttributes().isEmpty()) {
92                     statements.add(buildAttributeStatement(requestContext,
93                             "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
94                 }
95
96                 samlResponse = buildResponse(requestContext, statements);
97             }
98         } catch (ProfileException e) {
99             samlResponse = buildErrorResponse(requestContext);
100         }
101
102         requestContext.setOutboundSAMLMessage(samlResponse);
103         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
104         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
105         encodeResponse(requestContext);
106         writeAuditLogEntry(requestContext);
107     }
108
109     /**
110      * Decodes an incoming request and populates a created request context with the resultant information.
111      * 
112      * @param inTransport inbound message transport
113      * @param outTransport outbound message transport
114      * 
115      * @return the created request context
116      * 
117      * @throws ProfileException throw if there is a problem decoding the request
118      */
119     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
120             throws ProfileException {
121         log.debug("Decoding incomming request");
122
123         MetadataProvider metadataProvider = getMetadataProvider();
124
125         AttributeQueryContext requestContext = new AttributeQueryContext();
126         requestContext.setMetadataProvider(metadataProvider);
127         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
128
129         requestContext.setCommunicationProfileId(AttributeQueryConfiguration.PROFILE_ID);
130         requestContext.setInboundMessageTransport(inTransport);
131         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
132         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
133
134         requestContext.setOutboundMessageTransport(outTransport);
135         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
136
137         try {
138             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
139             if (decoder == null) {
140                 throw new ProfileException("No message decoder configured for inbound binding " + getInboundBinding());
141             }
142             requestContext.setMessageDecoder(decoder);
143             decoder.decode(requestContext);
144             log.debug("Decoded request");
145             return requestContext;
146         } catch (MessageDecodingException e) {
147             log.error("Error decoding attribute query message", e);
148             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
149             throw new ProfileException("Error decoding attribute query message");
150         } catch (SecurityException e) {
151             log.error("Message did not meet security requirements", e);
152             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
153                     "Message did not meet security requirements"));
154             throw new ProfileException("Message did not meet security policy requirements", e);
155         } finally {
156             // Set as much information as can be retrieved from the decoded message
157
158             Request request = requestContext.getInboundSAMLMessage();
159             if (request == null) {
160                 log.error("Decoder did not contain an attribute query, an error occured decoding the message");
161                 throw new ProfileException("Unable to decode message.");
162             }
163             AttributeQuery query = request.getAttributeQuery();
164             requestContext.setSubjectNameIdentifier(query.getSubject().getNameIdentifier());
165
166             String relyingPartyId = requestContext.getInboundMessageIssuer();
167             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
168             if (rpConfig == null) {
169                 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
170                 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
171                         + relyingPartyId);
172             }
173             requestContext.setRelyingPartyConfiguration(rpConfig);
174
175             AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
176                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
177             if (profileConfig != null) {
178                 requestContext.setProfileConfiguration(profileConfig);
179                 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
180                 if (profileConfig.getSigningCredential() != null) {
181                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
182                 } else if (rpConfig.getDefaultSigningCredential() != null) {
183                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
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.SAML11P_NS));
197                 }
198             } catch (MetadataProviderException e) {
199                 log.error("Unable to locate metadata for asserting party");
200                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, 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.SAML1_SOAP11_BINDING_URI)) {
218             endpoint = acsEndpointBuilder.buildObject();
219             endpoint.setBinding(SAMLConstants.SAML1_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             BaseSAML1ProfileRequestContext<Request, Response, AttributeQueryConfiguration> {}
237 }