Have decoders extract basic SAML message information (message ID, claimed issuer...
[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.setMetadataProvider(metadataProvider);
153         
154         requestContext.setInboundMessageTransport(inTransport);
155         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
156         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
157
158         
159         requestContext.setOutboundMessageTransport(outTransport);
160         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
161
162         try {
163             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
164             requestContext.setMessageDecoder(decoder);
165             decoder.decode(requestContext);
166             if (log.isDebugEnabled()) {
167                 log.debug("Decoded request");
168             }
169             return requestContext;
170         } catch (MessageDecodingException e) {
171             log.error("Error decoding artifact resolve message", e);
172             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
173             throw new ProfileException("Error decoding artifact resolve message");
174         } catch (SecurityPolicyException e) {
175             log.error("Message did not meet security policy requirements", e);
176             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
177                     "Message did not meet security policy requirements"));
178             throw new ProfileException("Message did not meet security policy requirements", e);
179         } finally {
180             // Set as much information as can be retrieved from the decoded message
181             try {
182                 String relyingPartyId = requestContext.getPeerEntityId();
183                 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
184                 requestContext.setRelyingPartyConfiguration(rpConfig);
185
186                 String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
187                 requestContext.setLocalEntityId(assertingPartyId);
188                 requestContext.setLocalEntityMetadata(metadataProvider.getEntityDescriptor(assertingPartyId));
189                 requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
190                 requestContext.setLocalEntityRoleMetadata(requestContext.getLocalEntityMetadata()
191                         .getAttributeAuthorityDescriptor(SAMLConstants.SAML20P_NS));
192
193                 ArtifactResolutionConfiguration profileConfig = (ArtifactResolutionConfiguration) rpConfig
194                         .getProfileConfiguration(ArtifactResolutionConfiguration.PROFILE_ID);
195                 requestContext.setProfileConfiguration(profileConfig);
196                 if (profileConfig.getSigningCredential() != null) {
197                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
198                 } else if (rpConfig.getDefaultSigningCredential() != null) {
199                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
200                 }
201
202             } catch (MetadataProviderException e) {
203                 log.error("Unable to locate metadata for asserting or relying party");
204                 requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null,
205                         "Error locating party metadata"));
206                 throw new ProfileException("Error locating party metadata");
207             }
208         }
209     }
210
211     /**
212      * Selects the appropriate endpoint for the relying party and stores it in the request context.
213      * 
214      * @param requestContext current request context
215      * 
216      * @return Endpoint selected from the information provided in the request context
217      */
218     protected Endpoint selectEndpoint(ArtifactResolutionRequestContext requestContext) {
219         BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
220         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
221         endpointSelector.setMetadataProvider(getMetadataProvider());
222         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
223         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
224         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
225         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
226         return endpointSelector.selectEndpoint();
227     }
228
229     /**
230      * Constructs a artifact resolution response with the derferenced SAML message inside.
231      * 
232      * @param requestContext current request context
233      * 
234      * @return constructed response
235      */
236     protected ArtifactResponse buildArtifactResponse(ArtifactResolutionRequestContext requestContext) {
237         DateTime issueInstant = new DateTime();
238
239         // create the SAML response and add the assertion
240         ArtifactResponse samlResponse = responseBuilder.buildObject();
241         samlResponse.setIssueInstant(issueInstant);
242         populateStatusResponse(requestContext, samlResponse);
243
244         if (requestContext.getFailureStatus() == null) {
245             Status status = buildStatus(StatusCode.SUCCESS_URI, null, null);
246             samlResponse.setStatus(status);
247             samlResponse.setMessage(requestContext.getReferencedMessage());
248         } else {
249             samlResponse.setStatus(requestContext.getFailureStatus());
250         }
251
252         return samlResponse;
253     }
254
255     /**
256      * Constructs an artifact resolution response with an error status as content.
257      * 
258      * @param requestContext current request context
259      * 
260      * @return constructed response
261      */
262     protected ArtifactResponse buildArtifactErrorResponse(ArtifactResolutionRequestContext requestContext) {
263         ArtifactResponse samlResponse = responseBuilder.buildObject();
264         samlResponse.setIssueInstant(new DateTime());
265         populateStatusResponse(requestContext, samlResponse);
266
267         samlResponse.setStatus(requestContext.getFailureStatus());
268
269         return samlResponse;
270     }
271
272     /** Represents the internal state of a SAML 2.0 Artiface resolver request while it's being processed by the IdP. */
273     public class ArtifactResolutionRequestContext extends
274             BaseSAML2ProfileRequestContext<ArtifactResolve, ArtifactResponse, ArtifactResolutionConfiguration>
275             implements SAML2ArtifactMessageContext<ArtifactResolve, ArtifactResponse, NameID> {
276
277         /** Artifact to be resolved. */
278         private AbstractSAML2Artifact 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 AbstractSAML2Artifact 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(AbstractSAML2Artifact 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 }