8fdf1d1684899f62b2246c961a10291816850c2a
[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.getInboundMessageIssuer());
88                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS, StatusCode.REQUEST_DENIED,
89                         "SAML 1 Artifact resolution profile is not configured for relying party "
90                                 + requestContext.getInboundMessageIssuer()));
91                 throw new ProfileException("SAML 1 Artifact resolution profile is not configured for relying party "
92                         + requestContext.getInboundMessageIssuer());
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.setMetadataProvider(metadataProvider);
131         
132         requestContext.setInboundMessageTransport(inTransport);
133         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
134         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
135         
136         requestContext.setOutboundMessageTransport(outTransport);
137         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
138
139         try {
140             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
141             requestContext.setMessageDecoder(decoder);
142             decoder.decode(requestContext);
143             if (log.isDebugEnabled()) {
144                 log.debug("Decoded request");
145             }
146             return requestContext;
147         } catch (MessageDecodingException e) {
148             log.error("Error decoding artifact resolve message", e);
149             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
150             throw new ProfileException("Error decoding artifact resolve message");
151         } catch (SecurityPolicyException e) {
152             log.error("Message did not meet security policy requirements", e);
153             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
154                     "Message did not meet security policy requirements"));
155             throw new ProfileException("Message did not meet security policy requirements", e);
156         } finally {
157             // Set as much information as can be retrieved from the decoded message
158             try {
159                 String relyingPartyId = requestContext.getInboundMessageIssuer();
160                 
161                 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
162                 requestContext.setRelyingPartyConfiguration(rpConfig);
163
164                 String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
165                 requestContext.setLocalEntityId(assertingPartyId);
166                 requestContext.setLocalEntityMetadata(metadataProvider.getEntityDescriptor(assertingPartyId));
167                 requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
168                 requestContext.setLocalEntityRoleMetadata(requestContext.getLocalEntityMetadata()
169                         .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
170
171                 ArtifactResolutionConfiguration profileConfig = (ArtifactResolutionConfiguration) rpConfig
172                         .getProfileConfiguration(ArtifactResolutionConfiguration.PROFILE_ID);
173                 requestContext.setProfileConfiguration(profileConfig);
174                 if (profileConfig.getSigningCredential() != null) {
175                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
176                 } else if (rpConfig.getDefaultSigningCredential() != null) {
177                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
178                 }
179
180             } catch (MetadataProviderException e) {
181                 log.error("Unable to locate metadata for asserting or relying party");
182                 requestContext
183                         .setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
184                 throw new ProfileException("Error locating party metadata");
185             }
186         }
187     }
188
189     /**
190      * Selects the appropriate endpoint for the relying party and stores it in the request context.
191      * 
192      * @param requestContext current request context
193      * 
194      * @return Endpoint selected from the information provided in the request context
195      */
196     protected Endpoint selectEndpoint(ArtifactResolutionRequestContext requestContext) {
197         BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
198         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
199         endpointSelector.setMetadataProvider(getMetadataProvider());
200         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
201         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
202         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
203         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
204         return endpointSelector.selectEndpoint();
205     }
206
207     /**
208      * Derferences the provided artifacts and stores them in the request context.
209      * 
210      * @param requestContext current request context
211      */
212     protected void derferenceArtifacts(ArtifactResolutionRequestContext requestContext) {
213         Collection<AbstractSAML1Artifact> artifacts = requestContext.getArtifacts();
214         if (artifacts != null) {
215             ArrayList<Assertion> assertions = new ArrayList<Assertion>();
216             SAMLArtifactMapEntry artifactEntry;
217
218             for (AbstractSAML1Artifact artifact : artifacts) {
219                 artifactEntry = artifactMap.get(artifact.getArtifactBytes());
220                 if (artifactEntry == null || artifactEntry.isExpired()) {
221                     log.error("Unknown artifact.");
222                 }
223
224                 if (!artifactEntry.getIssuerId().equals(requestContext.getLocalEntityId())) {
225                     log.error("Artifact issuer mismatch.  Artifact issued by " + artifactEntry.getIssuerId()
226                             + " but IdP has entity ID of " + requestContext.getLocalEntityId());
227                 }
228
229                 if (!artifactEntry.getRelyingPartyId().equals(requestContext.getInboundMessageIssuer())) {
230                     log.error("Artifact requester mismatch.  Artifact was issued to "
231                             + artifactEntry.getRelyingPartyId() + " but was resolve request came from "
232                             + requestContext.getInboundMessageIssuer());
233                 }
234                 artifactMap.remove(artifact.getArtifactBytes());
235                 assertions.add((Assertion) artifactEntry.getSamlMessage());
236             }
237             requestContext.setReferencedAssertions(assertions);
238         }
239     }
240
241     /**
242      * Builds the response to the artifact request.
243      * 
244      * @param requestContext current request context
245      * 
246      * @return response to the artifact request
247      */
248     protected Response buildArtifactResponse(ArtifactResolutionRequestContext requestContext) {
249         DateTime issueInstant = new DateTime();
250
251         // create the SAML response and add the assertion
252         Response samlResponse = responseBuilder.buildObject();
253         samlResponse.setIssueInstant(issueInstant);
254         populateStatusResponse(requestContext, samlResponse);
255
256         if (requestContext.getReferencedAssertions() != null) {
257             samlResponse.getAssertions().addAll(requestContext.getReferencedAssertions());
258         }
259
260         Status status = buildStatus(StatusCode.SUCCESS, null, null);
261         samlResponse.setStatus(status);
262
263         return samlResponse;
264     }
265
266     /** Represents the internal state of a SAML 1 Artiface resolver request while it's being processed by the IdP. */
267     public class ArtifactResolutionRequestContext extends
268             BaseSAML1ProfileRequestContext<Request, Response, ArtifactResolutionConfiguration> implements
269             SAML1ArtifactMessageContext<Request, Response, NameIdentifier> {
270
271         /** Artifact to be resolved. */
272         private Collection<AbstractSAML1Artifact> artifacts;
273
274         /** Message referenced by the SAML artifact. */
275         private Collection<Assertion> referencedAssertions;
276
277         /**
278          * Gets the artifacts to be resolved.
279          * 
280          * @return artifacts to be resolved
281          */
282         public Collection<AbstractSAML1Artifact> getArtifacts() {
283             return artifacts;
284         }
285
286         /**
287          * Sets the artifacts to be resolved.
288          * 
289          * @param artifacts artifacts to be resolved
290          */
291         public void setArtifacts(Collection<AbstractSAML1Artifact> artifacts) {
292             this.artifacts = artifacts;
293         }
294
295         /**
296          * Gets the SAML assertions referenced by the artifact(s).
297          * 
298          * @return SAML assertions referenced by the artifact(s)
299          */
300         public Collection<Assertion> getReferencedAssertions() {
301             return referencedAssertions;
302         }
303
304         /**
305          * Sets the SAML assertions referenced by the artifact(s).
306          * 
307          * @param assertions SAML assertions referenced by the artifact(s)
308          */
309         public void setReferencedAssertions(Collection<Assertion> assertions) {
310             referencedAssertions = assertions;
311         }
312     }
313 }