795aafbbc4a76bda325748d49df2ee6b0a0d427f
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / ArtifactResolution.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 import java.util.Collection;
21 import java.util.List;
22
23 import org.joda.time.DateTime;
24 import org.opensaml.common.SAMLObjectBuilder;
25 import org.opensaml.common.binding.BasicEndpointSelector;
26 import org.opensaml.common.binding.artifact.SAMLArtifactMap;
27 import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry;
28 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
29 import org.opensaml.common.xml.SAMLConstants;
30 import org.opensaml.saml1.binding.SAML1ArtifactMessageContext;
31 import org.opensaml.saml1.core.Assertion;
32 import org.opensaml.saml1.core.AssertionArtifact;
33 import org.opensaml.saml1.core.NameIdentifier;
34 import org.opensaml.saml1.core.Request;
35 import org.opensaml.saml1.core.Response;
36 import org.opensaml.saml1.core.Status;
37 import org.opensaml.saml1.core.StatusCode;
38 import org.opensaml.saml2.metadata.AssertionConsumerService;
39 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
40 import org.opensaml.saml2.metadata.Endpoint;
41 import org.opensaml.saml2.metadata.EntityDescriptor;
42 import org.opensaml.saml2.metadata.SPSSODescriptor;
43 import org.opensaml.saml2.metadata.provider.MetadataProvider;
44 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
45 import org.opensaml.ws.message.decoder.MessageDecodingException;
46 import org.opensaml.ws.transport.http.HTTPInTransport;
47 import org.opensaml.ws.transport.http.HTTPOutTransport;
48 import org.opensaml.xml.security.SecurityException;
49 import org.slf4j.Logger;
50 import org.slf4j.LoggerFactory;
51
52 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
53 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
54 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ArtifactResolutionConfiguration;
55
56 /**
57  * SAML 1 Artifact resolution profile handler.
58  */
59 public class ArtifactResolution extends AbstractSAML1ProfileHandler {
60
61     /** Class logger. */
62     private final Logger log = LoggerFactory.getLogger(ArtifactResolution.class);
63
64     /** Builder of Response objects. */
65     private SAMLObjectBuilder<Response> responseBuilder;
66
67     /** Builder of assertion consumer service endpoints. */
68     private SAMLObjectBuilder<AssertionConsumerService> acsEndpointBuilder;
69
70     /** Map artifacts to SAML messages. */
71     private SAMLArtifactMap artifactMap;
72
73     /**
74      * Constructor.
75      * 
76      * @param map ArtifactMap used to lookup artifacts to be resolved.
77      */
78     public ArtifactResolution(SAMLArtifactMap map) {
79         super();
80
81         artifactMap = map;
82
83         responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
84         acsEndpointBuilder = (SAMLObjectBuilder<AssertionConsumerService>) getBuilderFactory().getBuilder(
85                 AssertionConsumerService.DEFAULT_ELEMENT_NAME);
86     }
87
88     /** {@inheritDoc} */
89     public String getProfileId() {
90         return "urn:mace:shibboleth:2.0:idp:profiles:saml1:request:artifact";
91     }
92
93     /** {@inheritDoc} */
94     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
95         Response samlResponse;
96
97         ArtifactResolutionRequestContext requestContext = decodeRequest(inTransport, outTransport);
98
99         try {
100             if (requestContext.getProfileConfiguration() == null) {
101                 log.error("SAML 1 Artifact resolution profile is not configured for relying party "
102                         + requestContext.getInboundMessageIssuer());
103                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS, StatusCode.REQUEST_DENIED,
104                         "SAML 1 Artifact resolution profile is not configured for relying party "
105                                 + requestContext.getInboundMessageIssuer()));
106                 throw new ProfileException("SAML 1 Artifact resolution profile is not configured for relying party "
107                         + requestContext.getInboundMessageIssuer());
108             }
109
110             checkSamlVersion(requestContext);
111
112             derferenceArtifacts(requestContext);
113
114             // create the SAML response
115             samlResponse = buildArtifactResponse(requestContext);
116         } catch (ProfileException e) {
117             samlResponse = buildErrorResponse(requestContext);
118         }
119
120         requestContext.setOutboundSAMLMessage(samlResponse);
121         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
122         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
123
124         encodeResponse(requestContext);
125         writeAuditLogEntry(requestContext);
126     }
127
128     /**
129      * Decodes an incoming request and populates a created request context with the resultant information.
130      * 
131      * @param inTransport inbound message transport
132      * @param outTransport outbound message transport
133      * 
134      * @return the created request context
135      * 
136      * @throws ProfileException throw if there is a problem decoding the request
137      */
138     protected ArtifactResolutionRequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
139             throws ProfileException {
140         log.debug("Decoding message with decoder binding {}", getInboundBinding());
141
142         MetadataProvider metadataProvider = getMetadataProvider();
143
144         ArtifactResolutionRequestContext requestContext = new ArtifactResolutionRequestContext();
145         requestContext.setMetadataProvider(metadataProvider);
146         requestContext.setSecurityPolicyResolver(getSecurityPolicyResolver());
147
148         requestContext.setCommunicationProfileId(ArtifactResolutionConfiguration.PROFILE_ID);
149         requestContext.setInboundMessageTransport(inTransport);
150         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
151         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
152
153         requestContext.setOutboundMessageTransport(outTransport);
154         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
155
156         try {
157             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
158             requestContext.setMessageDecoder(decoder);
159             decoder.decode(requestContext);
160             log.debug("Decoded request");
161             return requestContext;
162         } catch (MessageDecodingException e) {
163             log.error("Error decoding artifact resolve message", e);
164             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
165             throw new ProfileException("Error decoding artifact resolve message");
166         } catch (SecurityException e) {
167             log.error("Message did not meet security requirements", e);
168             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
169                     "Message did not meet security requirements"));
170             throw new ProfileException("Message did not meet security requirements", e);
171         } finally {
172             // Set as much information as can be retrieved from the decoded message
173             String relyingPartyId = requestContext.getInboundMessageIssuer();
174             RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
175             if (rpConfig == null) {
176                 log.error("Unable to retrieve relying party configuration data for entity with ID {}", relyingPartyId);
177                 throw new ProfileException("Unable to retrieve relying party configuration data for entity with ID "
178                         + relyingPartyId);
179             }
180             requestContext.setRelyingPartyConfiguration(rpConfig);
181
182             ArtifactResolutionConfiguration profileConfig = (ArtifactResolutionConfiguration) rpConfig
183                     .getProfileConfiguration(ArtifactResolutionConfiguration.PROFILE_ID);
184             if (profileConfig != null) {
185                 requestContext.setProfileConfiguration(profileConfig);
186                 if (profileConfig.getSigningCredential() != null) {
187                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
188                 } else if (rpConfig.getDefaultSigningCredential() != null) {
189                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
190                 }
191             }
192
193             requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
194
195             String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
196             requestContext.setLocalEntityId(assertingPartyId);
197             try {
198                 EntityDescriptor localEntityDescriptor = metadataProvider.getEntityDescriptor(assertingPartyId);
199                 if (localEntityDescriptor != null) {
200                     requestContext.setLocalEntityMetadata(localEntityDescriptor);
201                     requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
202                     requestContext.setLocalEntityRoleMetadata(localEntityDescriptor
203                             .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
204                 }
205             } catch (MetadataProviderException e) {
206                 log.error("Unable to locate metadata for asserting party");
207                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null,
208                         "Error locating asserting party metadata"));
209                 throw new ProfileException("Error locating asserting party metadata");
210             }
211         }
212     }
213
214     /**
215      * Selects the appropriate endpoint for the relying party and stores it in the request context.
216      * 
217      * @param requestContext current request context
218      * 
219      * @return Endpoint selected from the information provided in the request context
220      */
221     protected Endpoint selectEndpoint(ArtifactResolutionRequestContext requestContext) {
222         Endpoint endpoint;
223
224         if (getInboundBinding().equals(SAMLConstants.SAML1_SOAP11_BINDING_URI)) {
225             endpoint = acsEndpointBuilder.buildObject();
226             endpoint.setBinding(SAMLConstants.SAML1_SOAP11_BINDING_URI);
227         } else {
228             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
229             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
230             endpointSelector.setMetadataProvider(getMetadataProvider());
231             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
232             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
233             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
234             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
235             endpoint = endpointSelector.selectEndpoint();
236         }
237
238         return endpoint;
239     }
240
241     /**
242      * Derferences the artifacts within the incomming request and stores them in the request context.
243      * 
244      * @param requestContext current request context
245      * 
246      * @throws ProfileException thrown if the incomming request does not contain any {@link AssertionArtifact}s.
247      */
248     protected void derferenceArtifacts(ArtifactResolutionRequestContext requestContext) throws ProfileException {
249         Request request = requestContext.getInboundSAMLMessage();
250         List<AssertionArtifact> assertionArtifacts = request.getAssertionArtifacts();
251
252         if (assertionArtifacts == null || assertionArtifacts.size() == 0) {
253             log.error("No AssertionArtifacts available in request");
254             throw new ProfileException("No AssertionArtifacts available in request");
255         }
256
257         ArrayList<Assertion> assertions = new ArrayList<Assertion>();
258         SAMLArtifactMapEntry artifactEntry;
259         for (AssertionArtifact assertionArtifact : assertionArtifacts) {
260             artifactEntry = artifactMap.get(assertionArtifact.getAssertionArtifact());
261             if (artifactEntry == null || artifactEntry.isExpired()) {
262                 log.error("Unknown artifact.");
263             }
264
265             if (!artifactEntry.getIssuerId().equals(requestContext.getLocalEntityId())) {
266                 log.error("Artifact issuer mismatch.  Artifact issued by " + artifactEntry.getIssuerId()
267                         + " but IdP has entity ID of " + requestContext.getLocalEntityId());
268             }
269
270             artifactMap.remove(assertionArtifact.getAssertionArtifact());
271             assertions.add((Assertion) artifactEntry.getSamlMessage());
272         }
273
274         requestContext.setReferencedAssertions(assertions);
275     }
276
277     /**
278      * Builds the response to the artifact request.
279      * 
280      * @param requestContext current request context
281      * 
282      * @return response to the artifact request
283      */
284     protected Response buildArtifactResponse(ArtifactResolutionRequestContext requestContext) {
285         DateTime issueInstant = new DateTime();
286
287         // create the SAML response and add the assertion
288         Response samlResponse = responseBuilder.buildObject();
289         samlResponse.setIssueInstant(issueInstant);
290         populateStatusResponse(requestContext, samlResponse);
291
292         if (requestContext.getReferencedAssertions() != null) {
293             samlResponse.getAssertions().addAll(requestContext.getReferencedAssertions());
294         }
295
296         Status status = buildStatus(StatusCode.SUCCESS, null, null);
297         samlResponse.setStatus(status);
298
299         return samlResponse;
300     }
301
302     /** Represents the internal state of a SAML 1 Artiface resolver request while it's being processed by the IdP. */
303     public class ArtifactResolutionRequestContext extends
304             BaseSAML1ProfileRequestContext<Request, Response, ArtifactResolutionConfiguration> implements
305             SAML1ArtifactMessageContext<Request, Response, NameIdentifier> {
306
307         /** Artifact to be resolved. */
308         private Collection<String> artifacts;
309
310         /** Message referenced by the SAML artifact. */
311         private Collection<Assertion> referencedAssertions;
312
313         /** {@inheritDoc} */
314         public Collection<String> getArtifacts() {
315             return artifacts;
316         }
317
318         /** {@inheritDoc} */
319         public void setArtifacts(Collection<String> encodedArtifacts) {
320             this.artifacts = encodedArtifacts;
321         }
322
323         /**
324          * Gets the SAML assertions referenced by the artifact(s).
325          * 
326          * @return SAML assertions referenced by the artifact(s)
327          */
328         public Collection<Assertion> getReferencedAssertions() {
329             return referencedAssertions;
330         }
331
332         /**
333          * Sets the SAML assertions referenced by the artifact(s).
334          * 
335          * @param assertions SAML assertions referenced by the artifact(s)
336          */
337         public void setReferencedAssertions(Collection<Assertion> assertions) {
338             referencedAssertions = assertions;
339         }
340     }
341 }