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