Address SIDP-95 (what kind of freak sends an Authn Request to the attribute query...
[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.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.saml1.AttributeQueryConfiguration;
48
49 /**
50  * SAML 1 Attribute Query profile handler.
51  */
52 public class AttributeQueryProfileHandler extends AbstractSAML1ProfileHandler {
53
54     /** Class logger. */
55     private final Logger log = LoggerFactory.getLogger(AttributeQueryProfileHandler.class);
56
57     /** Builder of assertion consumer service endpoints. */
58     private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
59
60     /** Constructor. */
61     public AttributeQueryProfileHandler() {
62         super();
63
64         acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
65                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
66     }
67
68     /** {@inheritDoc} */
69     public String getProfileId() {
70         return "urn:mace:shibboleth:2.0:idp:profiles:saml1:query:attribute";
71     }
72
73     /** {@inheritDoc} */
74     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
75         AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
76
77         Response samlResponse;
78         try {
79             if (requestContext.getProfileConfiguration() == null) {
80                 log.error("SAML 1 Attribute Query profile is not configured for relying party "
81                         + requestContext.getInboundMessageIssuer());
82                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
83                         "SAML 1 Attribute Query profile is not configured for relying party "
84                                 + requestContext.getInboundMessageIssuer()));
85                 samlResponse = buildErrorResponse(requestContext);
86             } else {
87                 resolvePrincipal(requestContext);
88                 resolveAttributes(requestContext);
89                 requestContext.setReleasedAttributes(requestContext.getPrincipalAttributes().keySet());
90
91                 ArrayList<Statement> statements = new ArrayList<Statement>();
92                 AttributeStatement attributeStatement = buildAttributeStatement(requestContext,
93                         "urn:oasis:names:tc:SAML:1.0:cm:sender-vouches");
94                 if (attributeStatement != null) {
95                     statements.add(attributeStatement);
96                 }
97
98                 samlResponse = buildResponse(requestContext, statements);
99             }
100         } catch (ProfileException e) {
101             samlResponse = buildErrorResponse(requestContext);
102         }
103
104         requestContext.setOutboundSAMLMessage(samlResponse);
105         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
106         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
107         encodeResponse(requestContext);
108         writeAuditLogEntry(requestContext);
109     }
110
111     /**
112      * Decodes an incoming request and populates a created request context with the resultant information.
113      * 
114      * @param inTransport inbound message transport
115      * @param outTransport outbound message transport
116      * 
117      * @return the created request context
118      * 
119      * @throws ProfileException throw if there is a problem decoding the request
120      */
121     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
122             throws ProfileException {
123         log.debug("Decoding message with decoder binding {}", getInboundBinding());
124
125         MetadataProvider metadataProvider = getMetadataProvider();
126
127         AttributeQueryContext requestContext = new AttributeQueryContext();
128         requestContext.setMetadataProvider(metadataProvider);
129         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
130
131         requestContext.setCommunicationProfileId(AttributeQueryConfiguration.PROFILE_ID);
132         requestContext.setInboundMessageTransport(inTransport);
133         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
134         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
135
136         requestContext.setOutboundMessageTransport(outTransport);
137         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
138
139         try {
140             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
141             if (decoder == null) {
142                 throw new ProfileException("No message decoder configured for inbound binding " + getInboundBinding());
143             }
144             requestContext.setMessageDecoder(decoder);
145             decoder.decode(requestContext);
146             log.debug("Decoded request");
147             
148             if (!(requestContext.getInboundMessage() instanceof Request)) {
149                 log.error("Incomming message was not a Request, it was a {}", requestContext.getInboundMessage()
150                         .getClass().getName());
151                 requestContext
152                         .setFailureStatus(buildStatus(StatusCode.REQUESTER, null, "Invalid SAML Request message."));
153                 throw new ProfileException("Invalid SAML Request message.");
154             }
155             
156             return requestContext;
157         } catch (MessageDecodingException e) {
158             log.error("Error decoding attribute query message", e);
159             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
160             throw new ProfileException("Error decoding attribute query message");
161         } catch (SecurityException e) {
162             log.error("Message did not meet security requirements", e);
163             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
164                     "Message did not meet security requirements"));
165             throw new ProfileException("Message did not meet security policy requirements", e);
166         } finally {
167             // Set as much information as can be retrieved from the decoded message
168             Request request = requestContext.getInboundSAMLMessage();
169             if (request == null) {
170                 log.error("Decoder did not contain an attribute query, an error occured decoding the message");
171                 throw new ProfileException("Unable to decode message.");
172             }
173             AttributeQuery query = request.getAttributeQuery();
174             if (query != null) {
175                 requestContext.setSubjectNameIdentifier(query.getSubject().getNameIdentifier());
176             }
177
178             String relyingPartyId = requestContext.getInboundMessageIssuer();
179             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
180             if (rpConfig == null) {
181                 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
182                 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
183                         + relyingPartyId);
184             }
185             requestContext.setRelyingPartyConfiguration(rpConfig);
186
187             AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
188                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
189             if (profileConfig != null) {
190                 requestContext.setProfileConfiguration(profileConfig);
191                 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
192                 if (profileConfig.getSigningCredential() != null) {
193                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
194                 } else if (rpConfig.getDefaultSigningCredential() != null) {
195                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
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.SAML11P_NS));
209                 }
210             } catch (MetadataProviderException e) {
211                 log.error("Unable to locate metadata for asserting party");
212                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, 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.SAML1_SOAP11_BINDING_URI)) {
230             endpoint = acsEndpointBuilder.buildObject();
231             endpoint.setBinding(SAMLConstants.SAML1_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             BaseSAML1ProfileRequestContext<Request, Response, AttributeQueryConfiguration> {}
249 }