Actually provide the SecurityPolicyResolver to the decoder
[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.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.saml1.AttributeQueryConfiguration;
46
47 /**
48  * SAML 1 Attribute Query profile handler.
49  */
50 public class AttributeQueryProfileHandler extends AbstractSAML1ProfileHandler {
51
52     /** Class logger. */
53     private final 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:saml1:query:attribute";
69     }
70
71     /** {@inheritDoc} */
72     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
73         AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
74
75         Response samlResponse;
76         try {
77             if (requestContext.getProfileConfiguration() == null) {
78                 log.error("SAML 1 Attribute Query profile is not configured for relying party "
79                         + requestContext.getInboundMessageIssuer());
80                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
81                         "SAML 1 Attribute Query profile is not configured for relying party "
82                                 + requestContext.getInboundMessageIssuer()));
83                 samlResponse = buildErrorResponse(requestContext);
84             }else{
85                 resolvePrincipal(requestContext);
86                 resolveAttributes(requestContext);
87                 requestContext.setReleasedAttributes(requestContext.getPrincipalAttributes().keySet());
88     
89                 ArrayList<Statement> statements = new ArrayList<Statement>();
90                 statements.add(buildAttributeStatement(requestContext, 
91                         "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches"));
92     
93                 samlResponse = buildResponse(requestContext, statements);
94             }
95         } catch (ProfileException e) {
96             samlResponse = buildErrorResponse(requestContext);
97         }
98
99         requestContext.setOutboundSAMLMessage(samlResponse);
100         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
101         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
102         encodeResponse(requestContext);
103         writeAuditLogEntry(requestContext);
104     }
105
106     /**
107      * Decodes an incoming request and populates a created request context with the resultant information.
108      * 
109      * @param inTransport inbound message transport
110      * @param outTransport outbound message transport
111      * 
112      * @return the created request context
113      * 
114      * @throws ProfileException throw if there is a problem decoding the request
115      */
116     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
117             throws ProfileException {
118         log.debug("Decoding incomming request");
119
120         MetadataProvider metadataProvider = getMetadataProvider();
121
122         AttributeQueryContext requestContext = new AttributeQueryContext();
123         requestContext.setMetadataProvider(metadataProvider);
124         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
125
126         requestContext.setCommunicationProfileId(AttributeQueryConfiguration.PROFILE_ID);
127         requestContext.setInboundMessageTransport(inTransport);
128         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
129         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
130
131         requestContext.setOutboundMessageTransport(outTransport);
132         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
133
134         try {
135             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
136             if (decoder == null) {
137                 throw new ProfileException("No message decoder configured for inbound binding " + getInboundBinding());
138             }
139             requestContext.setMessageDecoder(decoder);
140             decoder.decode(requestContext);
141             log.debug("Decoded request");
142             return requestContext;
143         } catch (MessageDecodingException e) {
144             log.error("Error decoding attribute query message", e);
145             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
146             throw new ProfileException("Error decoding attribute query message");
147         } catch (SecurityException e) {
148             log.error("Message did not meet security requirements", e);
149             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
150                     "Message did not meet security requirements"));
151             throw new ProfileException("Message did not meet security policy requirements", e);
152         } finally {
153             // Set as much information as can be retrieved from the decoded message
154             try {
155                 Request request = requestContext.getInboundSAMLMessage();
156                 AttributeQuery query = request.getAttributeQuery();
157                 requestContext.setSubjectNameIdentifier(query.getSubject().getNameIdentifier());
158
159                 String relyingPartyId = requestContext.getInboundMessageIssuer();
160                 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
161                 requestContext.setRelyingPartyConfiguration(rpConfig);
162                 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
163
164                 String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
165                 requestContext.setLocalEntityId(assertingPartyId);
166                 requestContext.setLocalEntityMetadata(metadataProvider.getEntityDescriptor(assertingPartyId));
167                 requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
168                 requestContext.setLocalEntityRoleMetadata(requestContext.getLocalEntityMetadata()
169                         .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
170
171                 AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
172                         .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
173                 if (profileConfig != null) {
174                     requestContext.setProfileConfiguration(profileConfig);
175                     requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
176                     if (profileConfig.getSigningCredential() != null) {
177                         requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
178                     } else if (rpConfig.getDefaultSigningCredential() != null) {
179                         requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
180                     }
181                 }
182
183             } catch (MetadataProviderException e) {
184                 log.error("Unable to locate metadata for asserting or relying party");
185                 requestContext
186                         .setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
187                 throw new ProfileException("Error locating party metadata");
188             }
189         }
190     }
191
192     /**
193      * Selects the appropriate endpoint for the relying party and stores it in the request context.
194      * 
195      * @param requestContext current request context
196      * 
197      * @return Endpoint selected from the information provided in the request context
198      */
199     protected Endpoint selectEndpoint(AttributeQueryContext requestContext) {
200         Endpoint endpoint;
201
202         if (getInboundBinding().equals(SAMLConstants.SAML1_SOAP11_BINDING_URI)) {
203             endpoint = acsEndpointBuilder.buildObject();
204             endpoint.setBinding(SAMLConstants.SAML1_SOAP11_BINDING_URI);
205         } else {
206             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
207             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
208             endpointSelector.setMetadataProvider(getMetadataProvider());
209             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
210             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
211             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
212             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
213             endpoint = endpointSelector.selectEndpoint();
214         }
215
216         return endpoint;
217     }
218
219     /** Basic data structure used to accumulate information as a request is being processed. */
220     protected class AttributeQueryContext extends
221             BaseSAML1ProfileRequestContext<Request, Response, AttributeQueryConfiguration> {}
222 }