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