You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@sling.apache.org by cz...@apache.org on 2022/02/07 10:20:09 UTC

[sling-org-apache-sling-security] branch master updated: SLING-11117 : Inconsistent formatting and minor improvements (#5)

This is an automated email from the ASF dual-hosted git repository.

cziegeler pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/sling-org-apache-sling-security.git


The following commit(s) were added to refs/heads/master by this push:
     new aab3b23  SLING-11117 : Inconsistent formatting and minor improvements (#5)
aab3b23 is described below

commit aab3b232abc27aaa32cd00547a9933bd080b5384
Author: anchela <an...@apache.org>
AuthorDate: Mon Feb 7 11:19:29 2022 +0100

    SLING-11117 : Inconsistent formatting and minor improvements (#5)
---
 .../security/impl/ContentDispositionFilter.java    |  57 ++++++-----
 .../apache/sling/security/impl/ReferrerFilter.java | 113 +++++++++++----------
 2 files changed, 86 insertions(+), 84 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 82d4389..13b4625 100644
--- a/src/main/java/org/apache/sling/security/impl/ContentDispositionFilter.java
+++ b/src/main/java/org/apache/sling/security/impl/ContentDispositionFilter.java
@@ -55,7 +55,9 @@ import org.slf4j.LoggerFactory;
 @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");
@@ -79,9 +81,9 @@ public class ContentDispositionFilter implements Filter {
     @Activate
     public ContentDispositionFilter(final 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) {
@@ -114,7 +116,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);
                         }
                     }
@@ -122,25 +124,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
     }
 
@@ -151,7 +152,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;
@@ -164,12 +165,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;
     }
@@ -189,7 +188,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;
@@ -233,7 +234,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);
                                 }
@@ -245,7 +246,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;
@@ -264,7 +265,7 @@ public class ContentDispositionFilter implements Filter {
             super.setContentType(type);
         }
 
-      //---------- PRIVATE METHODS ---------
+        //---------- PRIVATE METHODS ---------
 
         private boolean setContentDisposition(Resource resource) {
             boolean contentDispositionAdded = false;
@@ -275,17 +276,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 38b3cdd..f1902aa 100644
--- a/src/main/java/org/apache/sling/security/impl/ReferrerFilter.java
+++ b/src/main/java/org/apache/sling/security/impl/ReferrerFilter.java
@@ -39,6 +39,7 @@ import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
+
 import org.osgi.service.component.annotations.Activate;
 import org.osgi.service.component.annotations.Component;
 import org.osgi.service.http.whiteboard.HttpWhiteboardConstants;
@@ -59,7 +60,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
@@ -171,24 +172,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");
@@ -203,10 +204,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());
         }
     }
 
@@ -216,17 +217,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]);
     }
 
     /**
@@ -234,17 +235,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
@@ -254,20 +255,20 @@ 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);
 
         String[] methods = config.filter_methods();
-        if ( methods != null ) {
+        if (methods != null) {
             final List<String> values = new ArrayList<>();
-            for(final String m : methods) {
-                if ( m != null && m.trim().length() > 0 ) {
+            for (final String m : methods) {
+                if (m != null && m.trim().length() > 0) {
                     values.add(m.trim().toUpperCase());
                 }
             }
-            if ( values.isEmpty() ) {
+            if (values.isEmpty()) {
                 methods = null;
             } else {
                 methods = values.toArray(new String[values.size()]);
@@ -278,9 +279,9 @@ public class ReferrerFilter implements  Preprocessor {
 
     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;
                 }
             }
@@ -292,14 +293,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;
@@ -309,18 +310,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;
         }
@@ -333,11 +335,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 {
@@ -350,37 +352,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;
     }
@@ -406,9 +406,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;
                 }
             }
@@ -421,7 +421,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;
@@ -432,11 +432,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;
             }
@@ -456,7 +457,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);