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