Search in sources :

Example 1 with ServletSecurityMetaData

use of org.jboss.metadata.web.spec.ServletSecurityMetaData in project wildfly by wildfly.

the class WarJACCService method createPermissions.

/**
 * {@inheritDoc}
 */
@Override
public void createPermissions(WarMetaData metaData, PolicyConfiguration pc) throws PolicyContextException {
    JBossWebMetaData jbossWebMetaData = metaData.getMergedJBossWebMetaData();
    HashMap<String, PatternInfo> patternMap = qualifyURLPatterns(jbossWebMetaData);
    List<SecurityConstraintMetaData> secConstraints = jbossWebMetaData.getSecurityConstraints();
    if (secConstraints != null) {
        for (SecurityConstraintMetaData secConstraint : secConstraints) {
            WebResourceCollectionsMetaData resourceCollectionsMetaData = secConstraint.getResourceCollections();
            UserDataConstraintMetaData userDataConstraintMetaData = secConstraint.getUserDataConstraint();
            if (resourceCollectionsMetaData != null) {
                if (secConstraint.isExcluded() || secConstraint.isUnchecked()) {
                    // Process the permissions for the excluded/unchecked resources
                    for (WebResourceCollectionMetaData resourceCollectionMetaData : resourceCollectionsMetaData) {
                        List<String> httpMethods = new ArrayList<>(resourceCollectionMetaData.getHttpMethods());
                        List<String> ommisions = resourceCollectionMetaData.getHttpMethodOmissions();
                        if (httpMethods.isEmpty() && !ommisions.isEmpty()) {
                            httpMethods.addAll(WebResourceCollectionMetaData.ALL_HTTP_METHODS);
                            httpMethods.removeAll(ommisions);
                        }
                        List<String> urlPatterns = resourceCollectionMetaData.getUrlPatterns();
                        for (String urlPattern : urlPatterns) {
                            PatternInfo info = patternMap.get(urlPattern);
                            info.descriptor = true;
                            // Add the excluded methods
                            if (secConstraint.isExcluded()) {
                                info.addExcludedMethods(httpMethods);
                            }
                            // SECURITY-63: Missing auth-constraint needs unchecked policy
                            if (secConstraint.isUnchecked() && httpMethods.isEmpty()) {
                                info.isMissingAuthConstraint = true;
                            } else {
                                info.missingAuthConstraintMethods.addAll(httpMethods);
                            }
                        }
                    }
                } else {
                    // Process the permission for the resources x roles
                    for (WebResourceCollectionMetaData resourceCollectionMetaData : resourceCollectionsMetaData) {
                        List<String> httpMethods = new ArrayList<>(resourceCollectionMetaData.getHttpMethods());
                        List<String> methodOmissions = resourceCollectionMetaData.getHttpMethodOmissions();
                        if (httpMethods.isEmpty() && !methodOmissions.isEmpty()) {
                            httpMethods.addAll(WebResourceCollectionMetaData.ALL_HTTP_METHODS);
                            httpMethods.removeAll(methodOmissions);
                        }
                        List<String> urlPatterns = resourceCollectionMetaData.getUrlPatterns();
                        for (String urlPattern : urlPatterns) {
                            // Get the qualified url pattern
                            PatternInfo info = patternMap.get(urlPattern);
                            info.descriptor = true;
                            HashSet<String> mappedRoles = new HashSet<String>();
                            secConstraint.getAuthConstraint().getRoleNames();
                            List<String> authRoles = secConstraint.getAuthConstraint().getRoleNames();
                            for (String role : authRoles) {
                                if ("*".equals(role)) {
                                    // The wildcard ref maps to all declared security-role names
                                    mappedRoles.addAll(jbossWebMetaData.getSecurityRoleNames());
                                } else {
                                    mappedRoles.add(role);
                                }
                            }
                            info.addRoles(mappedRoles, httpMethods);
                            // Add the transport to methods
                            if (userDataConstraintMetaData != null && userDataConstraintMetaData.getTransportGuarantee() != null)
                                info.addTransport(userDataConstraintMetaData.getTransportGuarantee().name(), httpMethods);
                        }
                    }
                }
            }
        }
    }
    JBossServletsMetaData servlets = jbossWebMetaData.getServlets();
    List<ServletMappingMetaData> mappings = jbossWebMetaData.getServletMappings();
    if (servlets != null && mappings != null) {
        Map<String, List<String>> servletMappingMap = new HashMap<>();
        for (ServletMappingMetaData mapping : mappings) {
            List<String> list = servletMappingMap.get(mapping.getServletName());
            if (list == null) {
                servletMappingMap.put(mapping.getServletName(), list = new ArrayList<>());
            }
            list.addAll(mapping.getUrlPatterns());
        }
        if (!jbossWebMetaData.isMetadataComplete()) {
            for (JBossServletMetaData servlet : servlets) {
                ServletSecurityMetaData security = servlet.getServletSecurity();
                if (security != null) {
                    List<String> servletMappings = servletMappingMap.get(servlet.getServletName());
                    if (servletMappings != null) {
                        if (security.getHttpMethodConstraints() != null) {
                            for (HttpMethodConstraintMetaData s : security.getHttpMethodConstraints()) {
                                if (s.getRolesAllowed() == null || s.getRolesAllowed().isEmpty()) {
                                    for (String urlPattern : servletMappings) {
                                        // Get the qualified url pattern
                                        PatternInfo info = patternMap.get(urlPattern);
                                        if (info.descriptor) {
                                            continue;
                                        }
                                        // Add the excluded methods
                                        if (s.getEmptyRoleSemantic() == null || s.getEmptyRoleSemantic() == EmptyRoleSemanticType.PERMIT) {
                                            info.missingAuthConstraintMethods.add(s.getMethod());
                                        } else {
                                            info.addExcludedMethods(Collections.singletonList(s.getMethod()));
                                        }
                                        // Add the transport to methods
                                        if (s.getTransportGuarantee() != null)
                                            info.addTransport(s.getTransportGuarantee().name(), Collections.singletonList(s.getMethod()));
                                    }
                                } else {
                                    for (String urlPattern : servletMappings) {
                                        // Get the qualified url pattern
                                        PatternInfo info = patternMap.get(urlPattern);
                                        if (info.descriptor) {
                                            continue;
                                        }
                                        HashSet<String> mappedRoles = new HashSet<String>();
                                        List<String> authRoles = s.getRolesAllowed();
                                        for (String role : authRoles) {
                                            if ("*".equals(role)) {
                                                // The wildcard ref maps to all declared security-role names
                                                mappedRoles.addAll(jbossWebMetaData.getSecurityRoleNames());
                                            } else {
                                                mappedRoles.add(role);
                                            }
                                        }
                                        info.addRoles(mappedRoles, Collections.singletonList(s.getMethod()));
                                        // Add the transport to methods
                                        if (s.getTransportGuarantee() != null)
                                            info.addTransport(s.getTransportGuarantee().name(), Collections.singletonList(s.getMethod()));
                                    }
                                }
                            }
                        }
                        if (security.getRolesAllowed() == null || security.getRolesAllowed().isEmpty()) {
                            for (String urlPattern : servletMappings) {
                                // Get the qualified url pattern
                                PatternInfo info = patternMap.get(urlPattern);
                                if (info.descriptor) {
                                    continue;
                                }
                                // Add the excluded methods
                                if (security.getEmptyRoleSemantic() == null || security.getEmptyRoleSemantic() == EmptyRoleSemanticType.PERMIT) {
                                    info.isMissingAuthConstraint = true;
                                } else {
                                    Set<String> methods = new HashSet<>(WebResourceCollectionMetaData.ALL_HTTP_METHODS);
                                    if (security.getHttpMethodConstraints() != null) {
                                        for (HttpMethodConstraintMetaData method : security.getHttpMethodConstraints()) {
                                            methods.remove(method.getMethod());
                                        }
                                    }
                                    info.addExcludedMethods(new ArrayList<>(methods));
                                }
                                // Add the transport to methods
                                if (security.getTransportGuarantee() != null)
                                    info.addTransport(security.getTransportGuarantee().name(), Collections.emptyList());
                            }
                        } else {
                            for (String urlPattern : servletMappings) {
                                // Get the qualified url pattern
                                PatternInfo info = patternMap.get(urlPattern);
                                if (info.descriptor) {
                                    continue;
                                }
                                HashSet<String> mappedRoles = new HashSet<String>();
                                List<String> authRoles = security.getRolesAllowed();
                                for (String role : authRoles) {
                                    if ("*".equals(role)) {
                                        // The wildcard ref maps to all declared security-role names
                                        mappedRoles.addAll(jbossWebMetaData.getSecurityRoleNames());
                                    } else {
                                        mappedRoles.add(role);
                                    }
                                }
                                info.addRoles(mappedRoles, Collections.emptyList());
                                // Add the transport to methods
                                if (security.getTransportGuarantee() != null)
                                    info.addTransport(security.getTransportGuarantee().name(), Collections.emptyList());
                            }
                        }
                    }
                }
            }
        }
    }
    // Create the permissions
    for (PatternInfo info : patternMap.values()) {
        String qurl = info.getQualifiedPattern();
        if (info.isOverridden) {
            continue;
        }
        // Create the excluded permissions
        String[] httpMethods = info.getExcludedMethods();
        if (httpMethods != null) {
            // There were excluded security-constraints
            WebResourcePermission wrp = new WebResourcePermission(qurl, httpMethods);
            WebUserDataPermission wudp = new WebUserDataPermission(qurl, httpMethods, null);
            pc.addToExcludedPolicy(wrp);
            pc.addToExcludedPolicy(wudp);
        }
        // Create the role permissions
        Iterator<Map.Entry<String, Set<String>>> roles = info.getRoleMethods();
        Set<String> seenMethods = new HashSet<>();
        while (roles.hasNext()) {
            Map.Entry<String, Set<String>> roleMethods = roles.next();
            String role = roleMethods.getKey();
            Set<String> methods = roleMethods.getValue();
            seenMethods.addAll(methods);
            httpMethods = methods.toArray(new String[methods.size()]);
            pc.addToRole(role, new WebResourcePermission(qurl, httpMethods));
        }
        // there are totally 7 http methods from the jacc spec (See WebResourceCollectionMetaData.ALL_HTTP_METHOD_NAMES)
        final int NUMBER_OF_HTTP_METHODS = 7;
        // JACC 1.1: create !(httpmethods) in unchecked perms
        if (jbossWebMetaData.getDenyUncoveredHttpMethods() == null && seenMethods.size() != NUMBER_OF_HTTP_METHODS) {
            WebResourcePermission wrpUnchecked = seenMethods.isEmpty() ? new WebResourcePermission(qurl, (String) null) : new WebResourcePermission(qurl, "!" + getCommaSeparatedString(seenMethods.toArray(new String[seenMethods.size()])));
            pc.addToUncheckedPolicy(wrpUnchecked);
        }
        if (jbossWebMetaData.getDenyUncoveredHttpMethods() == null) {
            // Create the unchecked permissions
            String[] missingHttpMethods = info.getMissingMethods();
            int length = missingHttpMethods.length;
            roles = info.getRoleMethods();
            if (length > 0 && !roles.hasNext()) {
                // Create the unchecked permissions WebResourcePermissions
                WebResourcePermission wrp = new WebResourcePermission(qurl, missingHttpMethods);
                pc.addToUncheckedPolicy(wrp);
            } else if (!roles.hasNext()) {
                pc.addToUncheckedPolicy(new WebResourcePermission(qurl, (String) null));
            }
            // SECURITY-63: Missing auth-constraint needs unchecked policy
            if (info.isMissingAuthConstraint) {
                pc.addToUncheckedPolicy(new WebResourcePermission(qurl, (String) null));
            } else if (!info.allMethods.containsAll(WebResourceCollectionMetaData.ALL_HTTP_METHODS)) {
                List<String> methods = new ArrayList<>(WebResourceCollectionMetaData.ALL_HTTP_METHODS);
                methods.removeAll(info.allMethods);
                pc.addToUncheckedPolicy(new WebResourcePermission(qurl, methods.toArray(new String[methods.size()])));
            }
            if (!info.missingAuthConstraintMethods.isEmpty()) {
                pc.addToUncheckedPolicy(new WebResourcePermission(qurl, info.missingAuthConstraintMethods.toArray(new String[info.missingAuthConstraintMethods.size()])));
            }
        }
        // Create the unchecked permissions WebUserDataPermissions
        Iterator<Map.Entry<String, Set<String>>> transportConstraints = info.getTransportMethods();
        while (transportConstraints.hasNext()) {
            Map.Entry<String, Set<String>> transportMethods = transportConstraints.next();
            String transport = transportMethods.getKey();
            Set<String> methods = transportMethods.getValue();
            httpMethods = new String[methods.size()];
            methods.toArray(httpMethods);
            WebUserDataPermission wudp = new WebUserDataPermission(qurl, httpMethods, transport);
            pc.addToUncheckedPolicy(wudp);
            // with the url pattern and null
            if ("NONE".equals(transport)) {
                WebUserDataPermission wudp1 = new WebUserDataPermission(qurl, null);
                pc.addToUncheckedPolicy(wudp1);
            } else {
                // JACC 1.1: Transport is CONFIDENTIAL/INTEGRAL, add a !(http methods)
                WebUserDataPermission wudpNonNull = new WebUserDataPermission(qurl, "!" + getCommaSeparatedString(httpMethods));
                pc.addToUncheckedPolicy(wudpNonNull);
            }
        }
    }
    Set<String> declaredRoles = jbossWebMetaData.getSecurityRoleNames();
    declaredRoles.add(ANY_AUTHENTICATED_USER_ROLE);
    /*
         * Create WebRoleRefPermissions for all servlet/security-role-refs along with all the cross product of servlets and
         * security-role elements that are not referenced via a security-role-ref as described in JACC section 3.1.3.2
         */
    JBossServletsMetaData servletsMetaData = jbossWebMetaData.getServlets();
    for (JBossServletMetaData servletMetaData : servletsMetaData) {
        Set<String> unrefRoles = new HashSet<String>(declaredRoles);
        String servletName = servletMetaData.getName();
        SecurityRoleRefsMetaData roleRefsMetaData = servletMetaData.getSecurityRoleRefs();
        // Perform the unreferenced roles processing for every servlet name
        if (roleRefsMetaData != null) {
            for (SecurityRoleRefMetaData roleRefMetaData : roleRefsMetaData) {
                String roleRef = roleRefMetaData.getRoleLink();
                String roleName = roleRefMetaData.getRoleName();
                WebRoleRefPermission wrrp = new WebRoleRefPermission(servletName, roleName);
                pc.addToRole(roleRef, wrrp);
                // Remove the role from the unreferencedRoles
                unrefRoles.remove(roleName);
            }
        }
        // in a security-role-ref within the servlet element.
        for (String unrefRole : unrefRoles) {
            WebRoleRefPermission unrefP = new WebRoleRefPermission(servletName, unrefRole);
            pc.addToRole(unrefRole, unrefP);
        }
    }
    // such permission must be the role-name of the corresponding role.
    for (String role : declaredRoles) {
        WebRoleRefPermission wrrep = new WebRoleRefPermission("", role);
        pc.addToRole(role, wrrep);
    }
}
Also used : JBossWebMetaData(org.jboss.metadata.web.jboss.JBossWebMetaData) SecurityRoleRefsMetaData(org.jboss.metadata.javaee.spec.SecurityRoleRefsMetaData) WebResourcePermission(javax.security.jacc.WebResourcePermission) HashSet(java.util.HashSet) Set(java.util.Set) HashMap(java.util.HashMap) JBossServletMetaData(org.jboss.metadata.web.jboss.JBossServletMetaData) ArrayList(java.util.ArrayList) ServletSecurityMetaData(org.jboss.metadata.web.spec.ServletSecurityMetaData) SecurityConstraintMetaData(org.jboss.metadata.web.spec.SecurityConstraintMetaData) WebResourceCollectionsMetaData(org.jboss.metadata.web.spec.WebResourceCollectionsMetaData) ArrayList(java.util.ArrayList) List(java.util.List) HashSet(java.util.HashSet) UserDataConstraintMetaData(org.jboss.metadata.web.spec.UserDataConstraintMetaData) JBossServletsMetaData(org.jboss.metadata.web.jboss.JBossServletsMetaData) WebUserDataPermission(javax.security.jacc.WebUserDataPermission) HttpMethodConstraintMetaData(org.jboss.metadata.web.spec.HttpMethodConstraintMetaData) ServletMappingMetaData(org.jboss.metadata.web.spec.ServletMappingMetaData) SecurityRoleRefMetaData(org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData) WebRoleRefPermission(javax.security.jacc.WebRoleRefPermission) HashMap(java.util.HashMap) Map(java.util.Map) WebResourceCollectionMetaData(org.jboss.metadata.web.spec.WebResourceCollectionMetaData)

