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