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