Fixup artifact decoders
[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.Configuration;
22 import org.opensaml.common.SAMLObject;
23 import org.opensaml.common.SAMLObjectBuilder;
24 import org.opensaml.common.binding.BasicEndpointSelector;
25 import org.opensaml.common.binding.artifact.SAMLArtifactMap;
26 import org.opensaml.common.binding.artifact.SAMLArtifactMap.SAMLArtifactMapEntry;
27 import org.opensaml.common.binding.decoding.SAMLMessageDecoder;
28 import org.opensaml.common.xml.SAMLConstants;
29 import org.opensaml.saml2.binding.SAML2ArtifactMessageContext;
30 import org.opensaml.saml2.binding.artifact.AbstractSAML2Artifact;
31 import org.opensaml.saml2.binding.artifact.SAML2ArtifactBuilderFactory;
32 import org.opensaml.saml2.core.ArtifactResolve;
33 import org.opensaml.saml2.core.ArtifactResponse;
34 import org.opensaml.saml2.core.NameID;
35 import org.opensaml.saml2.core.Status;
36 import org.opensaml.saml2.core.StatusCode;
37 import org.opensaml.saml2.metadata.AssertionConsumerService;
38 import org.opensaml.saml2.metadata.AttributeAuthorityDescriptor;
39 import org.opensaml.saml2.metadata.Endpoint;
40 import org.opensaml.saml2.metadata.SPSSODescriptor;
41 import org.opensaml.saml2.metadata.provider.MetadataProvider;
42 import org.opensaml.saml2.metadata.provider.MetadataProviderException;
43 import org.opensaml.ws.message.decoder.MessageDecodingException;
44 import org.opensaml.ws.security.SecurityPolicyException;
45 import org.opensaml.ws.transport.http.HTTPInTransport;
46 import org.opensaml.ws.transport.http.HTTPOutTransport;
47 import org.opensaml.xml.util.Base64;
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.saml2.ArtifactResolutionConfiguration;
52
53 /**
54  * SAML 2.0 Artifact resolution profile handler.
55  */
56 public class ArtifactResolution extends AbstractSAML2ProfileHandler {
57
58     /** Class logger. */
59     private final Logger log = Logger.getLogger(ArtifactResolution.class);
60
61     /** Map artifacts to SAML messages. */
62     private SAMLArtifactMap artifactMap;
63
64     /** Artifact response object builder. */
65     private SAMLObjectBuilder<ArtifactResponse> responseBuilder;
66
67     /** Constructor. */
68     public ArtifactResolution() {
69         super();
70         responseBuilder = (SAMLObjectBuilder<ArtifactResponse>) getBuilderFactory().getBuilder(
71                 ArtifactResponse.DEFAULT_ELEMENT_NAME);
72     }
73
74     /** {@inheritDoc} */
75     public String getProfileId() {
76         return "urn:mace:shibboleth:2.0:idp:profiles:saml2:request:artifact";
77     }
78
79     /** {@inheritDoc} */
80     public void processRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport) throws ProfileException {
81         ArtifactResponse samlResponse;
82
83         ArtifactResolutionRequestContext requestContext = decodeRequest(inTransport, outTransport);
84
85         try {
86             if (requestContext.getRelyingPartyConfiguration() == null) {
87                 log.error("SAML 2 Artifact Resolve profile is not configured for relying party "
88                         + requestContext.getPeerEntityId());
89                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
90                         "SAML 2 Artifact Resolve profile is not configured for relying party "
91                                 + requestContext.getPeerEntityId()));
92                 throw new ProfileException("SAML 2 Artifact Resolve profile is not configured for relying party "
93                         + requestContext.getPeerEntityId());
94             }
95
96             checkSamlVersion(requestContext);
97
98             SAMLArtifactMapEntry artifactEntry = artifactMap.peek(requestContext.getArtifact().getArtifactBytes());
99             if (artifactEntry == null || artifactEntry.isExpired()) {
100                 log.error("Unknown artifact.");
101                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
102                         "Unknown artifact."));
103             }
104
105             if (!artifactEntry.getIssuerId().equals(requestContext.getLocalEntityId())) {
106                 log.error("Artifact issuer mismatch.  Artifact issued by " + artifactEntry.getIssuerId()
107                         + " but IdP has entity ID of " + requestContext.getLocalEntityId());
108                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
109                         "Artifact issuer mismatch."));
110             }
111
112             if (!artifactEntry.getRelyingPartyId().equals(requestContext.getPeerEntityId())) {
113                 log.error("Artifact requester mismatch.  Artifact was issued to " + artifactEntry.getRelyingPartyId()
114                         + " but was resolve request came from " + requestContext.getPeerEntityId());
115                 requestContext.setFailureStatus(buildStatus(StatusCode.SUCCESS_URI, StatusCode.REQUEST_DENIED_URI,
116                         "Artifact requester mismatch."));
117             }
118             artifactMap.get(requestContext.getArtifact().getArtifactBytes());
119             SAMLObject referencedMessage = artifactEntry.getSamlMessage();
120             requestContext.setReferencedMessage(referencedMessage);
121
122             // create the SAML response
123             samlResponse = buildArtifactResponse(requestContext);
124         } catch (ProfileException e) {
125             samlResponse = buildArtifactErrorResponse(requestContext);
126         }
127
128         requestContext.setOutboundSAMLMessage(samlResponse);
129         requestContext.setOutboundSAMLMessageId(samlResponse.getID());
130         requestContext.setOutboundSAMLMessageIssueInstant(samlResponse.getIssueInstant());
131
132         encodeResponse(requestContext);
133         writeAuditLogEntry(requestContext);
134     }
135
136     /**
137      * Decodes an incoming request and populates a created request context with the resultant information.
138      * 
139      * @param inTransport inbound message transport
140      * @param outTransport outbound message transport
141      * 
142      * @return the created request context
143      * 
144      * @throws ProfileException throw if there is a problem decoding the request
145      */
146     protected ArtifactResolutionRequestContext decodeRequest(HTTPInTransport inTransport, HTTPOutTransport outTransport)
147             throws ProfileException {
148         if (log.isDebugEnabled()) {
149             log.debug("Decoding incomming request");
150         }
151
152         MetadataProvider metadataProvider = getMetadataProvider();
153
154         ArtifactResolutionRequestContext requestContext = new ArtifactResolutionRequestContext();
155         requestContext.setInboundMessageTransport(inTransport);
156         requestContext.setInboundSAMLProtocol(SAMLConstants.SAML20P_NS);
157         requestContext.setOutboundMessageTransport(outTransport);
158         requestContext.setOutboundSAMLProtocol(SAMLConstants.SAML20P_NS);
159         requestContext.setMetadataProvider(metadataProvider);
160
161         try {
162             SAMLMessageDecoder decoder = getMessageDecoders().get(getInboundBinding());
163             requestContext.setMessageDecoder(decoder);
164             decoder.decode(requestContext);
165             if (log.isDebugEnabled()) {
166                 log.debug("Decoded request");
167             }
168             return requestContext;
169         } catch (MessageDecodingException e) {
170             log.error("Error decoding artifact resolve message", e);
171             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, null, "Error decoding message"));
172             throw new ProfileException("Error decoding artifact resolve message");
173         } catch (SecurityPolicyException e) {
174             log.error("Message did not meet security policy requirements", e);
175             requestContext.setFailureStatus(buildStatus(StatusCode.RESPONDER_URI, StatusCode.REQUEST_DENIED_URI,
176                     "Message did not meet security policy requirements"));
177             throw new ProfileException("Message did not meet security policy requirements", e);
178         } finally {
179             // Set as much information as can be retrieved from the decoded message
180             try {
181                 ArtifactResolve artResolve = requestContext.getInboundSAMLMessage();
182                 requestContext.setInboundSAMLMessageId(artResolve.getID());
183                 requestContext.setInboundSAMLMessageIssueInstant(artResolve.getIssueInstant());
184
185                 String relyingPartyId = requestContext.getPeerEntityId();
186                 requestContext.setPeerEntityMetadata(metadataProvider.getEntityDescriptor(relyingPartyId));
187                 requestContext.setPeerEntityRole(SPSSODescriptor.DEFAULT_ELEMENT_NAME);
188                 requestContext.setPeerEntityRoleMetadata(requestContext.getPeerEntityMetadata().getSPSSODescriptor(
189                         SAMLConstants.SAML20P_NS));
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 artifact artifact to be resolved
303          */
304         public void setArtifact(AbstractSAML2Artifact artifact) {
305             this.artifact = artifact;
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 }