103cd5fe76d20933a6b9c58dfc9937b31cef7d12
[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.apache.log4j.Logger;
24 import org.joda.time.DateTime;
25 import org.opensaml.common.SAMLObjectBuilder;
26 import org.opensaml.common.binding.BasicEndpointSelector;
27 import org.opensaml.common.binding.artifact.SAMLArtifactMap;
28 import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry;
29 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
30 import org.opensaml.common.xml.SAMLConstants;
31 import org.opensaml.saml1.binding.SAML1ArtifactMessageContext;
32 import org.opensaml.saml1.core.Assertion;
33 import org.opensaml.saml1.core.AssertionArtifact;
34 import org.opensaml.saml1.core.NameIdentifier;
35 import org.opensaml.saml1.core.Request;
36 import org.opensaml.saml1.core.Response;
37 import org.opensaml.saml1.core.Status;
38 import org.opensaml.saml1.core.StatusCode;
39 import org.opensaml.saml2.metadata.AssertionConsumerService;
40 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
41 import org.opensaml.saml2.metadata.Endpoint;
42 import org.opensaml.saml2.metadata.EntityDescriptor;
43 import org.opensaml.saml2.metadata.SPSSODescriptor;
44 import org.opensaml.saml2.metadata.provider.MetadataProvider;
45 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
46 import org.opensaml.ws.message.decoder.MessageDecodingException;
47 import org.opensaml.ws.security.SecurityPolicyException;
48 import org.opensaml.ws.transport.http.HTTPInTransport;
49 import org.opensaml.ws.transport.http.HTTPOutTransport;
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 = Logger.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         if (log.isDebugEnabled()) {
140             log.debug("Decoding incomming request");
141         }
142
143         MetadataProvider metadataProvider = getMetadataProvider();
144
145         ArtifactResolutionRequestContext requestContext = new ArtifactResolutionRequestContext();
146         requestContext.setMetadataProvider(metadataProvider);
147
148         requestContext.setInboundMessageTransport(inTransport);
149         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
150         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
151
152         requestContext.setOutboundMessageTransport(outTransport);
153         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
154
155         try {
156             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
157             requestContext.setMessageDecoder(decoder);
158             decoder.decode(requestContext);
159             if (log.isDebugEnabled()) {
160                 log.debug("Decoded request");
161             }
162             return requestContext;
163         } catch (MessageDecodingException e) {
164             log.error("Error decoding artifact resolve message", e);
165             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
166             throw new ProfileException("Error decoding artifact resolve message");
167         } catch (SecurityPolicyException e) {
168             log.error("Message did not meet security policy requirements", e);
169             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
170                     "Message did not meet security policy requirements"));
171             throw new ProfileException("Message did not meet security policy requirements", e);
172         } finally {
173             // Set as much information as can be retrieved from the decoded message
174             try {
175                 String relyingPartyId = requestContext.getInboundMessageIssuer();
176                 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
177                 requestContext.setRelyingPartyConfiguration(rpConfig);
178                 requestContext.setPeerEntityEndpoint(selectEndpoint(requestContext));
179
180                 String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
181                 requestContext.setLocalEntityId(assertingPartyId);
182                 EntityDescriptor assertingPartyMetadata = metadataProvider.getEntityDescriptor(assertingPartyId);
183                 if (assertingPartyMetadata == null) {
184                     throw new MetadataProviderException("Unable to locate metadata for asserting party "
185                             + assertingPartyId);
186                 }
187                 requestContext.setLocalEntityMetadata(assertingPartyMetadata);
188                 requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
189                 requestContext.setLocalEntityRoleMetadata(assertingPartyMetadata
190                         .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
191
192                 ArtifactResolutionConfiguration profileConfig = (ArtifactResolutionConfiguration) rpConfig
193                         .getProfileConfiguration(ArtifactResolutionConfiguration.PROFILE_ID);
194                 if (profileConfig != null) {
195                     requestContext.setProfileConfiguration(profileConfig);
196                     if (profileConfig.getSigningCredential() != null) {
197                         requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
198                     } else if (rpConfig.getDefaultSigningCredential() != null) {
199                         requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
200                     }
201                 }
202
203             } catch (MetadataProviderException e) {
204                 log.error(e.getMessage());
205                 requestContext
206                         .setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
207                 throw new ProfileException("Error locating party metadata");
208             }
209         }
210     }
211
212     /**
213      * Selects the appropriate endpoint for the relying party and stores it in the request context.
214      * 
215      * @param requestContext current request context
216      * 
217      * @return Endpoint selected from the information provided in the request context
218      */
219     protected Endpoint selectEndpoint(ArtifactResolutionRequestContext requestContext) {
220         Endpoint endpoint;
221
222         if (getInboundBinding().equals(SAMLConstants.SAML1_SOAP11_BINDING_URI)) {
223             endpoint = acsEndpointBuilder.buildObject();
224             endpoint.setBinding(SAMLConstants.SAML1_SOAP11_BINDING_URI);
225         } else {
226             BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
227             endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
228             endpointSelector.setMetadataProvider(getMetadataProvider());
229             endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
230             endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
231             endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
232             endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
233             endpoint = endpointSelector.selectEndpoint();
234         }
235
236         return endpoint;
237     }
238
239     /**
240      * Derferences the artifacts within the incomming request and stores them in the request context.
241      * 
242      * @param requestContext current request context
243      * 
244      * @throws ProfileException thrown if the incomming request does not contain any {@link AssertionArtifact}s.
245      */
246     protected void derferenceArtifacts(ArtifactResolutionRequestContext requestContext) throws ProfileException {
247         Request request = requestContext.getInboundSAMLMessage();
248         List<AssertionArtifact> assertionArtifacts = request.getAssertionArtifacts();
249
250         if (assertionArtifacts == null || assertionArtifacts.size() == 0) {
251             log.error("No AssertionArtifacts available in request");
252             throw new ProfileException("No AssertionArtifacts available in request");
253         }
254
255         ArrayList<Assertion> assertions = new ArrayList<Assertion>();
256         SAMLArtifactMapEntry artifactEntry;
257         for (AssertionArtifact assertionArtifact : assertionArtifacts) {
258             artifactEntry = artifactMap.get(assertionArtifact.getAssertionArtifact());
259             if (artifactEntry == null || artifactEntry.isExpired()) {
260                 log.error("Unknown artifact.");
261             }
262
263             if (!artifactEntry.getIssuerId().equals(requestContext.getLocalEntityId())) {
264                 log.error("Artifact issuer mismatch.  Artifact issued by " + artifactEntry.getIssuerId()
265                         + " but IdP has entity ID of " + requestContext.getLocalEntityId());
266             }
267
268             artifactMap.remove(assertionArtifact.getAssertionArtifact());
269             assertions.add((Assertion) artifactEntry.getSamlMessage());
270         }
271
272         requestContext.setReferencedAssertions(assertions);
273     }
274
275     /**
276      * Builds the response to the artifact request.
277      * 
278      * @param requestContext current request context
279      * 
280      * @return response to the artifact request
281      */
282     protected Response buildArtifactResponse(ArtifactResolutionRequestContext requestContext) {
283         DateTime issueInstant = new DateTime();
284
285         // create the SAML response and add the assertion
286         Response samlResponse = responseBuilder.buildObject();
287         samlResponse.setIssueInstant(issueInstant);
288         populateStatusResponse(requestContext, samlResponse);
289
290         if (requestContext.getReferencedAssertions() != null) {
291             samlResponse.getAssertions().addAll(requestContext.getReferencedAssertions());
292         }
293
294         Status status = buildStatus(StatusCode.SUCCESS, null, null);
295         samlResponse.setStatus(status);
296
297         return samlResponse;
298     }
299
300     /** Represents the internal state of a SAML 1 Artiface resolver request while it's being processed by the IdP. */
301     public class ArtifactResolutionRequestContext extends
302             BaseSAML1ProfileRequestContext<Request, Response, ArtifactResolutionConfiguration> implements
303             SAML1ArtifactMessageContext<Request, Response, NameIdentifier> {
304
305         /** Artifact to be resolved. */
306         private Collection<String> artifacts;
307
308         /** Message referenced by the SAML artifact. */
309         private Collection<Assertion> referencedAssertions;
310
311         /** {@inheritDoc} */
312         public Collection<String> getArtifacts() {
313             return artifacts;
314         }
315
316         /** {@inheritDoc} */
317         public void setArtifacts(Collection<String> encodedArtifacts) {
318             this.artifacts = encodedArtifacts;
319         }
320
321         /**
322          * Gets the SAML assertions referenced by the artifact(s).
323          * 
324          * @return SAML assertions referenced by the artifact(s)
325          */
326         public Collection<Assertion> getReferencedAssertions() {
327             return referencedAssertions;
328         }
329
330         /**
331          * Sets the SAML assertions referenced by the artifact(s).
332          * 
333          * @param assertions SAML assertions referenced by the artifact(s)
334          */
335         public void setReferencedAssertions(Collection<Assertion> assertions) {
336             referencedAssertions = assertions;
337         }
338     }
339 }