View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.myfaces.tobago.internal.util;
21  
22  import org.apache.myfaces.tobago.context.TobagoContext;
23  import org.apache.myfaces.tobago.context.UserAgent;
24  import org.apache.myfaces.tobago.internal.config.ContentSecurityPolicy;
25  import org.apache.myfaces.tobago.internal.context.Nonce;
26  import org.apache.myfaces.tobago.portlet.PortletUtils;
27  import org.slf4j.Logger;
28  import org.slf4j.LoggerFactory;
29  
30  import javax.faces.context.FacesContext;
31  import javax.portlet.MimeResponse;
32  import javax.servlet.http.HttpServletResponse;
33  import java.util.Map;
34  
35  public final class ResponseUtils {
36  
37    private static final Logger LOG = LoggerFactory.getLogger(ResponseUtils.class);
38  
39    private ResponseUtils() {
40      // utils class
41    }
42  
43    public static void ensureNoCacheHeader(final FacesContext facesContext) {
44      final Object response = facesContext.getExternalContext().getResponse();
45      if (response instanceof HttpServletResponse) {
46        ensureNoCacheHeader((HttpServletResponse) response);
47      } else if (PortletUtils.isPortletApiAvailable() && response instanceof MimeResponse) {
48        ensureNoCacheHeader((MimeResponse) response);
49      }
50    }
51  
52    public static void ensureNoCacheHeader(final HttpServletResponse response) {
53      response.setHeader("Cache-Control", "no-cache,no-store,max-age=0,must-revalidate");
54      response.setHeader("Pragma", "no-cache");
55      response.setDateHeader("Expires", 0);
56      response.setDateHeader("max-age", 0);
57    }
58  
59    public static void ensureNoCacheHeader(final MimeResponse response) {
60      // TODO validate this
61      response.getCacheControl().setExpirationTime(0);
62    }
63  
64    public static void ensureContentTypeHeader(final FacesContext facesContext, final String contentType) {
65      final Object response = facesContext.getExternalContext().getResponse();
66      if (response instanceof HttpServletResponse) {
67        ensureContentTypeHeader((HttpServletResponse) response, contentType);
68      } else if (PortletUtils.isPortletApiAvailable() && response instanceof MimeResponse) {
69        ensureContentTypeHeader((MimeResponse) response, contentType);
70      }
71    }
72  
73    public static void ensureContentTypeHeader(final HttpServletResponse response, final String contentType) {
74      if (!response.containsHeader("Content-Type")) {
75        response.setContentType(contentType);
76      } else {
77        final String responseContentType = response.getContentType();
78        if (!StringUtils.equalsIgnoreCaseAndWhitespace(responseContentType, contentType)) {
79          response.setContentType(contentType);
80          if (LOG.isDebugEnabled()) {
81            LOG.debug("Response already contains Header Content-Type '" + responseContentType
82                + "'. Overwriting with '" + contentType + "'");
83          }
84        }
85      }
86    }
87  
88    public static void ensureContentTypeHeader(final MimeResponse response, final String contentType) {
89      final String responseContentType = response.getContentType();
90      if (!StringUtils.equalsIgnoreCaseAndWhitespace(responseContentType, contentType)) {
91        response.setContentType(contentType);
92        if (LOG.isDebugEnabled()) {
93          LOG.debug("Response already contains Header Content-Type '" + responseContentType
94              + "'. Overwriting with '" + contentType + "'");
95        }
96      }
97    }
98  
99    public static void ensureContentSecurityPolicyHeader(
100       final FacesContext facesContext, final ContentSecurityPolicy contentSecurityPolicy) {
101     final Object response = facesContext.getExternalContext().getResponse();
102     if (response instanceof HttpServletResponse) {
103       final HttpServletResponse servletResponse = (HttpServletResponse) response;
104       final TobagoContext tobagoContext = TobagoContext.getInstance(facesContext);
105       final UserAgent userAgent = tobagoContext.getUserAgent();
106       final String[] cspHeaders;
107       switch (contentSecurityPolicy.getMode()) {
108         case OFF:
109           cspHeaders = new String[0];
110           break;
111         case ON:
112           cspHeaders = userAgent.getCspHeaders();
113           break;
114         case REPORT_ONLY:
115           cspHeaders = userAgent.getCspReportOnlyHeaders();
116           break;
117         default:
118           throw new IllegalArgumentException("Undefined mode: " + contentSecurityPolicy.getMode());
119       }
120       final StringBuilder builder = new StringBuilder();
121       final String nonce = Nonce.getNonce(facesContext);
122       for (final Map.Entry<String, String> directive : contentSecurityPolicy.getDirectiveMap().entrySet()) {
123         builder.append(directive.getKey());
124         builder.append(" ");
125         builder.append(directive.getValue().replace("${nonce}", nonce));
126         builder.append(";");
127       }
128       for (final String cspHeader : cspHeaders) {
129         servletResponse.setHeader(cspHeader, builder.toString());
130       }
131     } else if (PortletUtils.isPortletApiAvailable() && response instanceof MimeResponse) {
132      // TODO Portlet
133       if (contentSecurityPolicy.getMode() != ContentSecurityPolicy.Mode.OFF) {
134         LOG.warn("CSP not implemented for Portlet!");
135       }
136     }
137   }
138 
139   public static void ensureNosniffHeader(final FacesContext facesContext) {
140     final Object response = facesContext.getExternalContext().getResponse();
141     if (response instanceof HttpServletResponse) {
142       final HttpServletResponse servletResponse = (HttpServletResponse) response;
143       ensureNosniffHeader(servletResponse);
144     }
145   }
146 
147   public static void ensureNosniffHeader(final HttpServletResponse servletResponse) {
148     servletResponse.setHeader("X-Content-Type-Options", "nosniff");
149   }
150 }