Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WW-5203] Re-builds policy string on each call #588

Merged
merged 1 commit into from
Aug 11, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,16 +18,15 @@
*/
package org.apache.struts2.interceptor.csp;

import static java.lang.String.format;

import com.opensymphony.xwork2.ActionContext;

import java.util.function.Supplier;
import javax.servlet.http.HttpServletResponse;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Map;
import java.util.function.Supplier;

import static java.lang.String.format;

/**
* Default implementation of {@link CspSettings}.
Expand All @@ -37,36 +36,30 @@
* @see CspInterceptor
*/
public class DefaultCspSettings implements CspSettings {
private final SecureRandom sRand = new SecureRandom();
// this lazy supplier computes a policy format the first time it's called and caches the result
// to reduce string operations when attaching policies to HTTP responses
private final Supplier<String> lazyPolicyBuilder = new Supplier<String>() {
boolean hasBeenCalled;
String policyFormat;

private final SecureRandom sRand = new SecureRandom();

// this supplier computes a policy format
private final Supplier<String> lazyPolicyBuilder = new Supplier<String>() {
@Override
public String get() {
if (!hasBeenCalled) {
StringBuilder policyFormatBuilder = new StringBuilder()
.append(OBJECT_SRC)
.append(format(" '%s'; ", NONE))
.append(SCRIPT_SRC)
.append(" 'nonce-%s' ") // nonce placeholder
.append(format("'%s' ", STRICT_DYNAMIC))
.append(format("%s %s; ", HTTP, HTTPS))
.append(BASE_URI)
.append(format(" '%s'; ", NONE));

if (reportUri != null) {
policyFormatBuilder
.append(REPORT_URI)
.append(format(" %s", reportUri));
}

policyFormat = policyFormatBuilder.toString();
StringBuilder policyFormatBuilder = new StringBuilder()
.append(OBJECT_SRC)
.append(format(" '%s'; ", NONE))
.append(SCRIPT_SRC)
.append(" 'nonce-%s' ") // nonce placeholder
.append(format("'%s' ", STRICT_DYNAMIC))
.append(format("%s %s; ", HTTP, HTTPS))
.append(BASE_URI)
.append(format(" '%s'; ", NONE));

if (reportUri != null) {
policyFormatBuilder
.append(REPORT_URI)
.append(format(" %s", reportUri));
}

return format(policyFormat, getNonceString());
return format(policyFormatBuilder.toString(), getNonceString());
}
};

Expand Down