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