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