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