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