Example 2 with ServletSecurityMetaData

use of org.jboss.metadata.web.spec.ServletSecurityMetaData in project wildfly by wildfly.

the class WarAnnotationDeploymentProcessor method processAnnotations.

/**
 * Process a single index.
 *
 * @param index the annotation index
 *
 * @throws DeploymentUnitProcessingException
 */
protected WebMetaData processAnnotations(Index index) throws DeploymentUnitProcessingException {
    WebMetaData metaData = new WebMetaData();
    // @WebServlet
    final List<AnnotationInstance> webServletAnnotations = index.getAnnotations(webServlet);
    if (webServletAnnotations != null && !webServletAnnotations.isEmpty()) {
        ServletsMetaData servlets = new ServletsMetaData();
        List<ServletMappingMetaData> servletMappings = new ArrayList<ServletMappingMetaData>();
        for (final AnnotationInstance annotation : webServletAnnotations) {
            ServletMetaData servlet = new ServletMetaData();
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebServletAnnotation(target));
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            servlet.setServletClass(classInfo.toString());
            AnnotationValue nameValue = annotation.value("name");
            if (nameValue == null || nameValue.asString().isEmpty()) {
                servlet.setName(classInfo.toString());
            } else {
                servlet.setName(nameValue.asString());
            }
            AnnotationValue loadOnStartup = annotation.value("loadOnStartup");
            if (loadOnStartup != null && loadOnStartup.asInt() >= 0) {
                servlet.setLoadOnStartupInt(loadOnStartup.asInt());
            }
            AnnotationValue asyncSupported = annotation.value("asyncSupported");
            if (asyncSupported != null) {
                servlet.setAsyncSupported(asyncSupported.asBoolean());
            }
            AnnotationValue initParamsValue = annotation.value("initParams");
            if (initParamsValue != null) {
                AnnotationInstance[] initParamsAnnotations = initParamsValue.asNestedArray();
                if (initParamsAnnotations != null && initParamsAnnotations.length > 0) {
                    List<ParamValueMetaData> initParams = new ArrayList<ParamValueMetaData>();
                    for (AnnotationInstance initParamsAnnotation : initParamsAnnotations) {
                        ParamValueMetaData initParam = new ParamValueMetaData();
                        AnnotationValue initParamName = initParamsAnnotation.value("name");
                        AnnotationValue initParamValue = initParamsAnnotation.value();
                        if (initParamName == null || initParamValue == null) {
                            throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebInitParamAnnotation(target));
                        }
                        AnnotationValue initParamDescription = initParamsAnnotation.value("description");
                        initParam.setParamName(initParamName.asString());
                        initParam.setParamValue(initParamValue.asString());
                        if (initParamDescription != null) {
                            Descriptions descriptions = getDescription(initParamDescription.asString());
                            if (descriptions != null) {
                                initParam.setDescriptions(descriptions);
                            }
                        }
                        initParams.add(initParam);
                    }
                    servlet.setInitParam(initParams);
                }
            }
            AnnotationValue descriptionValue = annotation.value("description");
            AnnotationValue displayNameValue = annotation.value("displayName");
            AnnotationValue smallIconValue = annotation.value("smallIcon");
            AnnotationValue largeIconValue = annotation.value("largeIcon");
            DescriptionGroupMetaData descriptionGroup = getDescriptionGroup((descriptionValue == null) ? "" : descriptionValue.asString(), (displayNameValue == null) ? "" : displayNameValue.asString(), (smallIconValue == null) ? "" : smallIconValue.asString(), (largeIconValue == null) ? "" : largeIconValue.asString());
            if (descriptionGroup != null) {
                servlet.setDescriptionGroup(descriptionGroup);
            }
            ServletMappingMetaData servletMapping = new ServletMappingMetaData();
            servletMapping.setServletName(servlet.getName());
            List<String> urlPatterns = new ArrayList<String>();
            AnnotationValue urlPatternsValue = annotation.value("urlPatterns");
            if (urlPatternsValue != null) {
                for (String urlPattern : urlPatternsValue.asStringArray()) {
                    urlPatterns.add(urlPattern);
                }
            }
            urlPatternsValue = annotation.value();
            if (urlPatternsValue != null) {
                for (String urlPattern : urlPatternsValue.asStringArray()) {
                    urlPatterns.add(urlPattern);
                }
            }
            if (!urlPatterns.isEmpty()) {
                servletMapping.setUrlPatterns(urlPatterns);
                servletMappings.add(servletMapping);
            }
            servlets.add(servlet);
        }
        metaData.setServlets(servlets);
        metaData.setServletMappings(servletMappings);
    }
    // @WebFilter
    final List<AnnotationInstance> webFilterAnnotations = index.getAnnotations(webFilter);
    if (webFilterAnnotations != null && !webFilterAnnotations.isEmpty()) {
        FiltersMetaData filters = new FiltersMetaData();
        List<FilterMappingMetaData> filterMappings = new ArrayList<FilterMappingMetaData>();
        for (final AnnotationInstance annotation : webFilterAnnotations) {
            FilterMetaData filter = new FilterMetaData();
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebFilterAnnotation(target));
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            filter.setFilterClass(classInfo.toString());
            AnnotationValue nameValue = annotation.value("filterName");
            if (nameValue == null || nameValue.asString().isEmpty()) {
                filter.setName(classInfo.toString());
            } else {
                filter.setName(nameValue.asString());
            }
            AnnotationValue asyncSupported = annotation.value("asyncSupported");
            if (asyncSupported != null) {
                filter.setAsyncSupported(asyncSupported.asBoolean());
            }
            AnnotationValue initParamsValue = annotation.value("initParams");
            if (initParamsValue != null) {
                AnnotationInstance[] initParamsAnnotations = initParamsValue.asNestedArray();
                if (initParamsAnnotations != null && initParamsAnnotations.length > 0) {
                    List<ParamValueMetaData> initParams = new ArrayList<ParamValueMetaData>();
                    for (AnnotationInstance initParamsAnnotation : initParamsAnnotations) {
                        ParamValueMetaData initParam = new ParamValueMetaData();
                        AnnotationValue initParamName = initParamsAnnotation.value("name");
                        AnnotationValue initParamValue = initParamsAnnotation.value();
                        if (initParamName == null || initParamValue == null) {
                            throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebInitParamAnnotation(target));
                        }
                        AnnotationValue initParamDescription = initParamsAnnotation.value("description");
                        initParam.setParamName(initParamName.asString());
                        initParam.setParamValue(initParamValue.asString());
                        if (initParamDescription != null) {
                            Descriptions descriptions = getDescription(initParamDescription.asString());
                            if (descriptions != null) {
                                initParam.setDescriptions(descriptions);
                            }
                        }
                        initParams.add(initParam);
                    }
                    filter.setInitParam(initParams);
                }
            }
            AnnotationValue descriptionValue = annotation.value("description");
            AnnotationValue displayNameValue = annotation.value("displayName");
            AnnotationValue smallIconValue = annotation.value("smallIcon");
            AnnotationValue largeIconValue = annotation.value("largeIcon");
            DescriptionGroupMetaData descriptionGroup = getDescriptionGroup((descriptionValue == null) ? "" : descriptionValue.asString(), (displayNameValue == null) ? "" : displayNameValue.asString(), (smallIconValue == null) ? "" : smallIconValue.asString(), (largeIconValue == null) ? "" : largeIconValue.asString());
            if (descriptionGroup != null) {
                filter.setDescriptionGroup(descriptionGroup);
            }
            filters.add(filter);
            FilterMappingMetaData filterMapping = new FilterMappingMetaData();
            filterMapping.setFilterName(filter.getName());
            List<String> urlPatterns = new ArrayList<String>();
            List<String> servletNames = new ArrayList<String>();
            List<DispatcherType> dispatchers = new ArrayList<DispatcherType>();
            AnnotationValue urlPatternsValue = annotation.value("urlPatterns");
            if (urlPatternsValue != null) {
                for (String urlPattern : urlPatternsValue.asStringArray()) {
                    urlPatterns.add(urlPattern);
                }
            }
            urlPatternsValue = annotation.value();
            if (urlPatternsValue != null) {
                for (String urlPattern : urlPatternsValue.asStringArray()) {
                    urlPatterns.add(urlPattern);
                }
            }
            if (!urlPatterns.isEmpty()) {
                filterMapping.setUrlPatterns(urlPatterns);
            }
            AnnotationValue servletNamesValue = annotation.value("servletNames");
            if (servletNamesValue != null) {
                for (String servletName : servletNamesValue.asStringArray()) {
                    servletNames.add(servletName);
                }
            }
            if (!servletNames.isEmpty()) {
                filterMapping.setServletNames(servletNames);
            }
            AnnotationValue dispatcherTypesValue = annotation.value("dispatcherTypes");
            if (dispatcherTypesValue != null) {
                for (String dispatcherValue : dispatcherTypesValue.asEnumArray()) {
                    dispatchers.add(DispatcherType.valueOf(dispatcherValue));
                }
            }
            if (!dispatchers.isEmpty()) {
                filterMapping.setDispatchers(dispatchers);
            }
            if (!urlPatterns.isEmpty() || !servletNames.isEmpty()) {
                filterMappings.add(filterMapping);
            }
        }
        metaData.setFilters(filters);
        metaData.setFilterMappings(filterMappings);
    }
    // @WebListener
    final List<AnnotationInstance> webListenerAnnotations = index.getAnnotations(webListener);
    if (webListenerAnnotations != null && !webListenerAnnotations.isEmpty()) {
        List<ListenerMetaData> listeners = new ArrayList<ListenerMetaData>();
        for (final AnnotationInstance annotation : webListenerAnnotations) {
            ListenerMetaData listener = new ListenerMetaData();
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidWebListenerAnnotation(target));
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            listener.setListenerClass(classInfo.toString());
            AnnotationValue descriptionValue = annotation.value();
            if (descriptionValue != null) {
                DescriptionGroupMetaData descriptionGroup = getDescriptionGroup(descriptionValue.asString());
                if (descriptionGroup != null) {
                    listener.setDescriptionGroup(descriptionGroup);
                }
            }
            listeners.add(listener);
        }
        metaData.setListeners(listeners);
    }
    // @RunAs
    final List<AnnotationInstance> runAsAnnotations = index.getAnnotations(runAs);
    if (runAsAnnotations != null && !runAsAnnotations.isEmpty()) {
        AnnotationsMetaData annotations = metaData.getAnnotations();
        if (annotations == null) {
            annotations = new AnnotationsMetaData();
            metaData.setAnnotations(annotations);
        }
        for (final AnnotationInstance annotation : runAsAnnotations) {
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                continue;
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            AnnotationMetaData annotationMD = annotations.get(classInfo.toString());
            if (annotationMD == null) {
                annotationMD = new AnnotationMetaData();
                annotationMD.setClassName(classInfo.toString());
                annotations.add(annotationMD);
            }
            if (annotation.value() == null) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidRunAsAnnotation(target));
            }
            RunAsMetaData runAs = new RunAsMetaData();
            runAs.setRoleName(annotation.value().asString());
            annotationMD.setRunAs(runAs);
        }
    }
    // @DeclareRoles
    final List<AnnotationInstance> declareRolesAnnotations = index.getAnnotations(declareRoles);
    if (declareRolesAnnotations != null && !declareRolesAnnotations.isEmpty()) {
        SecurityRolesMetaData securityRoles = metaData.getSecurityRoles();
        if (securityRoles == null) {
            securityRoles = new SecurityRolesMetaData();
            metaData.setSecurityRoles(securityRoles);
        }
        for (final AnnotationInstance annotation : declareRolesAnnotations) {
            if (annotation.value() == null) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidDeclareRolesAnnotation(annotation.target()));
            }
            for (String role : annotation.value().asStringArray()) {
                SecurityRoleMetaData sr = new SecurityRoleMetaData();
                sr.setRoleName(role);
                securityRoles.add(sr);
            }
        }
    }
    // @MultipartConfig
    final List<AnnotationInstance> multipartConfigAnnotations = index.getAnnotations(multipartConfig);
    if (multipartConfigAnnotations != null && !multipartConfigAnnotations.isEmpty()) {
        AnnotationsMetaData annotations = metaData.getAnnotations();
        if (annotations == null) {
            annotations = new AnnotationsMetaData();
            metaData.setAnnotations(annotations);
        }
        for (final AnnotationInstance annotation : multipartConfigAnnotations) {
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidMultipartConfigAnnotation(target));
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            AnnotationMetaData annotationMD = annotations.get(classInfo.toString());
            if (annotationMD == null) {
                annotationMD = new AnnotationMetaData();
                annotationMD.setClassName(classInfo.toString());
                annotations.add(annotationMD);
            }
            MultipartConfigMetaData multipartConfig = new MultipartConfigMetaData();
            AnnotationValue locationValue = annotation.value("location");
            if (locationValue != null && locationValue.asString().length() > 0) {
                multipartConfig.setLocation(locationValue.asString());
            }
            AnnotationValue maxFileSizeValue = annotation.value("maxFileSize");
            if (maxFileSizeValue != null && maxFileSizeValue.asLong() != -1L) {
                multipartConfig.setMaxFileSize(maxFileSizeValue.asLong());
            }
            AnnotationValue maxRequestSizeValue = annotation.value("maxRequestSize");
            if (maxRequestSizeValue != null && maxRequestSizeValue.asLong() != -1L) {
                multipartConfig.setMaxRequestSize(maxRequestSizeValue.asLong());
            }
            AnnotationValue fileSizeThresholdValue = annotation.value("fileSizeThreshold");
            if (fileSizeThresholdValue != null && fileSizeThresholdValue.asInt() != 0) {
                multipartConfig.setFileSizeThreshold(fileSizeThresholdValue.asInt());
            }
            annotationMD.setMultipartConfig(multipartConfig);
        }
    }
    // @ServletSecurity
    final List<AnnotationInstance> servletSecurityAnnotations = index.getAnnotations(servletSecurity);
    if (servletSecurityAnnotations != null && !servletSecurityAnnotations.isEmpty()) {
        AnnotationsMetaData annotations = metaData.getAnnotations();
        if (annotations == null) {
            annotations = new AnnotationsMetaData();
            metaData.setAnnotations(annotations);
        }
        for (final AnnotationInstance annotation : servletSecurityAnnotations) {
            AnnotationTarget target = annotation.target();
            if (!(target instanceof ClassInfo)) {
                throw new DeploymentUnitProcessingException(UndertowLogger.ROOT_LOGGER.invalidServletSecurityAnnotation(target));
            }
            ClassInfo classInfo = ClassInfo.class.cast(target);
            AnnotationMetaData annotationMD = annotations.get(classInfo.toString());
            if (annotationMD == null) {
                annotationMD = new AnnotationMetaData();
                annotationMD.setClassName(classInfo.toString());
                annotations.add(annotationMD);
            }
            ServletSecurityMetaData servletSecurity = new ServletSecurityMetaData();
            AnnotationValue httpConstraintValue = annotation.value();
            List<String> rolesAllowed = new ArrayList<String>();
            if (httpConstraintValue != null) {
                AnnotationInstance httpConstraint = httpConstraintValue.asNested();
                AnnotationValue httpConstraintERSValue = httpConstraint.value();
                if (httpConstraintERSValue != null) {
                    servletSecurity.setEmptyRoleSemantic(EmptyRoleSemanticType.valueOf(httpConstraintERSValue.asEnum()));
                }
                AnnotationValue httpConstraintTGValue = httpConstraint.value("transportGuarantee");
                if (httpConstraintTGValue != null) {
                    servletSecurity.setTransportGuarantee(TransportGuaranteeType.valueOf(httpConstraintTGValue.asEnum()));
                }
                AnnotationValue rolesAllowedValue = httpConstraint.value("rolesAllowed");
                if (rolesAllowedValue != null) {
                    for (String role : rolesAllowedValue.asStringArray()) {
                        rolesAllowed.add(role);
                    }
                }
            }
            servletSecurity.setRolesAllowed(rolesAllowed);
            AnnotationValue httpMethodConstraintsValue = annotation.value("httpMethodConstraints");
            if (httpMethodConstraintsValue != null) {
                AnnotationInstance[] httpMethodConstraints = httpMethodConstraintsValue.asNestedArray();
                if (httpMethodConstraints.length > 0) {
                    List<HttpMethodConstraintMetaData> methodConstraints = new ArrayList<HttpMethodConstraintMetaData>();
                    for (AnnotationInstance httpMethodConstraint : httpMethodConstraints) {
                        HttpMethodConstraintMetaData methodConstraint = new HttpMethodConstraintMetaData();
                        AnnotationValue httpMethodConstraintValue = httpMethodConstraint.value();
                        if (httpMethodConstraintValue != null) {
                            methodConstraint.setMethod(httpMethodConstraintValue.asString());
                        }
                        AnnotationValue httpMethodConstraintERSValue = httpMethodConstraint.value("emptyRoleSemantic");
                        if (httpMethodConstraintERSValue != null) {
                            methodConstraint.setEmptyRoleSemantic(EmptyRoleSemanticType.valueOf(httpMethodConstraintERSValue.asEnum()));
                        }
                        AnnotationValue httpMethodConstraintTGValue = httpMethodConstraint.value("transportGuarantee");
                        if (httpMethodConstraintTGValue != null) {
                            methodConstraint.setTransportGuarantee(TransportGuaranteeType.valueOf(httpMethodConstraintTGValue.asEnum()));
                        }
                        AnnotationValue rolesAllowedValue = httpMethodConstraint.value("rolesAllowed");
                        rolesAllowed = new ArrayList<String>();
                        if (rolesAllowedValue != null) {
                            for (String role : rolesAllowedValue.asStringArray()) {
                                rolesAllowed.add(role);
                            }
                        }
                        methodConstraint.setRolesAllowed(rolesAllowed);
                        methodConstraints.add(methodConstraint);
                    }
                    servletSecurity.setHttpMethodConstraints(methodConstraints);
                }
            }
            annotationMD.setServletSecurity(servletSecurity);
        }
    }
    return metaData;
}
Also used : DeploymentUnitProcessingException(org.jboss.as.server.deployment.DeploymentUnitProcessingException) SecurityRoleMetaData(org.jboss.metadata.javaee.spec.SecurityRoleMetaData) ArrayList(java.util.ArrayList) SecurityRolesMetaData(org.jboss.metadata.javaee.spec.SecurityRolesMetaData) ServletSecurityMetaData(org.jboss.metadata.web.spec.ServletSecurityMetaData) Descriptions(org.jboss.annotation.javaee.Descriptions) ListenerMetaData(org.jboss.metadata.web.spec.ListenerMetaData) MultipartConfigMetaData(org.jboss.metadata.web.spec.MultipartConfigMetaData) ServletMetaData(org.jboss.metadata.web.spec.ServletMetaData) DispatcherType(org.jboss.metadata.web.spec.DispatcherType) FilterMappingMetaData(org.jboss.metadata.web.spec.FilterMappingMetaData) AnnotationTarget(org.jboss.jandex.AnnotationTarget) ParamValueMetaData(org.jboss.metadata.javaee.spec.ParamValueMetaData) FilterMetaData(org.jboss.metadata.web.spec.FilterMetaData) RunAsMetaData(org.jboss.metadata.javaee.spec.RunAsMetaData) HttpMethodConstraintMetaData(org.jboss.metadata.web.spec.HttpMethodConstraintMetaData) FiltersMetaData(org.jboss.metadata.web.spec.FiltersMetaData) ServletMappingMetaData(org.jboss.metadata.web.spec.ServletMappingMetaData) ServletsMetaData(org.jboss.metadata.web.spec.ServletsMetaData) AnnotationValue(org.jboss.jandex.AnnotationValue) DescriptionGroupMetaData(org.jboss.metadata.javaee.spec.DescriptionGroupMetaData) AnnotationsMetaData(org.jboss.metadata.web.spec.AnnotationsMetaData) AnnotationMetaData(org.jboss.metadata.web.spec.AnnotationMetaData) WebMetaData(org.jboss.metadata.web.spec.WebMetaData) AnnotationInstance(org.jboss.jandex.AnnotationInstance) ClassInfo(org.jboss.jandex.ClassInfo)

