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