Finish synch up with OpenSAML stack message context API changes
[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.xml.SAMLConstants;
23 import org.opensaml.saml2.core.AttributeQuery;
24 import org.opensaml.saml2.core.Response;
25 import org.opensaml.saml2.core.Statement;
26 import org.opensaml.saml2.core.StatusCode;
27 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
28 import org.opensaml.saml2.metadata.SPSSODescriptor;
29 import org.opensaml.saml2.metadata.provider.MetadataProvider;
30 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
31 import org.opensaml.ws.message.decoder.MessageDecodingException;
32 import org.opensaml.ws.message.encoder.MessageEncodingException;
33 import org.opensaml.ws.security.SecurityPolicyException;
34 import org.opensaml.ws.transport.http.HTTPInTransport;
35 import org.opensaml.ws.transport.http.HTTPOutTransport;
36
37 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
38 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
39 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.AttributeQueryConfiguration;
40
41 /** SAML 2.0 Attribute Query profile handler. */
42 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
43
44     /** Class logger. */
45     private static Logger log = Logger.getLogger(AttributeQueryProfileHandler.class);
46
47     /** {@inheritDoc} */
48     public String getProfileId() {
49         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:query:attribute";
50     }
51
52     /** {@inheritDoc} */
53     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
54         Response samlResponse;
55
56         AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
57
58         try {
59             if (requestContext.getRelyingPartyConfiguration() == null) {
60                 log.error("SAML 2 Attribute Query profile is not configured for relying party "
61                         + requestContext.getRelyingPartyEntityId());
62                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
63                         "SAML 2 Attribute Query profile is not configured for relying party "
64                                 + requestContext.getRelyingPartyEntityId()));
65                 samlResponse = buildErrorResponse(requestContext);
66             }
67
68             checkSamlVersion(requestContext);
69
70             // Resolve attribute query name id to principal name and place in context
71             resolvePrincipal(requestContext);
72
73             resolveAttributes(requestContext);
74
75             // Lookup principal name and attributes, create attribute statement from information
76             ArrayList<Statement> statements = new ArrayList<Statement>();
77             statements.add(buildAttributeStatement(requestContext));
78
79             // create the SAML response
80             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches", 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
89         encodeResponse(requestContext);
90         writeAuditLogEntry(requestContext);
91     }
92
93     /**
94      * Decodes an incoming request and populates a created request context with the resultant information.
95      * 
96      * @param inTransport inbound message transport
97      * @param outTransport outbound message transport
98      * 
99      * @return the created request context
100      * 
101      * @throws ProfileException throw if there is a problem decoding the request
102      */
103     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
104             throws ProfileException {
105         if (log.isDebugEnabled()) {
106             log.debug("Decoding incomming request");
107         }
108
109         MetadataProvider metadataProvider = getMetadataProvider();
110
111         AttributeQueryContext requestContext = new AttributeQueryContext();
112         requestContext.setMessageInTransport(inTransport);
113         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
114         requestContext.setMessageOutTransport(outTransport);
115         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
116         requestContext.setMetadataProvider(metadataProvider);
117
118         try {
119             getMessageDecoder().decode(requestContext);
120             if (log.isDebugEnabled()) {
121                 log.debug("Decoded request");
122             }
123             return requestContext;
124         } catch (MessageDecodingException e) {
125             log.error("Error decoding attribute query message", e);
126             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
127             throw new ProfileException("Error decoding attribute query message");
128         } catch (SecurityPolicyException e) {
129             log.error("Message did not meet security policy requirements", e);
130             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
131                     "Message did not meet security policy requirements"));
132             throw new ProfileException("Message did not meet security policy requirements", e);
133         } finally {
134             // Set as much information as can be retrieved from the decoded message
135             try {
136                 AttributeQuery attributeQuery = requestContext.getInboundSAMLMessage();
137                 requestContext.setInboundSAMLMessageId(attributeQuery.getID());
138                 requestContext.setInboundSAMLMessageIssueInstant(attributeQuery.getIssueInstant());
139
140                 String relyingPartyId = requestContext.getRelyingPartyEntityId();
141                 requestContext.setPeerEntityMetadata(metadataProvider.getEntityDescriptor(relyingPartyId));
142                 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
143                 requestContext.setPeerEntityRoleMetadata(requestContext.getPeerEntityMetadata().getSPSSODescriptor(
144                         SAMLConstants.SAML20P_NS));
145                 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
146                 requestContext.setRelyingPartyConfiguration(rpConfig);
147
148                 String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
149                 requestContext.setAssertingPartyEntityId(assertingPartyId);
150                 requestContext.setLocalEntityMetadata(metadataProvider.getEntityDescriptor(assertingPartyId));
151                 requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
152                 requestContext.setLocalEntityRoleMetadata(requestContext.getLocalEntityMetadata()
153                         .getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS));
154
155                 AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
156                         .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
157                 requestContext.setProfileConfiguration(profileConfig);
158                 if (profileConfig.getSigningCredential() != null) {
159                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
160                 } else if (rpConfig.getDefaultSigningCredential() != null) {
161                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
162                 }
163
164             } catch (MetadataProviderException e) {
165                 log.error("Unable to locate metadata for asserting or relying party");
166                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
167                         "Error locating party metadata"));
168                 throw new ProfileException("Error locating party metadata");
169             }
170         }
171     }
172
173     /**
174      * Encodes the request's SAML response and writes it to the servlet response.
175      * 
176      * @param requestContext current request context
177      * 
178      * @throws ProfileException thrown if no message encoder is registered for this profiles binding
179      */
180     protected void encodeResponse(AttributeQueryContext requestContext) throws ProfileException {
181         if (log.isDebugEnabled()) {
182             log.debug("Encoding response to SAML request " + requestContext.getInboundSAMLMessageId()
183                     + " from relying party " + requestContext.getRelyingPartyEntityId());
184         }
185
186         try {
187             getMessageEncoder().encode(requestContext);
188         } catch (MessageEncodingException e) {
189             throw new ProfileException("Unable to encode response to relying party: "
190                     + requestContext.getRelyingPartyEntityId(), e);
191         }
192     }
193
194     /** Basic data structure used to accumulate information as a request is being processed. */
195     protected class AttributeQueryContext extends
196             BaseSAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
197
198     }
199 }