Fix log typos
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml2 / 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.saml2;
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.saml2.core.AttributeQuery;
26 import org.opensaml.saml2.core.AttributeStatement;
27 import org.opensaml.saml2.core.Response;
28 import org.opensaml.saml2.core.Statement;
29 import org.opensaml.saml2.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.EntityDescriptor;
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.transport.http.HTTPInTransport;
39 import org.opensaml.ws.transport.http.HTTPOutTransport;
40 import org.opensaml.xml.security.SecurityException;
41 import org.slf4j.Logger;
42 import org.slf4j.LoggerFactory;
43
44 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
45 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
46 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AttributeQueryConfiguration;
47
48 /** SAML 2.0 Attribute Query profile handler. */
49 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
50
51     /** Class logger. */
52     private static Logger log = LoggerFactory.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:saml2:query:attribute";
68     }
69
70     /** {@inheritDoc} */
71     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
72         Response samlResponse;
73
74         AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
75
76         try {
77             if (requestContext.getProfileConfiguration() == null) {
78                 log.error("SAML 2 Attribute Query profile is not configured for relying party "
79                         + requestContext.getInboundMessageIssuer());
80                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
81                         "SAML 2 Attribute Query profile is not configured for relying party "
82                                 + requestContext.getInboundMessageIssuer()));
83                 throw new ProfileException("SAML 2 Attribute Query profile is not configured for relying party "
84                         + requestContext.getInboundMessageIssuer());
85             }
86
87             checkSamlVersion(requestContext);
88
89             // Resolve attribute query name id to principal name and place in context
90             resolvePrincipal(requestContext);
91             resolveAttributes(requestContext);
92             requestContext.setReleasedAttributes(requestContext.getPrincipalAttributes().keySet());
93
94             // Lookup principal name and attributes, create attribute statement from information
95             ArrayList<Statement> statements = new ArrayList<Statement>();
96             AttributeStatement attributeStatement = buildAttributeStatement(requestContext);
97             if (attributeStatement != null) {
98                 statements.add(attributeStatement);
99             }
100
101             // create the SAML response
102             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches", statements);
103         } catch (ProfileException e) {
104             samlResponse = buildErrorResponse(requestContext);
105         }
106
107         requestContext.setOutboundSAMLMessage(samlResponse);
108         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
109         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
110
111         encodeResponse(requestContext);
112         writeAuditLogEntry(requestContext);
113     }
114
115     /**
116      * Decodes an incoming request and populates a created request context with the resultant information.
117      * 
118      * @param inTransport inbound message transport
119      * @param outTransport outbound message transport
120      * 
121      * @return the created request context
122      * 
123      * @throws ProfileException throw if there is a problem decoding the request
124      */
125     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
126             throws ProfileException {
127         log.debug("Decoding message with decoder binding {}", getInboundBinding());
128
129         MetadataProvider metadataProvider = getMetadataProvider();
130
131         AttributeQueryContext requestContext = new AttributeQueryContext();
132         requestContext.setMetadataProvider(metadataProvider);
133         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
134
135         requestContext.setCommunicationProfileId(AttributeQueryConfiguration.PROFILE_ID);
136         requestContext.setInboundMessageTransport(inTransport);
137         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
138         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
139
140         requestContext.setOutboundMessageTransport(outTransport);
141         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
142
143         try {
144             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
145             requestContext.setMessageDecoder(decoder);
146             decoder.decode(requestContext);
147             log.debug("Decoded request");
148
149             if (!(requestContext.getInboundSAMLMessage() instanceof AttributeQuery)) {
150                 log.error("Incoming message was not a AttributeQuery, it was a {}", requestContext
151                         .getInboundSAMLMessage().getClass().getName());
152                 requestContext.setFailureStatus(buildStatus(StatusCode.REQUESTER_URI, null,
153                         "Invalid SAML AttributeQuery message."));
154                 throw new ProfileException("Invalid SAML AttributeQuery message.");
155             }
156
157             return requestContext;
158         } catch (MessageDecodingException e) {
159             log.error("Error decoding attribute query message", e);
160             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
161             throw new ProfileException("Error decoding attribute query message");
162         } catch (SecurityException e) {
163             log.error("Message did not meet security requirements", e);
164             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
165                     "Message did not meet security requirements"));
166             throw new ProfileException("Message did not meet security requirements", e);
167         } finally {
168             // Set as much information as can be retrieved from the decoded message
169             AttributeQuery query = requestContext.getInboundSAMLMessage();
170             if (query != null) {
171                 requestContext.setSubjectNameIdentifier(query.getSubject().getNameID());
172             }
173
174             String relyingPartyId = requestContext.getInboundMessageIssuer();
175             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
176             if (rpConfig == null) {
177                 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
178                 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
179                         + relyingPartyId);
180             }
181             requestContext.setRelyingPartyConfiguration(rpConfig);
182
183             AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
184                     .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
185             if (profileConfig != null) {
186                 requestContext.setProfileConfiguration(profileConfig);
187                 requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
188                 if (profileConfig.getSigningCredential() != null) {
189                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
190                 } else if (rpConfig.getDefaultSigningCredential() != null) {
191                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
192                 }
193             }
194
195             requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
196
197             String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
198             requestContext.setLocalEntityId(assertingPartyId);
199             try {
200                 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
201                 if (localEntityDescriptor != null) {
202                     requestContext.setLocalEntityMetadata(localEntityDescriptor);
203                     requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
204                     requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
205                             .getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS));
206                 }
207             } catch (MetadataProviderException e) {
208                 log.error("Unable to locate metadata for asserting party");
209                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
210                         "Error locating asserting party metadata"));
211                 throw new ProfileException("Error locating asserting party metadata");
212             }
213         }
214     }
215
216     /**
217      * Selects the appropriate endpoint for the relying party and stores it in the request context.
218      * 
219      * @param requestContext current request context
220      * 
221      * @return Endpoint selected from the information provided in the request context
222      */
223     protected Endpoint selectEndpoint(AttributeQueryContext requestContext) {
224         Endpoint endpoint;
225
226         if (getInboundBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {
227             endpoint = acsEndpointBuilder.buildObject();
228             endpoint.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI);
229         } else {
230             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
231             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
232             endpointSelector.setMetadataProvider(getMetadataProvider());
233             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
234             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
235             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
236             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
237             endpoint = endpointSelector.selectEndpoint();
238         }
239
240         return endpoint;
241     }
242
243     /** Basic data structure used to accumulate information as a request is being processed. */
244     protected class AttributeQueryContext extends
245             BaseSAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
246
247     }
248 }