Don't create empty attribute statements when no attributes are released. Fixed bug...
[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             if(!requestContext.getPrincipalAttributes().isEmpty()){
96                 statements.add(buildAttributeStatement(requestContext));
97             }
98
99             // create the SAML response
100             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches", statements);
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
109         encodeResponse(requestContext);
110         writeAuditLogEntry(requestContext);
111     }
112
113     /**
114      * Decodes an incoming request and populates a created request context with the resultant information.
115      * 
116      * @param inTransport inbound message transport
117      * @param outTransport outbound message transport
118      * 
119      * @return the created request context
120      * 
121      * @throws ProfileException throw if there is a problem decoding the request
122      */
123     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
124             throws ProfileException {
125         log.debug("Decoding incomming request");
126
127         MetadataProvider metadataProvider = getMetadataProvider();
128
129         AttributeQueryContext requestContext = new AttributeQueryContext();
130         requestContext.setMetadataProvider(metadataProvider);
131         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
132
133         requestContext.setCommunicationProfileId(AttributeQueryConfiguration.PROFILE_ID);
134         requestContext.setInboundMessageTransport(inTransport);
135         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
136         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
137
138         requestContext.setOutboundMessageTransport(outTransport);
139         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
140
141         try {
142             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
143             requestContext.setMessageDecoder(decoder);
144             decoder.decode(requestContext);
145             log.debug("Decoded request");
146             return requestContext;
147         } catch (MessageDecodingException e) {
148             log.error("Error decoding attribute query message", e);
149             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
150             throw new ProfileException("Error decoding attribute query message");
151         } catch (SecurityException e) {
152             log.error("Message did not meet security requirements", e);
153             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
154                     "Message did not meet security requirements"));
155             throw new ProfileException("Message did not meet security requirements", e);
156         } finally {
157             // Set as much information as can be retrieved from the decoded message
158             AttributeQuery query = requestContext.getInboundSAMLMessage();
159             requestContext.setSubjectNameIdentifier(query.getSubject().getNameID());
160
161             String relyingPartyId = requestContext.getInboundMessageIssuer();
162             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
163             if (rpConfig == null) {
164                 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
165                 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
166                         + relyingPartyId);
167             }
168             requestContext.setRelyingPartyConfiguration(rpConfig);
169
170             AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
171                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
172             if (profileConfig != null) {
173                 requestContext.setProfileConfiguration(profileConfig);
174                 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
175                 if (profileConfig.getSigningCredential() != null) {
176                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
177                 } else if (rpConfig.getDefaultSigningCredential() != null) {
178                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
179                 }
180             }
181
182             requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
183
184             String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
185             requestContext.setLocalEntityId(assertingPartyId);
186             try {
187                 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
188                 if (localEntityDescriptor != null) {
189                     requestContext.setLocalEntityMetadata(localEntityDescriptor);
190                     requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
191                     requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
192                             .getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS));
193                 }
194             } catch (MetadataProviderException e) {
195                 log.error("Unable to locate metadata for asserting party");
196                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
197                         "Error locating asserting party metadata"));
198                 throw new ProfileException("Error locating asserting party metadata");
199             }
200         }
201     }
202
203     /**
204      * Selects the appropriate endpoint for the relying party and stores it in the request context.
205      * 
206      * @param requestContext current request context
207      * 
208      * @return Endpoint selected from the information provided in the request context
209      */
210     protected Endpoint selectEndpoint(AttributeQueryContext requestContext) {
211         Endpoint endpoint;
212
213         if (getInboundBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {
214             endpoint = acsEndpointBuilder.buildObject();
215             endpoint.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI);
216         } else {
217             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
218             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
219             endpointSelector.setMetadataProvider(getMetadataProvider());
220             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
221             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
222             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
223             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
224             endpoint = endpointSelector.selectEndpoint();
225         }
226
227         return endpoint;
228     }
229
230     /** Basic data structure used to accumulate information as a request is being processed. */
231     protected class AttributeQueryContext extends
232             BaseSAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
233
234     }
235 }