Skip to content

Commit

Permalink
Enable content security policy by default (javamelody#1031)
Browse files Browse the repository at this point in the history
  • Loading branch information
evernat authored and elnggng committed Mar 17, 2022
1 parent 4fc5efe commit 8a7481b
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 0 deletions.
Expand Up @@ -211,6 +211,11 @@ public enum Parameter {
*/
X_FRAME_OPTIONS("x-frame-options"),

/**
* Parameter to enable or disable the Content Security Policy header (true by default).
*/
CONTENT_SECURITY_POLICY_ENABLED("content-security-policy-enabled"),

/**
* Expression régulière (null par défaut) pour restreindre l'accès au monitoring à certaines adresses IP.
*/
Expand Down
Expand Up @@ -65,6 +65,8 @@
*/
public class HtmlController {
static final String HTML_BODY_FORMAT = "htmlbody";
private static final boolean CONTENT_SECURITY_POLICY_ENABLED = Parameter.CONTENT_SECURITY_POLICY_ENABLED
.getValue() == null || Parameter.CONTENT_SECURITY_POLICY_ENABLED.getValueAsBoolean();
private static final String X_FRAME_OPTIONS = Parameter.X_FRAME_OPTIONS.getValue();
private static final RequestToMethodMapper<HtmlController> REQUEST_TO_METHOD_MAPPER = new RequestToMethodMapper<>(
HtmlController.class);
Expand Down Expand Up @@ -120,6 +122,14 @@ static boolean isLocalCollectNeeded(String part) {

public static BufferedWriter getWriter(HttpServletResponse httpResponse) throws IOException {
httpResponse.setContentType("text/html; charset=UTF-8");
if (CONTENT_SECURITY_POLICY_ENABLED) {
final String analyticsId = Parameter.ANALYTICS_ID.getValue();
final boolean analyticsEnabled = analyticsId != null && !"disabled".equals(analyticsId);
httpResponse.setHeader("Content-Security-Policy",
"default-src 'self'"
+ (analyticsEnabled ? " https://ssl.google-analytics.com" : "")
+ "; object-src 'none';");
}
if (X_FRAME_OPTIONS == null) {
// default value of X-Frame-Options is SAMEORIGIN
httpResponse.setHeader("X-Frame-Options", "SAMEORIGIN");
Expand Down

0 comments on commit 8a7481b

Please sign in to comment.