You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by an...@apache.org on 2022/02/03 14:41:39 UTC
[sling-org-apache-sling-security] 01/01: SLING-11117 : Inconsistent formatting and minor improvements
This is an automated email from the ASF dual-hosted git repository.
angela pushed a commit to branch SLING-11117
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-security.git
commit fe2e3d82d3c31318154cddbc700aad837c97d01e
Author: angela <an...@adobe.com>
AuthorDate: Thu Feb 3 15:40:49 2022 +0100
SLING-11117 : Inconsistent formatting and minor improvements
---
.../security/impl/ContentDispositionFilter.java | 61 ++++-----
.../apache/sling/security/impl/ReferrerFilter.java | 138 +++++++++++----------
2 files changed, 104 insertions(+), 95 deletions(-)
diff --git a/src/main/java/org/apache/sling/security/impl/ContentDispositionFilter.java b/src/main/java/org/apache/sling/security/impl/ContentDispositionFilter.java
index 4962495..f00302d 100644
--- a/src/main/java/org/apache/sling/security/impl/ContentDispositionFilter.java
+++ b/src/main/java/org/apache/sling/security/impl/ContentDispositionFilter.java
@@ -44,11 +44,13 @@ import org.osgi.service.metatype.annotations.Designate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-@Component(property={"sling.filter.scope=request", "sling.filter.scope=forward", "service.ranking:Integer=25000"})
-@Designate(ocd=ContentDispositionFilterConfiguration.class)
+@Component(property = {"sling.filter.scope=request", "sling.filter.scope=forward", "service.ranking:Integer=25000"})
+@Designate(ocd = ContentDispositionFilterConfiguration.class)
public class ContentDispositionFilter implements Filter {
- /** Logger. */
+ /**
+ * Logger.
+ */
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private static final List<String> supportedMethods = Arrays.asList("GET", "HEAD");
@@ -72,9 +74,9 @@ public class ContentDispositionFilter implements Filter {
@Activate
private void activate(ContentDispositionFilterConfiguration configuration) {
- Set<String> paths = new HashSet<String>();
- List<String> pfxs = new ArrayList<String>();
- Map<String, Set<String>> contentTypesMap = new HashMap<String, Set<String>>();
+ Set<String> paths = new HashSet<>();
+ List<String> pfxs = new ArrayList<>();
+ Map<String, Set<String>> contentTypesMap = new HashMap<>();
// check for null till we upgrade to DS 1.4 (https://osgi.org/bugzilla/show_bug.cgi?id=208)
if (configuration.sling_content_disposition_paths() != null) {
@@ -107,7 +109,7 @@ public class ContentDispositionFilter implements Filter {
paths.add(p);
}
if (colonIdx != -1 && p != null) {
- Set <String> contentTypes = getContentTypes(path.substring(colonIdx+1));
+ Set<String> contentTypes = getContentTypes(path.substring(colonIdx + 1));
contentTypesMap.put(p, contentTypes);
}
}
@@ -115,25 +117,24 @@ public class ContentDispositionFilter implements Filter {
}
}
}
- contentDispositionPaths = paths.isEmpty() ? Collections.<String>emptySet() : paths;
- contentDispositionPathsPfx = pfxs.toArray(new String[pfxs.size()]);
- contentTypesMapping = contentTypesMap.isEmpty()?Collections.<String, Set<String>>emptyMap(): contentTypesMap;
+ contentDispositionPaths = paths.isEmpty() ? Collections.emptySet() : paths;
+ contentDispositionPathsPfx = pfxs.toArray(new String[0]);
+ contentTypesMapping = contentTypesMap.isEmpty() ? Collections.emptyMap() : contentTypesMap;
- enableContentDispositionAllPaths = configuration.sling_content_disposition_all_paths();
+ enableContentDispositionAllPaths = configuration.sling_content_disposition_all_paths();
String[] contentDispositionExcludedPathsArray = configuration.sling_content_disposition_excluded_paths() != null ? configuration.sling_content_disposition_excluded_paths() : new String[]{};
- contentDispositionExcludedPaths = new HashSet<String>(Arrays.asList(contentDispositionExcludedPathsArray));
+ contentDispositionExcludedPaths = new HashSet<>(Arrays.asList(contentDispositionExcludedPathsArray));
- logger.info("Initialized. content disposition paths: {}, content disposition paths-pfx {}, content disposition excluded paths: {}. Enable Content Disposition for all paths is set to {}", new Object[]{
- contentDispositionPaths, contentDispositionPathsPfx, contentDispositionExcludedPaths, enableContentDispositionAllPaths}
- );
+ logger.info("Initialized. content disposition paths: {}, content disposition paths-pfx {}, content disposition excluded paths: {}. Enable Content Disposition for all paths is set to {}",
+ contentDispositionPaths, contentDispositionPathsPfx, contentDispositionExcludedPaths, enableContentDispositionAllPaths);
}
@Override
- public void init(FilterConfig filterConfig) throws ServletException {
+ public void init(FilterConfig filterConfig) {
// nothing to do
}
@@ -144,7 +145,7 @@ public class ContentDispositionFilter implements Filter {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
- FilterChain chain) throws IOException, ServletException {
+ FilterChain chain) throws IOException, ServletException {
final SlingHttpServletRequest slingRequest = (SlingHttpServletRequest) request;
final SlingHttpServletResponse slingResponse = (SlingHttpServletResponse) response;
@@ -157,12 +158,10 @@ public class ContentDispositionFilter implements Filter {
//---------- PRIVATE METHODS ---------
private static Set<String> getContentTypes(String contentTypes) {
- Set<String> contentTypesSet = new HashSet<String>();
+ Set<String> contentTypesSet = new HashSet<>();
if (contentTypes != null && contentTypes.length() > 0) {
String[] contentTypesArray = contentTypes.split(",");
- for (String contentType : contentTypesArray) {
- contentTypesSet.add(contentType);
- }
+ Collections.addAll(contentTypesSet, contentTypesArray);
}
return contentTypesSet;
}
@@ -182,7 +181,9 @@ public class ContentDispositionFilter implements Filter {
static final String ATTRIBUTE_NAME =
"org.apache.sling.security.impl.ContentDispositionFilter.RewriterResponse.contentType";
- /** The current request. */
+ /**
+ * The current request.
+ */
private final SlingHttpServletRequest request;
private final Resource resource;
@@ -226,7 +227,7 @@ public class ContentDispositionFilter implements Filter {
if (contentDispositionPaths.contains(resourcePath)) {
if (contentTypesMapping.containsKey(resourcePath)) {
- Set <String> exceptions = contentTypesMapping.get(resourcePath);
+ Set<String> exceptions = contentTypesMapping.get(resourcePath);
if (!exceptions.contains(type)) {
contentDispositionAdded = setContentDisposition(resource);
}
@@ -238,7 +239,7 @@ public class ContentDispositionFilter implements Filter {
for (String path : contentDispositionPathsPfx) {
if (resourcePath.startsWith(path)) {
if (contentTypesMapping.containsKey(path)) {
- Set <String> exceptions = contentTypesMapping.get(path);
+ Set<String> exceptions = contentTypesMapping.get(path);
if (!exceptions.contains(type)) {
setContentDisposition(resource);
break;
@@ -257,7 +258,7 @@ public class ContentDispositionFilter implements Filter {
super.setContentType(type);
}
- //---------- PRIVATE METHODS ---------
+ //---------- PRIVATE METHODS ---------
private boolean setContentDisposition(Resource resource) {
boolean contentDispositionAdded = false;
@@ -268,17 +269,17 @@ public class ContentDispositionFilter implements Filter {
return contentDispositionAdded;
}
- private boolean isJcrData(Resource resource){
+ private boolean isJcrData(Resource resource) {
boolean jcrData = false;
- if (resource!= null) {
+ if (resource != null) {
ValueMap props = resource.adaptTo(ValueMap.class);
- if (props != null && props.containsKey(PROP_JCR_DATA) ) {
+ if (props != null && props.containsKey(PROP_JCR_DATA)) {
jcrData = true;
} else {
Resource jcrContent = resource.getChild(JCR_CONTENT_LEAF);
- if (jcrContent!= null) {
+ if (jcrContent != null) {
props = jcrContent.adaptTo(ValueMap.class);
- if (props != null && props.containsKey(PROP_JCR_DATA) ) {
+ if (props != null && props.containsKey(PROP_JCR_DATA)) {
jcrData = true;
}
}
diff --git a/src/main/java/org/apache/sling/security/impl/ReferrerFilter.java b/src/main/java/org/apache/sling/security/impl/ReferrerFilter.java
index 1ca775f..0aa4099 100644
--- a/src/main/java/org/apache/sling/security/impl/ReferrerFilter.java
+++ b/src/main/java/org/apache/sling/security/impl/ReferrerFilter.java
@@ -41,6 +41,7 @@ import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import org.osgi.framework.BundleContext;
import org.osgi.framework.Constants;
import org.osgi.framework.ServiceRegistration;
@@ -62,7 +63,7 @@ import org.slf4j.LoggerFactory;
}
)
@Designate(ocd = ReferrerFilter.Config.class)
-public class ReferrerFilter implements Preprocessor {
+public class ReferrerFilter implements Preprocessor {
/**
* Request header providing the clients user agent information used
@@ -154,16 +155,24 @@ public class ReferrerFilter implements Preprocessor {
*/
private boolean allowEmpty;
- /** Allowed uri referrers */
+ /**
+ * Allowed uri referrers
+ */
private URL[] allowedUriReferrers;
- /** Allowed regexp referrers */
+ /**
+ * Allowed regexp referrers
+ */
private Pattern[] allowedRegexReferrers;
- /** Methods to be filtered. */
+ /**
+ * Methods to be filtered.
+ */
private String[] filterMethods;
- /** Paths to be excluded */
+ /**
+ * Paths to be excluded
+ */
private Pattern[] excludedRegexUserAgents;
private ServiceRegistration<Object> configPrinterRegistration;
@@ -176,24 +185,24 @@ public class ReferrerFilter implements Preprocessor {
try {
final Enumeration<NetworkInterface> ifaces = NetworkInterface.getNetworkInterfaces();
- while(ifaces.hasMoreElements()){
+ while (ifaces.hasMoreElements()) {
final NetworkInterface iface = ifaces.nextElement();
- logger.info("Adding Allowed referers for Interface:" + iface.getDisplayName());
+ logger.info("Adding Allowed referers for Interface: {}", iface.getDisplayName());
final Enumeration<InetAddress> ias = iface.getInetAddresses();
- while(ias.hasMoreElements()){
+ while (ias.hasMoreElements()) {
final InetAddress ia = ias.nextElement();
final String address = ia.getHostAddress().trim().toLowerCase();
- if ( ia instanceof Inet4Address ) {
+ if (ia instanceof Inet4Address) {
referrers.add("http://" + address + ":0");
referrers.add("https://" + address + ":0");
}
- if ( ia instanceof Inet6Address ) {
+ if (ia instanceof Inet6Address) {
referrers.add("http://[" + address + "]" + ":0");
referrers.add("https://[" + address + "]" + ":0");
}
}
}
- } catch ( final SocketException se) {
+ } catch (final SocketException se) {
logger.error("Unable to detect network interfaces", se);
}
referrers.add("http://localhost" + ":0");
@@ -208,10 +217,10 @@ public class ReferrerFilter implements Preprocessor {
private void add(final List<URL> urls, final String ref) {
try {
- final URL u = new URL(ref);
+ final URL u = new URL(ref);
urls.add(u);
} catch (final MalformedURLException mue) {
- logger.warn("Unable to create URL from " + ref + " : " + mue.getMessage());
+ logger.warn("Unable to create URL from {} : {}", ref, mue.getMessage());
}
}
@@ -221,17 +230,17 @@ public class ReferrerFilter implements Preprocessor {
private URL[] createReferrerUrls(final Set<String> referrers) {
final List<URL> urls = new ArrayList<>();
- for(final String ref : referrers) {
+ for (final String ref : referrers) {
final int pos = ref.indexOf("://");
// valid url?
- if ( pos != -1 ) {
+ if (pos != -1) {
this.add(urls, ref);
} else {
this.add(urls, "http://" + ref + ":0");
this.add(urls, "https://" + ref + ":0");
}
}
- return urls.toArray(new URL[urls.size()]);
+ return urls.toArray(new URL[0]);
}
/**
@@ -239,17 +248,17 @@ public class ReferrerFilter implements Preprocessor {
*/
private Pattern[] createRegexPatterns(final String[] regexps) {
final List<Pattern> patterns = new ArrayList<>();
- if ( regexps != null ) {
- for(final String regexp : regexps) {
+ if (regexps != null) {
+ for (final String regexp : regexps) {
try {
- final Pattern pattern = Pattern.compile(regexp);
+ final Pattern pattern = Pattern.compile(regexp);
patterns.add(pattern);
} catch (final Exception e) {
- logger.warn("Unable to create Pattern from {} : {}", new Object[]{regexp, e.getMessage()});
+ logger.warn("Unable to create Pattern from {} : {}", regexp, e.getMessage());
}
}
}
- return patterns.toArray(new Pattern[patterns.size()]);
+ return patterns.toArray(new Pattern[0]);
}
@Activate
@@ -259,19 +268,19 @@ public class ReferrerFilter implements Preprocessor {
this.excludedRegexUserAgents = createRegexPatterns(config.exclude_agents_regexp());
final Set<String> allowUriReferrers = getDefaultAllowedReferrers();
- if ( config.allow_hosts() != null ) {
+ if (config.allow_hosts() != null) {
allowUriReferrers.addAll(Arrays.asList(config.allow_hosts()));
}
this.allowedUriReferrers = createReferrerUrls(allowUriReferrers);
this.filterMethods = config.filter_methods();
if (this.filterMethods != null
- &&this.filterMethods.length == 1
- && (this.filterMethods[0] == null || this.filterMethods[0].trim().length() == 0)) {
+ && this.filterMethods.length == 1
+ && (this.filterMethods[0] == null || this.filterMethods[0].trim().length() == 0)) {
this.filterMethods = null;
}
- if ( this.filterMethods != null ) {
- for(int i=0; i<filterMethods.length; i++) {
+ if (this.filterMethods != null) {
+ for (int i = 0; i < filterMethods.length; i++) {
filterMethods[i] = filterMethods[i].toUpperCase();
}
}
@@ -286,23 +295,21 @@ public class ReferrerFilter implements Preprocessor {
private ServiceRegistration<Object> registerConfigPrinter(BundleContext bundleContext) {
final ConfigurationPrinter cfgPrinter = new ConfigurationPrinter();
final Dictionary<String, String> serviceProps = new Hashtable<>();
- serviceProps.put(Constants.SERVICE_DESCRIPTION,
- "Apache Sling Referrer Filter Configuration Printer");
+ serviceProps.put(Constants.SERVICE_DESCRIPTION, "Apache Sling Referrer Filter Configuration Printer");
serviceProps.put(Constants.SERVICE_VENDOR, "The Apache Software Foundation");
serviceProps.put("felix.webconsole.label", "slingreferrerfilter");
serviceProps.put("felix.webconsole.title", "Sling Referrer Filter");
serviceProps.put("felix.webconsole.configprinter.modes", "always");
- return bundleContext.registerService(Object.class,
- cfgPrinter, serviceProps);
+ return bundleContext.registerService(Object.class, cfgPrinter, serviceProps);
}
private boolean isModification(final HttpServletRequest req) {
final String method = req.getMethod();
- if ( filterMethods != null ) {
- for(final String m : filterMethods) {
- if ( m.equals(method) ) {
+ if (filterMethods != null) {
+ for (final String m : filterMethods) {
+ if (m.equals(method)) {
return true;
}
}
@@ -314,14 +321,14 @@ public class ReferrerFilter implements Preprocessor {
public void doFilter(final ServletRequest req,
final ServletResponse res,
final FilterChain chain)
- throws IOException, ServletException {
- if ( req instanceof HttpServletRequest && res instanceof HttpServletResponse ) {
- final HttpServletRequest request = (HttpServletRequest)req;
+ throws IOException, ServletException {
+ if (req instanceof HttpServletRequest && res instanceof HttpServletResponse) {
+ final HttpServletRequest request = (HttpServletRequest) req;
// is this a modification request from a browser
- if ( this.isBrowserRequest(request) && this.isModification(request) ) {
- if ( !this.isValidRequest(request) ) {
- final HttpServletResponse response = (HttpServletResponse)res;
+ if (this.isBrowserRequest(request) && this.isModification(request)) {
+ if (!this.isValidRequest(request)) {
+ final HttpServletResponse response = (HttpServletResponse) res;
// we use 403
response.sendError(403);
return;
@@ -331,18 +338,19 @@ public class ReferrerFilter implements Preprocessor {
chain.doFilter(req, res);
}
- final static class HostInfo {
- public String host;
- public String scheme;
- public int port;
- public String toURI() {
+ static final class HostInfo {
+ String host;
+ String scheme;
+ int port;
+
+ String toURI() {
return scheme + "://" + host + ":" + port;
}
}
HostInfo getHost(final String referrer) {
final int startPos = referrer.indexOf("://") + 3;
- if ( startPos == 2 || startPos == referrer.length() ) {
+ if (startPos == 2 || startPos == referrer.length()) {
// we consider this illegal
return null;
}
@@ -355,11 +363,11 @@ public class ReferrerFilter implements Preprocessor {
final String hostPart = (endPos == -1 ? hostAndPath.substring(startPos) : hostAndPath.substring(startPos, endPos));
final int hostNameStart = hostPart.indexOf('@') + 1;
final int hostNameEnd = hostPart.lastIndexOf(':');
- if (hostNameEnd < hostNameStart ) {
+ if (hostNameEnd < hostNameStart) {
info.host = hostPart.substring(hostNameStart);
- if ( info.scheme.equals("http") ) {
+ if (info.scheme.equals("http")) {
info.port = 80;
- } else if ( info.scheme.equals("https") ) {
+ } else if (info.scheme.equals("https")) {
info.port = 443;
}
} else {
@@ -372,37 +380,35 @@ public class ReferrerFilter implements Preprocessor {
boolean isValidRequest(final HttpServletRequest request) {
final String referrer = request.getHeader("referer");
// check for missing/empty referrer
- if ( referrer == null || referrer.trim().length() == 0 ) {
- if ( !this.allowEmpty ) {
+ if (referrer == null || referrer.trim().length() == 0) {
+ if (!this.allowEmpty) {
this.logger.info("Rejected empty referrer header for {} request to {}", request.getMethod(), request.getRequestURI());
}
return this.allowEmpty;
}
// check for relative referrer - which is always allowed
- if ( referrer.indexOf(":/") == - 1 ) {
+ if (!referrer.contains(":/")) {
return true;
}
final HostInfo info = getHost(referrer);
- if ( info == null ) {
+ if (info == null) {
// if this is invalid we just return invalid
- this.logger.info("Rejected illegal referrer header for {} request to {} : {}",
- new Object[] {request.getMethod(), request.getRequestURI(), referrer});
+ this.logger.info("Rejected illegal referrer header for {} request to {} : {}", request.getMethod(), request.getRequestURI(), referrer);
return false;
}
// allow the request if the host name of the referrer is
// the same as the request's host name
- if ( info.host.equals(request.getServerName()) ) {
+ if (info.host.equals(request.getServerName())) {
return true;
}
// allow the request if the referrer matches any of the allowed referrers
boolean valid = isValidUriReferrer(info) || isValidRegexReferrer(info);
- if ( !valid) {
- this.logger.info("Rejected referrer header for {} request to {} : {}",
- new Object[] {request.getMethod(), request.getRequestURI(), referrer});
+ if (!valid) {
+ this.logger.info("Rejected referrer header for {} request to {} : {}", request.getMethod(), request.getRequestURI(), referrer);
}
return valid;
}
@@ -428,9 +434,9 @@ public class ReferrerFilter implements Preprocessor {
* @return <code>true</code> if the hostInfo matches any of the allowed URI referrer.
*/
private boolean isValidUriReferrer(HostInfo hostInfo) {
- for(final URL ref : this.allowedUriReferrers) {
- if ( hostInfo.host.equals(ref.getHost()) && hostInfo.scheme.equals(ref.getProtocol()) ) {
- if ( ref.getPort() == 0 || hostInfo.port == ref.getPort() ) {
+ for (final URL ref : this.allowedUriReferrers) {
+ if (hostInfo.host.equals(ref.getHost()) && hostInfo.scheme.equals(ref.getProtocol())) {
+ if (ref.getPort() == 0 || hostInfo.port == ref.getPort()) {
return true;
}
}
@@ -443,7 +449,7 @@ public class ReferrerFilter implements Preprocessor {
* @return <code>true</code> if the hostInfo matches any of the allowed regexp referrer.
*/
private boolean isValidRegexReferrer(HostInfo hostInfo) {
- for(final Pattern ref : this.allowedRegexReferrers) {
+ for (final Pattern ref : this.allowedRegexReferrers) {
String url = hostInfo.toURI();
if (ref.matcher(url).matches()) {
return true;
@@ -454,11 +460,12 @@ public class ReferrerFilter implements Preprocessor {
/**
* Returns <code>true</code> if the provided user agent matches any present exclusion regexp pattern.
+ *
* @param userAgent The user agent string to check
* @return <code>true</code> if the user agent matches any exclusion pattern.
*/
private boolean isExcludedRegexUserAgent(String userAgent) {
- for(final Pattern pattern : this.excludedRegexUserAgents) {
+ for (final Pattern pattern : this.excludedRegexUserAgents) {
if (pattern.matcher(userAgent).matches()) {
return true;
}
@@ -478,7 +485,7 @@ public class ReferrerFilter implements Preprocessor {
*
* @param request The request to inspect
* @return <code>true</code> if the request is assumed to be sent by a
- * browser.
+ * browser.
*/
protected boolean isBrowserRequest(final HttpServletRequest request) {
final String userAgent = request.getHeader(USER_AGENT);
@@ -491,8 +498,9 @@ public class ReferrerFilter implements Preprocessor {
/**
* Print out the allowedReferrers
- * @see org.apache.felix.webconsole.ConfigurationPrinter#printConfiguration(java.io.PrintWriter)
+ *
* @param pw the PrintWriter object
+ * @see org.apache.felix.webconsole.ConfigurationPrinter#printConfiguration(java.io.PrintWriter)
*/
public void printConfiguration(final PrintWriter pw) {
pw.println("Current Apache Sling Referrer Filter Allowed Referrers:");