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