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