99d5f6f4b16d654a2458afb9a740e68258943dde
[java-idp.git] / src / edu / internet2 / middleware / shibboleth / idp / profile / saml1 / 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.saml1;
18
19 import java.util.ArrayList;
20 import java.util.Collection;
21
22 import org.apache.log4j.Logger;
23 import org.joda.time.DateTime;
24 import org.opensaml.common.SAMLObjectBuilder;
25 import org.opensaml.common.binding.BasicEndpointSelector;
26 import org.opensaml.common.binding.artifact.SAMLArtifactMap;
27 import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry;
28 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
29 import org.opensaml.common.xml.SAMLConstants;
30 import org.opensaml.saml1.binding.SAML1ArtifactMessageContext;
31 import org.opensaml.saml1.binding.artifact.AbstractSAML1Artifact;
32 import org.opensaml.saml1.core.Assertion;
33 import org.opensaml.saml1.core.NameIdentifier;
34 import org.opensaml.saml1.core.Request;
35 import org.opensaml.saml1.core.Response;
36 import org.opensaml.saml1.core.Status;
37 import org.opensaml.saml1.core.StatusCode;
38 import org.opensaml.saml2.metadata.AssertionConsumerService;
39 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
40 import org.opensaml.saml2.metadata.Endpoint;
41 import org.opensaml.saml2.metadata.SPSSODescriptor;
42 import org.opensaml.saml2.metadata.provider.MetadataProvider;
43 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
44 import org.opensaml.ws.message.decoder.MessageDecodingException;
45 import org.opensaml.ws.security.SecurityPolicyException;
46 import org.opensaml.ws.transport.http.HTTPInTransport;
47 import org.opensaml.ws.transport.http.HTTPOutTransport;
48
49 import edu.internet2.middleware.shibboleth.common.profile.ProfileException;
50 import edu.internet2.middleware.shibboleth.common.relyingparty.RelyingPartyConfiguration;
51 import edu.internet2.middleware.shibboleth.common.relyingparty.provider.saml1.ArtifactResolutionConfiguration;
52
53 /**
54  * SAML 1 Artifact resolution profile handler.
55  */
56 public class ArtifactResolution extends AbstractSAML1ProfileHandler {
57
58     /** Class logger. */
59     private final Logger log = Logger.getLogger(ArtifactResolution.class);
60
61     /** Builder of Response objects. */
62     private SAMLObjectBuilder<Response> responseBuilder;
63
64     /** Map artifacts to SAML messages. */
65     private SAMLArtifactMap artifactMap;
66
67     /**
68      * Constructor.
69      * 
70      * @param map ArtifactMap used to lookup artifacts to be resolved.
71      */
72     public ArtifactResolution(SAMLArtifactMap map) {
73         super();
74
75         artifactMap = map;
76
77         responseBuilder = (SAMLObjectBuilder<Response>) getBuilderFactory().getBuilder(Response.DEFAULT_ELEMENT_NAME);
78     }
79
80     /** {@inheritDoc} */
81     public String getProfileId() {
82         return "urn:mace:shibboleth:2.0:idp:profiles:saml1:request:artifact";
83     }
84
85     /** {@inheritDoc} */
86     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
87         Response samlResponse;
88
89         ArtifactResolutionRequestContext requestContext = decodeRequest(inTransport, outTransport);
90
91         try {
92             if (requestContext.getRelyingPartyConfiguration() == null) {
93                 log.error("SAML 1 Artifact resolution profile is not configured for relying party "
94                         + requestContext.getInboundMessageIssuer());
95                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS, StatusCode.REQUEST_DENIED,
96                         "SAML 1 Artifact resolution profile is not configured for relying party "
97                                 + requestContext.getInboundMessageIssuer()));
98                 throw new ProfileException("SAML 1 Artifact resolution profile is not configured for relying party "
99                         + requestContext.getInboundMessageIssuer());
100             }
101
102             checkSamlVersion(requestContext);
103
104             // create the SAML response
105             samlResponse = buildArtifactResponse(requestContext);
106         } catch (ProfileException e) {
107             samlResponse = buildErrorResponse(requestContext);
108         }
109
110         requestContext.setOutboundSAMLMessage(samlResponse);
111         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
112         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
113
114         encodeResponse(requestContext);
115         writeAuditLogEntry(requestContext);
116     }
117
118     /**
119      * Decodes an incoming request and populates a created request context with the resultant information.
120      * 
121      * @param inTransport inbound message transport
122      * @param outTransport outbound message transport
123      * 
124      * @return the created request context
125      * 
126      * @throws ProfileException throw if there is a problem decoding the request
127      */
128     protected ArtifactResolutionRequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
129             throws ProfileException {
130         if (log.isDebugEnabled()) {
131             log.debug("Decoding incomming request");
132         }
133
134         MetadataProvider metadataProvider = getMetadataProvider();
135
136         ArtifactResolutionRequestContext requestContext = new ArtifactResolutionRequestContext();
137         requestContext.setMetadataProvider(metadataProvider);
138
139         requestContext.setInboundMessageTransport(inTransport);
140         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML11P_NS);
141         requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
142
143         requestContext.setOutboundMessageTransport(outTransport);
144         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML11P_NS);
145
146         try {
147             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
148             requestContext.setMessageDecoder(decoder);
149             decoder.decode(requestContext);
150             if (log.isDebugEnabled()) {
151                 log.debug("Decoded request");
152             }
153             return requestContext;
154         } catch (MessageDecodingException e) {
155             log.error("Error decoding artifact resolve message", e);
156             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error decoding message"));
157             throw new ProfileException("Error decoding artifact resolve message");
158         } catch (SecurityPolicyException e) {
159             log.error("Message did not meet security policy requirements", e);
160             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER, StatusCode.REQUEST_DENIED,
161                     "Message did not meet security policy requirements"));
162             throw new ProfileException("Message did not meet security policy requirements", e);
163         } finally {
164             // Set as much information as can be retrieved from the decoded message
165             try {
166                 String relyingPartyId = requestContext.getInboundMessageIssuer();
167                 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
168                 requestContext.setRelyingPartyConfiguration(rpConfig);
169
170                 String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
171                 requestContext.setLocalEntityId(assertingPartyId);
172                 requestContext.setLocalEntityMetadata(metadataProvider.getEntityDescriptor(assertingPartyId));
173                 requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
174                 requestContext.setLocalEntityRoleMetadata(requestContext.getLocalEntityMetadata()
175                         .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
176
177                 ArtifactResolutionConfiguration profileConfig = (ArtifactResolutionConfiguration) rpConfig
178                         .getProfileConfiguration(ArtifactResolutionConfiguration.PROFILE_ID);
179                 requestContext.setProfileConfiguration(profileConfig);
180                 if (profileConfig.getSigningCredential() != null) {
181                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
182                 } else if (rpConfig.getDefaultSigningCredential() != null) {
183                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
184                 }
185
186             } catch (MetadataProviderException e) {
187                 log.error("Unable to locate metadata for asserting or relying party");
188                 requestContext
189                         .setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
190                 throw new ProfileException("Error locating party metadata");
191             }
192         }
193     }
194
195     /**
196      * Selects the appropriate endpoint for the relying party and stores it in the request context.
197      * 
198      * @param requestContext current request context
199      * 
200      * @return Endpoint selected from the information provided in the request context
201      */
202     protected Endpoint selectEndpoint(ArtifactResolutionRequestContext requestContext) {
203         BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
204         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
205         endpointSelector.setMetadataProvider(getMetadataProvider());
206         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
207         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
208         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
209         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
210         return endpointSelector.selectEndpoint();
211     }
212
213     /**
214      * Derferences the provided artifacts and stores them in the request context.
215      * 
216      * @param requestContext current request context
217      */
218     protected void derferenceArtifacts(ArtifactResolutionRequestContext requestContext) {
219         Collection<AbstractSAML1Artifact> artifacts = requestContext.getArtifacts();
220         if (artifacts != null) {
221             ArrayList<Assertion> assertions = new ArrayList<Assertion>();
222             SAMLArtifactMapEntry artifactEntry;
223
224             for (AbstractSAML1Artifact artifact : artifacts) {
225                 artifactEntry = artifactMap.get(artifact.getArtifactBytes());
226                 if (artifactEntry == null || artifactEntry.isExpired()) {
227                     log.error("Unknown artifact.");
228                 }
229
230                 if (!artifactEntry.getIssuerId().equals(requestContext.getLocalEntityId())) {
231                     log.error("Artifact issuer mismatch.  Artifact issued by " + artifactEntry.getIssuerId()
232                             + " but IdP has entity ID of " + requestContext.getLocalEntityId());
233                 }
234
235                 if (!artifactEntry.getRelyingPartyId().equals(requestContext.getInboundMessageIssuer())) {
236                     log.error("Artifact requester mismatch.  Artifact was issued to "
237                             + artifactEntry.getRelyingPartyId() + " but was resolve request came from "
238                             + requestContext.getInboundMessageIssuer());
239                 }
240                 artifactMap.remove(artifact.getArtifactBytes());
241                 assertions.add((Assertion) artifactEntry.getSamlMessage());
242             }
243             requestContext.setReferencedAssertions(assertions);
244         }
245     }
246
247     /**
248      * Builds the response to the artifact request.
249      * 
250      * @param requestContext current request context
251      * 
252      * @return response to the artifact request
253      */
254     protected Response buildArtifactResponse(ArtifactResolutionRequestContext requestContext) {
255         DateTime issueInstant = new DateTime();
256
257         // create the SAML response and add the assertion
258         Response samlResponse = responseBuilder.buildObject();
259         samlResponse.setIssueInstant(issueInstant);
260         populateStatusResponse(requestContext, samlResponse);
261
262         if (requestContext.getReferencedAssertions() != null) {
263             samlResponse.getAssertions().addAll(requestContext.getReferencedAssertions());
264         }
265
266         Status status = buildStatus(StatusCode.SUCCESS, null, null);
267         samlResponse.setStatus(status);
268
269         return samlResponse;
270     }
271
272     /** Represents the internal state of a SAML 1 Artiface resolver request while it's being processed by the IdP. */
273     public class ArtifactResolutionRequestContext extends
274             BaseSAML1ProfileRequestContext<Request, Response, ArtifactResolutionConfiguration> implements
275             SAML1ArtifactMessageContext<Request, Response, NameIdentifier> {
276
277         /** Artifact to be resolved. */
278         private Collection<AbstractSAML1Artifact> artifacts;
279
280         /** Message referenced by the SAML artifact. */
281         private Collection<Assertion> referencedAssertions;
282
283         /**
284          * Gets the artifacts to be resolved.
285          * 
286          * @return artifacts to be resolved
287          */
288         public Collection<AbstractSAML1Artifact> getArtifacts() {
289             return artifacts;
290         }
291
292         /**
293          * Sets the artifacts to be resolved.
294          * 
295          * @param artifacts artifacts to be resolved
296          */
297         public void setArtifacts(Collection<AbstractSAML1Artifact> artifacts) {
298             this.artifacts = artifacts;
299         }
300
301         /**
302          * Gets the SAML assertions referenced by the artifact(s).
303          * 
304          * @return SAML assertions referenced by the artifact(s)
305          */
306         public Collection<Assertion> getReferencedAssertions() {
307             return referencedAssertions;
308         }
309
310         /**
311          * Sets the SAML assertions referenced by the artifact(s).
312          * 
313          * @param assertions SAML assertions referenced by the artifact(s)
314          */
315         public void setReferencedAssertions(Collection<Assertion> assertions) {
316             referencedAssertions = assertions;
317         }
318     }
319 }