Populate request context with relying party ID from artifact map entry
[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                 AbstractSAML1Artifact artifact = requestContext.getArtifacts().iterator().next();
167                 SAMLArtifactMapEntry artifactEntry = artifactMap.get(artifact.getArtifactBytes());
168                 String relyingPartyId = artifactEntry.getRelyingPartyId();
169
170                 requestContext.setInboundMessageIssuer(relyingPartyId);
171                 RelyingPartyConfiguration rpConfig = getRelyingPartyConfiguration(relyingPartyId);
172                 requestContext.setRelyingPartyConfiguration(rpConfig);
173
174                 String assertingPartyId = requestContext.getRelyingPartyConfiguration().getProviderId();
175                 requestContext.setLocalEntityId(assertingPartyId);
176                 requestContext.setLocalEntityMetadata(metadataProvider.getEntityDescriptor(assertingPartyId));
177                 requestContext.setLocalEntityRole(AttributeAuthorityDescriptor.DEFAULT_ELEMENT_NAME);
178                 requestContext.setLocalEntityRoleMetadata(requestContext.getLocalEntityMetadata()
179                         .getAttributeAuthorityDescriptor(SAMLConstants.SAML11P_NS));
180
181                 ArtifactResolutionConfiguration profileConfig = (ArtifactResolutionConfiguration) rpConfig
182                         .getProfileConfiguration(ArtifactResolutionConfiguration.PROFILE_ID);
183                 requestContext.setProfileConfiguration(profileConfig);
184                 if (profileConfig.getSigningCredential() != null) {
185                     requestContext.setOutboundSAMLMessageSigningCredential(profileConfig.getSigningCredential());
186                 } else if (rpConfig.getDefaultSigningCredential() != null) {
187                     requestContext.setOutboundSAMLMessageSigningCredential(rpConfig.getDefaultSigningCredential());
188                 }
189
190             } catch (MetadataProviderException e) {
191                 log.error("Unable to locate metadata for asserting or relying party");
192                 requestContext
193                         .setFailureStatus(buildStatus(StatusCode.RESPONDER, null, "Error locating party metadata"));
194                 throw new ProfileException("Error locating party metadata");
195             }
196         }
197     }
198
199     /**
200      * Selects the appropriate endpoint for the relying party and stores it in the request context.
201      * 
202      * @param requestContext current request context
203      * 
204      * @return Endpoint selected from the information provided in the request context
205      */
206     protected Endpoint selectEndpoint(ArtifactResolutionRequestContext requestContext) {
207         BasicEndpointSelector endpointSelector = new BasicEndpointSelector();
208         endpointSelector.setEndpointType(AssertionConsumerService.DEFAULT_ELEMENT_NAME);
209         endpointSelector.setMetadataProvider(getMetadataProvider());
210         endpointSelector.setEntityMetadata(requestContext.getPeerEntityMetadata());
211         endpointSelector.setEntityRoleMetadata(requestContext.getPeerEntityRoleMetadata());
212         endpointSelector.setSamlRequest(requestContext.getInboundSAMLMessage());
213         endpointSelector.getSupportedIssuerBindings().addAll(getSupportedOutboundBindings());
214         return endpointSelector.selectEndpoint();
215     }
216
217     /**
218      * Derferences the provided artifacts and stores them in the request context.
219      * 
220      * @param requestContext current request context
221      */
222     protected void derferenceArtifacts(ArtifactResolutionRequestContext requestContext) {
223         Collection<AbstractSAML1Artifact> artifacts = requestContext.getArtifacts();
224         if (artifacts != null) {
225             ArrayList<Assertion> assertions = new ArrayList<Assertion>();
226             SAMLArtifactMapEntry artifactEntry;
227
228             for (AbstractSAML1Artifact artifact : artifacts) {
229                 artifactEntry = artifactMap.get(artifact.getArtifactBytes());
230                 if (artifactEntry == null || artifactEntry.isExpired()) {
231                     log.error("Unknown artifact.");
232                 }
233
234                 if (!artifactEntry.getIssuerId().equals(requestContext.getLocalEntityId())) {
235                     log.error("Artifact issuer mismatch.  Artifact issued by " + artifactEntry.getIssuerId()
236                             + " but IdP has entity ID of " + requestContext.getLocalEntityId());
237                 }
238
239                 if (!artifactEntry.getRelyingPartyId().equals(requestContext.getInboundMessageIssuer())) {
240                     log.error("Artifact requester mismatch.  Artifact was issued to "
241                             + artifactEntry.getRelyingPartyId() + " but was resolve request came from "
242                             + requestContext.getInboundMessageIssuer());
243                 }
244                 artifactMap.remove(artifact.getArtifactBytes());
245                 assertions.add((Assertion) artifactEntry.getSamlMessage());
246             }
247             requestContext.setReferencedAssertions(assertions);
248         }
249     }
250
251     /**
252      * Builds the response to the artifact request.
253      * 
254      * @param requestContext current request context
255      * 
256      * @return response to the artifact request
257      */
258     protected Response buildArtifactResponse(ArtifactResolutionRequestContext requestContext) {
259         DateTime issueInstant = new DateTime();
260
261         // create the SAML response and add the assertion
262         Response samlResponse = responseBuilder.buildObject();
263         samlResponse.setIssueInstant(issueInstant);
264         populateStatusResponse(requestContext, samlResponse);
265
266         if (requestContext.getReferencedAssertions() != null) {
267             samlResponse.getAssertions().addAll(requestContext.getReferencedAssertions());
268         }
269
270         Status status = buildStatus(StatusCode.SUCCESS, null, null);
271         samlResponse.setStatus(status);
272
273         return samlResponse;
274     }
275
276     /** Represents the internal state of a SAML 1 Artiface resolver request while it's being processed by the IdP. */
277     public class ArtifactResolutionRequestContext extends
278             BaseSAML1ProfileRequestContext<Request, Response, ArtifactResolutionConfiguration> implements
279             SAML1ArtifactMessageContext<Request, Response, NameIdentifier> {
280
281         /** Artifact to be resolved. */
282         private Collection<AbstractSAML1Artifact> artifacts;
283
284         /** Message referenced by the SAML artifact. */
285         private Collection<Assertion> referencedAssertions;
286
287         /**
288          * Gets the artifacts to be resolved.
289          * 
290          * @return artifacts to be resolved
291          */
292         public Collection<AbstractSAML1Artifact> getArtifacts() {
293             return artifacts;
294         }
295
296         /**
297          * Sets the artifacts to be resolved.
298          * 
299          * @param artifacts artifacts to be resolved
300          */
301         public void setArtifacts(Collection<AbstractSAML1Artifact> artifacts) {
302             this.artifacts = artifacts;
303         }
304
305         /**
306          * Gets the SAML assertions referenced by the artifact(s).
307          * 
308          * @return SAML assertions referenced by the artifact(s)
309          */
310         public Collection<Assertion> getReferencedAssertions() {
311             return referencedAssertions;
312         }
313
314         /**
315          * Sets the SAML assertions referenced by the artifact(s).
316          * 
317          * @param assertions SAML assertions referenced by the artifact(s)
318          */
319         public void setReferencedAssertions(Collection<Assertion> assertions) {
320             referencedAssertions = assertions;
321         }
322     }
323 }