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