6584bce7b2ead78001183ac545b05637687eb91a
[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.core.ArtifactResolve;
29 import org.opensaml.saml2.core.ArtifactResponse;
30 import org.opensaml.saml2.core.Status;
31 import org.opensaml.saml2.core.StatusCode;
32 import org.opensaml.saml2.metadata.AssertionConsumerService;
33 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
34 import org.opensaml.saml2.metadata.Endpoint;
35 import org.opensaml.saml2.metadata.SPSSODescriptor;
36 import org.opensaml.saml2.metadata.provider.MetadataProvider;
37 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
38 import org.opensaml.ws.message.decoder.MessageDecodingException;
39 import org.opensaml.ws.security.SecurityPolicyException;
40 import org.opensaml.ws.transport.http.HTTPInTransport;
41 import org.opensaml.ws.transport.http.HTTPOutTransport;
42
43 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
44 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
45 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml2.ArtifactResolutionConfiguration;
46
47 /**
48  * SAML 2.0 Artifact resolution profile handler.
49  */
50 public class ArtifactResolution extends AbstractSAML2ProfileHandler {
51
52     /** Class logger. */
53     private final Logger log = Logger.getLogger(ArtifactResolution.class);
54
55     /** Map artifacts to SAML messages. */
56     private SAMLArtifactMap artifactMap;
57
58     /** Artifact response object builder. */
59     private SAMLObjectBuilder<ArtifactResponse> responseBuilder;
60
61     public ArtifactResolution() {
62         super();
63         responseBuilder = (SAMLObjectBuilder<ArtifactResponse>) getBuilderFactory().getBuilder(
64                 ArtifactResponse.DEFAULT_ELEMENT_NAME);
65     }
66
67     /** {@inheritDoc} */
68     public String getProfileId() {
69         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:artifact";
70     }
71
72     /** {@inheritDoc} */
73     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
74         ArtifactResponse samlResponse;
75
76         ArtifactResolutionRequestContext requestContext = decodeRequest(inTransport, outTransport);
77
78         try {
79             if (requestContext.getRelyingPartyConfiguration() == null) {
80                 log.error("SAML 2 Artifact Resolve profile is not configured for relying party "
81                         + requestContext.getPeerEntityId());
82                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
83                         "SAML 2 Artifact Resolve profile is not configured for relying party "
84                                 + requestContext.getPeerEntityId()));
85                 throw new ProfileException("SAML 2 Artifact Resolve profile is not configured for relying party "
86                         + requestContext.getPeerEntityId());
87             }
88
89             checkSamlVersion(requestContext);
90
91             SAMLArtifactMapEntry artifactEntry = artifactMap.peek(requestContext.getArtifact().getBytes());
92             if (artifactEntry == null || artifactEntry.isExpired()) {
93                 log.error("Unknown artifact.");
94                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
95                         "Unknown artifact."));
96                 throw new ProfileException("Unknown artifact.");
97             }
98             
99             if (!artifactEntry.getIssuerId().equals(requestContext.getLocalEntityId())) {
100                 log.error("Artifact issuer mismatch.  Artifact issued by " + artifactEntry.getIssuerId()
101                         + " but IdP has entity ID of " + requestContext.getLocalEntityId());
102                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
103                         "Artifact issuer mismatch."));
104                 throw new ProfileException("Artifact issuer mismatch.");
105             }
106
107             if (!artifactEntry.getRelyingPartyId().equals(requestContext.getPeerEntityId())) {
108                 log.error("Artifact requester mismatch.  Artifact was issued to " + artifactEntry.getRelyingPartyId()
109                         + " but was resolve request came from " + requestContext.getPeerEntityId());
110                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
111                         "Artifact requester mismatch."));
112                 throw new ProfileException("Artifact requester mismatch.");
113             }
114
115             SAMLObject referencedMessage = artifactEntry.getSamlMessage();
116             requestContext.setReferencedMessage(referencedMessage);
117
118             // create the SAML response
119             samlResponse = buildArtifactResponse(requestContext);
120         } catch (ProfileException e) {
121             samlResponse = buildArtifactErrorResponse(requestContext);
122         }
123
124         requestContext.setOutboundSAMLMessage(samlResponse);
125         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
126         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
127
128         encodeResponse(requestContext);
129         writeAuditLogEntry(requestContext);
130     }
131
132     /**
133      * Decodes an incoming request and populates a created request context with the resultant information.
134      * 
135      * @param inTransport inbound message transport
136      * @param outTransport outbound message transport
137      * 
138      * @return the created request context
139      * 
140      * @throws ProfileException throw if there is a problem decoding the request
141      */
142     protected ArtifactResolutionRequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
143             throws ProfileException {
144         if (log.isDebugEnabled()) {
145             log.debug("Decoding incomming request");
146         }
147
148         MetadataProvider metadataProvider = getMetadataProvider();
149
150         ArtifactResolutionRequestContext requestContext = new ArtifactResolutionRequestContext();
151         requestContext.setInboundMessageTransport(inTransport);
152         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
153         requestContext.setOutboundMessageTransport(outTransport);
154         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
155         requestContext.setMetadataProvider(metadataProvider);
156
157         try {
158             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
159             requestContext.setMessageDecoder(decoder);
160             decoder.decode(requestContext);
161             if (log.isDebugEnabled()) {
162                 log.debug("Decoded request");
163             }
164             return requestContext;
165         } catch (MessageDecodingException e) {
166             log.error("Error decoding artifact resolve message", e);
167             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
168             throw new ProfileException("Error decoding artifact resolve message");
169         } catch (SecurityPolicyException e) {
170             log.error("Message did not meet security policy requirements", e);
171             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
172                     "Message did not meet security policy requirements"));
173             throw new ProfileException("Message did not meet security policy requirements", e);
174         } finally {
175             // Set as much information as can be retrieved from the decoded message
176             try {
177                 ArtifactResolve artResolve = requestContext.getInboundSAMLMessage();
178                 requestContext.setArtifact(artResolve.getArtifact().getArtifact());
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.setRelyingParty(requestContext.getPeerEntityMetadata());
227         endpointSelector.setRelyingPartyRole(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         Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
249         samlResponse.setStatus(status);
250
251         samlResponse.setMessage(requestContext.getReferencedMessage());
252
253         return samlResponse;
254     }
255
256     /**
257      * Constructs an artifact resolution response with an error status as content.
258      * 
259      * @param requestContext current request context
260      * 
261      * @return constructed response
262      */
263     protected ArtifactResponse buildArtifactErrorResponse(ArtifactResolutionRequestContext requestContext) {
264         ArtifactResponse samlResponse = responseBuilder.buildObject();
265         samlResponse.setIssueInstant(new DateTime());
266         populateStatusResponse(requestContext, samlResponse);
267
268         samlResponse.setStatus(requestContext.getFailureStatus());
269
270         return samlResponse;
271     }
272
273     /** Represents the internal state of a SAML 2.0 Artiface resolver request while it's being processed by the IdP. */
274     public class ArtifactResolutionRequestContext extends
275             BaseSAML2ProfileRequestContext<ArtifactResolve, ArtifactResponse, ArtifactResolutionConfiguration> {
276
277         /** Artifact to be resolved. */
278         private String artifact;
279
280         /** Message referenced by the SAML artifact. */
281         private SAMLObject referencedMessage;
282
283         /**
284          * Gets the artifact to be resolved.
285          * 
286          * @return artifact to be resolved
287          */
288         public String getArtifact() {
289             return artifact;
290         }
291
292         /**
293          * Sets the artifact to be resolved.
294          * 
295          * @param artifact artifact to be resolved
296          */
297         public void setArtifact(String artifact) {
298             this.artifact = artifact;
299         }
300
301         /**
302          * Gets the SAML message referenced by the artifact.
303          * 
304          * @return SAML message referenced by the artifact
305          */
306         public SAMLObject getReferencedMessage() {
307             return referencedMessage;
308         }
309
310         /**
311          * Sets the SAML message referenced by the artifact.
312          * 
313          * @param message SAML message referenced by the artifact
314          */
315         public void setReferencedMessage(SAMLObject message) {
316             referencedMessage = message;
317         }
318     }
319 }