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