Example 3 with ServletSecurityMetaData

use of org.jboss.metadata.web.spec.ServletSecurityMetaData in project wildfly by wildfly.

the class WarJACCService method qualifyURLPatterns.

/**
 * Jakarta Authorization url pattern Qualified URL Pattern Names.
 *
 * The rules for qualifying a URL pattern are dependent on the rules for determining if one URL pattern matches another as
 * defined in Section 3.1.3.3, Servlet URL-Pattern Matching Rules, and are described as follows: - If the pattern is a path
 * prefix pattern, it must be qualified by every path-prefix pattern in the deployment descriptor matched by and different
 * from the pattern being qualified. The pattern must also be qualified by every exact pattern appearing in the deployment
 * descriptor that is matched by the pattern being qualified. - If the pattern is an extension pattern, it must be qualified
 * by every path-prefix pattern appearing in the deployment descriptor and every exact pattern in the deployment descriptor
 * that is matched by the pattern being qualified. - If the pattern is the default pattern, "/", it must be qualified by
 * every other pattern except the default pattern appearing in the deployment descriptor. - If the pattern is an exact
 * pattern, its qualified form must not contain any qualifying patterns.
 *
 * URL patterns are qualified by appending to their String representation, a colon separated representation of the list of
 * patterns that qualify the pattern. Duplicates must not be included in the list of qualifying patterns, and any qualifying
 * pattern matched by another qualifying pattern may5 be dropped from the list.
 *
 * Any pattern, qualified by a pattern that matches it, is overridden and made irrelevant (in the translation) by the
 * qualifying pattern. Specifically, all extension patterns and the default pattern are made irrelevant by the presence of
 * the path prefix pattern "/*" in a deployment descriptor. Patterns qualified by the "/*" pattern violate the
 * URLPatternSpec constraints of WebResourcePermission and WebUserDataPermission names and must be rejected by the
 * corresponding permission constructors.
 *
 * @param metaData - the web deployment metadata
 * @return HashMap<String, PatternInfo>
 */
