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