Security policy work round two, now wired into the IdP
[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.Response;
27 import org.opensaml.saml2.core.Statement;
28 import org.opensaml.saml2.core.StatusCode;
29 import org.opensaml.saml2.metadata.AssertionConsumerService;
30 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
31 import org.opensaml.saml2.metadata.Endpoint;
32 import org.opensaml.saml2.metadata.SPSSODescriptor;
33 import org.opensaml.saml2.metadata.provider.MetadataProvider;
34 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
35 import org.opensaml.ws.message.decoder.MessageDecodingException;
36 import org.opensaml.ws.transport.http.HTTPInTransport;
37 import org.opensaml.ws.transport.http.HTTPOutTransport;
38 import org.opensaml.xml.security.SecurityException;
39 import org.slf4j.Logger;
40 import org.slf4j.LoggerFactory;
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.saml2.AttributeQueryConfiguration;
45
46 /** SAML 2.0 Attribute Query profile handler. */
47 public class AttributeQueryProfileHandler extends AbstractSAML2ProfileHandler {
48
49     /** Class logger. */
50     private static Logger log = LoggerFactory.getLogger(AttributeQueryProfileHandler.class);
51     
52     /** Builder of assertion consumer service endpoints. */
53     private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
54
55     /** Constructor. */
56     public AttributeQueryProfileHandler() {
57         super();
58
59         acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
60                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
61     }
62
63     /** {@inheritDoc} */
64     public String getProfileId() {
65         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:query:attribute";
66     }
67
68     /** {@inheritDoc} */
69     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
70         Response samlResponse;
71
72         AttributeQueryContext requestContext = decodeRequest(inTransport, outTransport);
73
74         try {
75             if (requestContext.getProfileConfiguration() == null) {
76                 log.error("SAML 2 Attribute Query profile is not configured for relying party "
77                         + requestContext.getInboundMessageIssuer());
78                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
79                         "SAML 2 Attribute Query profile is not configured for relying party "
80                                 + requestContext.getInboundMessageIssuer()));
81                 throw new ProfileException("SAML 2 Attribute Query profile is not configured for relying party "
82                                 + requestContext.getInboundMessageIssuer());
83             }
84
85             checkSamlVersion(requestContext);
86
87             // Resolve attribute query name id to principal name and place in context
88             resolvePrincipal(requestContext);
89             resolveAttributes(requestContext);
90             requestContext.setReleasedAttributes(requestContext.getPrincipalAttributes().keySet());
91
92             // Lookup principal name and attributes, create attribute statement from information
93             ArrayList<Statement> statements = new ArrayList<Statement>();
94             statements.add(buildAttributeStatement(requestContext));
95
96             // create the SAML response
97             samlResponse = buildResponse(requestContext, "urn:oasis:names:tc:SAML:2.0:cm:sender-vouches", statements);
98         } catch (ProfileException e) {
99             samlResponse = buildErrorResponse(requestContext);
100         }
101
102         requestContext.setOutboundSAMLMessage(samlResponse);
103         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
104         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
105
106         encodeResponse(requestContext);
107         writeAuditLogEntry(requestContext);
108     }
109
110     /**
111      * Decodes an incoming request and populates a created request context with the resultant information.
112      * 
113      * @param inTransport inbound message transport
114      * @param outTransport outbound message transport
115      * 
116      * @return the created request context
117      * 
118      * @throws ProfileException throw if there is a problem decoding the request
119      */
120     protected AttributeQueryContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
121             throws ProfileException {
122         log.debug("Decoding incomming request");
123
124         MetadataProvider metadataProvider = getMetadataProvider();
125
126         AttributeQueryContext requestContext = new AttributeQueryContext();
127         requestContext.setMetadataProvider(metadataProvider);
128         
129         requestContext.setCommunicationProfileId(AttributeQueryConfiguration.PROFILE_ID);
130         requestContext.setInboundMessageTransport(inTransport);
131         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
132         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
133
134         
135         requestContext.setOutboundMessageTransport(outTransport);
136         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
137
138         try {
139             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
140             requestContext.setMessageDecoder(decoder);
141             decoder.decode(requestContext);
142             log.debug("Decoded request");
143             return requestContext;
144         } catch (MessageDecodingException e) {
145             log.error("Error decoding attribute query message", e);
146             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
147             throw new ProfileException("Error decoding attribute query message");
148         } catch (SecurityException e) {
149             log.error("Message did not meet security requirements", e);
150             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
151                     "Message did not meet security requirements"));
152             throw new ProfileException("Message did not meet security requirements", e);
153         } finally {
154             // Set as much information as can be retrieved from the decoded message
155             try {
156                 AttributeQuery query = requestContext.getInboundSAMLMessage();
157                 requestContext.setSubjectNameIdentifier(query.getSubject().getNameID());
158                 
159                 String relyingPartyId = requestContext.getInboundMessageIssuer();
160                 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
161                 requestContext.setRelyingPartyConfiguration(rpConfig);
162                 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
163
164                 String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
165                 requestContext.setLocalEntityId(assertingPartyId);
166                 requestContext.setLocalEntityMetadata(metadataProvider.getEntityDescriptor(assertingPartyId));
167                 requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
168                 requestContext.setLocalEntityRoleMetadata(requestContext.getLocalEntityMetadata()
169                         .getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS));
170
171                 AttributeQueryConfiguration profileConfig = (AttributeQueryConfiguration) rpConfig
172                         .getProfileConfiguration(AttributeQueryConfiguration.PROFILE_ID);
173                 if(profileConfig != null){
174                     requestContext.setProfileConfiguration(profileConfig);
175                     requestContext.setOutboundMessageArtifactType(profileConfig.getOutboundArtifactType());
176                     if (profileConfig.getSigningCredential() != null) {
177                         requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
178                     } else if (rpConfig.getDefaultSigningCredential() != null) {
179                         requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
180                     }
181                 }
182             } catch (MetadataProviderException e) {
183                 log.error("Unable to locate metadata for asserting or relying party");
184                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
185                         "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.SAML2_SOAP11_BINDING_URI)) {
202             endpoint = acsEndpointBuilder.buildObject();
203             endpoint.setBinding(SAMLConstants.SAML2_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             BaseSAML2ProfileRequestContext<AttributeQuery, Response, AttributeQueryConfiguration> {
221
222     }
223 }