static HashMap<String, PatternInfo> qualifyURLPatterns(JBossWebMetaData metaData) {
    ArrayList<PatternInfo> prefixList = new ArrayList<PatternInfo>();
    ArrayList<PatternInfo> extensionList = new ArrayList<PatternInfo>();
    ArrayList<PatternInfo> exactList = new ArrayList<PatternInfo>();
    HashMap<String, PatternInfo> patternMap = new HashMap<String, PatternInfo>();
    PatternInfo defaultInfo = null;
    List<SecurityConstraintMetaData> constraints = metaData.getSecurityConstraints();
    if (constraints != null) {
        for (SecurityConstraintMetaData constraint : constraints) {
            WebResourceCollectionsMetaData resourceCollectionsMetaData = constraint.getResourceCollections();
            if (resourceCollectionsMetaData != null) {
                for (WebResourceCollectionMetaData resourceCollectionMetaData : resourceCollectionsMetaData) {
                    List<String> urlPatterns = resourceCollectionMetaData.getUrlPatterns();
                    for (String url : urlPatterns) {
                        int type = getPatternType(url);
                        PatternInfo info = patternMap.get(url);
                        if (info == null) {
                            info = new PatternInfo(url, type);
                            patternMap.put(url, info);
                            switch(type) {
                                case PREFIX:
                                    prefixList.add(info);
                                    break;
                                case EXTENSION:
                                    extensionList.add(info);
                                    break;
                                case EXACT:
                                    exactList.add(info);
                                    break;
                                case DEFAULT:
                                    defaultInfo = info;
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }
    JBossServletsMetaData servlets = metaData.getServlets();
    List<ServletMappingMetaData> mappings = metaData.getServletMappings();
    if (!metaData.isMetadataComplete() && servlets != null && mappings != null) {
        Map<String, List<String>> servletMappingMap = new HashMap<>();
        for (ServletMappingMetaData mapping : mappings) {
            List<String> list = servletMappingMap.get(mapping.getServletName());
            if (list == null) {
                servletMappingMap.put(mapping.getServletName(), list = new ArrayList<>());
            }
            list.addAll(mapping.getUrlPatterns());
        }
        for (JBossServletMetaData servlet : servlets) {
            ServletSecurityMetaData security = servlet.getServletSecurity();
            if (security != null) {
                List<String> servletMappings = servletMappingMap.get(servlet.getServletName());
                if (servletMappings != null) {
                    for (String url : servletMappings) {
                        int type = getPatternType(url);
                        PatternInfo info = patternMap.get(url);
                        if (info == null) {
                            info = new PatternInfo(url, type);
                            patternMap.put(url, info);
                            switch(type) {
                                case PREFIX:
                                    prefixList.add(info);
                                    break;
                                case EXTENSION:
                                    extensionList.add(info);
                                    break;
                                case EXACT:
                                    exactList.add(info);
                                    break;
                                case DEFAULT:
                                    defaultInfo = info;
                                    break;
                            }
                        }
                    }
                }
            }
        }
    }
    // Qualify all prefix patterns
    for (int i = 0; i < prefixList.size(); i++) {
        PatternInfo info = prefixList.get(i);
        // Qualify by every other prefix pattern matching this pattern
        for (int j = 0; j < prefixList.size(); j++) {
            if (i == j)
                continue;
            PatternInfo other = prefixList.get(j);
            if (info.matches(other))
                info.addQualifier(other);
        }
        // Qualify by every exact pattern that is matched by this pattern
        for (PatternInfo other : exactList) {
            if (info.matches(other))
                info.addQualifier(other);
        }
    }
    // Qualify all extension patterns
    for (PatternInfo info : extensionList) {
        // Qualify by every path prefix pattern
        for (PatternInfo other : prefixList) {
            // Any extension
            info.addQualifier(other);
        }
        // Qualify by every matching exact pattern
        for (PatternInfo other : exactList) {
            if (info.isExtensionFor(other))
                info.addQualifier(other);
        }
    }
    // Qualify the default pattern
    if (defaultInfo == null) {
        defaultInfo = new PatternInfo("/", DEFAULT);
        patternMap.put("/", defaultInfo);
    }
    for (PatternInfo info : patternMap.values()) {
        if (info == defaultInfo)
            continue;
        defaultInfo.addQualifier(info);
    }
    return patternMap;
}
Also used : JBossServletsMetaData(org.jboss.metadata.web.jboss.JBossServletsMetaData) HashMap(java.util.HashMap) JBossServletMetaData(org.jboss.metadata.web.jboss.JBossServletMetaData) ArrayList(java.util.ArrayList) ServletSecurityMetaData(org.jboss.metadata.web.spec.ServletSecurityMetaData) SecurityConstraintMetaData(org.jboss.metadata.web.spec.SecurityConstraintMetaData) WebResourceCollectionsMetaData(org.jboss.metadata.web.spec.WebResourceCollectionsMetaData) ServletMappingMetaData(org.jboss.metadata.web.spec.ServletMappingMetaData) ArrayList(java.util.ArrayList) List(java.util.List) WebResourceCollectionMetaData(org.jboss.metadata.web.spec.WebResourceCollectionMetaData)

Aggregations

ArrayList (java.util.ArrayList)3 ServletMappingMetaData (org.jboss.metadata.web.spec.ServletMappingMetaData)3 ServletSecurityMetaData (org.jboss.metadata.web.spec.ServletSecurityMetaData)3 HashMap (java.util.HashMap)2 List (java.util.List)2 JBossServletMetaData (org.jboss.metadata.web.jboss.JBossServletMetaData)2 JBossServletsMetaData (org.jboss.metadata.web.jboss.JBossServletsMetaData)2 HttpMethodConstraintMetaData (org.jboss.metadata.web.spec.HttpMethodConstraintMetaData)2 SecurityConstraintMetaData (org.jboss.metadata.web.spec.SecurityConstraintMetaData)2 WebResourceCollectionMetaData (org.jboss.metadata.web.spec.WebResourceCollectionMetaData)2 WebResourceCollectionsMetaData (org.jboss.metadata.web.spec.WebResourceCollectionsMetaData)2 HashSet (java.util.HashSet)1 Map (java.util.Map)1 Set (java.util.Set)1 WebResourcePermission (javax.security.jacc.WebResourcePermission)1 WebRoleRefPermission (javax.security.jacc.WebRoleRefPermission)1 WebUserDataPermission (javax.security.jacc.WebUserDataPermission)1 Descriptions (org.jboss.annotation.javaee.Descriptions)1 DeploymentUnitProcessingException (org.jboss.as.server.deployment.DeploymentUnitProcessingException)1 AnnotationInstance (org.jboss.jandex.AnnotationInstance)1