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