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