Add some logging messages
[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.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.saml2.core.AttributeQuery;
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.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.saml2.AttributeQueryConfiguration;
44
45 /** SAML 2.0 Attribute Query profile handler. */
46 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
47
48     /** Class logger. */
49     private static Logger log = Logger.getLogger(AttributeQueryProfileHandler.class);
50     
51     /** Builder of assertion consumer service endpoints. */
52     private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
53
54     /** Constructor. */
55     public AttributeQueryProfileHandler() {
56         super();
57
58         acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
59                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
60     }
61
62     /** {@inheritDoc} */
63     public String getProfileId() {
64         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:query:attribute";
65     }
66
67     /** {@inheritDoc} */
68     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
69         Response samlResponse;
70
71         AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
72
73         try {
74             if (requestContext.getProfileConfiguration() == null) {
75                 log.error("SAML 2 Attribute Query profile is not configured for relying party "
76                         + requestContext.getInboundMessageIssuer());
77                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
78                         "SAML 2 Attribute Query profile is not configured for relying party "
79                                 + requestContext.getInboundMessageIssuer()));
80                 samlResponse = buildErrorResponse(requestContext);
81             }
82
83             checkSamlVersion(requestContext);
84
85             // Resolve attribute query name id to principal name and place in context
86             resolvePrincipal(requestContext);
87             resolveAttributes(requestContext);
88             requestContext.setReleasedAttributes(requestContext.getPrincipalAttributes().keySet());
89
90             // Lookup principal name and attributes, create attribute statement from information
91             ArrayList<Statement> statements = new ArrayList<Statement>();
92             statements.add(buildAttributeStatement(requestContext));
93
94             // create the SAML response
95             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches", statements);
96         } catch (ProfileException e) {
97             samlResponse = buildErrorResponse(requestContext);
98         }
99
100         requestContext.setOutboundSAMLMessage(samlResponse);
101         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
102         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
103
104         encodeResponse(requestContext);
105         writeAuditLogEntry(requestContext);
106     }
107
108     /**
109      * Decodes an incoming request and populates a created request context with the resultant information.
110      * 
111      * @param inTransport inbound message transport
112      * @param outTransport outbound message transport
113      * 
114      * @return the created request context
115      * 
116      * @throws ProfileException throw if there is a problem decoding the request
117      */
118     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
119             throws ProfileException {
120         if (log.isDebugEnabled()) {
121             log.debug("Decoding incomming request");
122         }
123
124         MetadataProvider metadataProvider = getMetadataProvider();
125
126         AttributeQueryContext requestContext = new AttributeQueryContext();
127         requestContext.setMetadataProvider(metadataProvider);
128         
129         requestContext.setInboundMessageTransport(inTransport);
130         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
131         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
132
133         
134         requestContext.setOutboundMessageTransport(outTransport);
135         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
136
137         try {
138             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
139             requestContext.setMessageDecoder(decoder);
140             decoder.decode(requestContext);
141             if (log.isDebugEnabled()) {
142                 log.debug("Decoded request");
143             }
144             return requestContext;
145         } catch (MessageDecodingException e) {
146             log.error("Error decoding attribute query message", e);
147             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
148             throw new ProfileException("Error decoding attribute query message");
149         } catch (SecurityPolicyException e) {
150             log.error("Message did not meet security policy requirements", e);
151             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
152                     "Message did not meet security policy requirements"));
153             throw new ProfileException("Message did not meet security policy requirements", e);
154         } finally {
155             // Set as much information as can be retrieved from the decoded message
156             try {
157                 AttributeQuery query = requestContext.getInboundSAMLMessage();
158                 requestContext.setSubjectNameIdentifier(query.getSubject().getNameID());
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.SAML20P_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             } catch (MetadataProviderException e) {
184                 log.error("Unable to locate metadata for asserting or relying party");
185                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
186                         "Error locating party metadata"));
187                 throw new ProfileException("Error locating party metadata");
188             }
189         }
190     }
191     
192     /**
193      * Selects the appropriate endpoint for the relying party and stores it in the request context.
194      * 
195      * @param requestContext current request context
196      * 
197      * @return Endpoint selected from the information provided in the request context
198      */
199     protected Endpoint selectEndpoint(AttributeQueryContext requestContext) {
200         Endpoint endpoint;
201
202         if (getInboundBinding().equals(SAMLConstants.SAML2_SOAP11_BINDING_URI)) {
203             endpoint = acsEndpointBuilder.buildObject();
204             endpoint.setBinding(SAMLConstants.SAML2_SOAP11_BINDING_URI);
205         } else {
206             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
207             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
208             endpointSelector.setMetadataProvider(getMetadataProvider());
209             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
210             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
211             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
212             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
213             endpoint = endpointSelector.selectEndpoint();
214         }
215
216         return endpoint;
217     }
218
219     /** Basic data structure used to accumulate information as a request is being processed. */
220     protected class AttributeQueryContext extends
221             BaseSAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
222
223     }
224 }