Search in sources :

Example 1 with SecurityConstraintMetaData

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

the class UndertowDeploymentInfoService method createServletConfig.

private DeploymentInfo createServletConfig() throws StartException {
    final ComponentRegistry componentRegistry = this.componentRegistry.get();
    try {
        if (!mergedMetaData.isMetadataComplete()) {
            mergedMetaData.resolveAnnotations();
        }
        mergedMetaData.resolveRunAs();
        final DeploymentInfo d = new DeploymentInfo();
        d.setContextPath(contextPath);
        if (mergedMetaData.getDescriptionGroup() != null) {
            d.setDisplayName(mergedMetaData.getDescriptionGroup().getDisplayName());
        }
        d.setDeploymentName(deploymentName);
        d.setHostName(host.get().getName());
        final ServletContainerService servletContainer = container.get();
        try {
            // TODO: make the caching limits configurable
            List<String> externalOverlays = mergedMetaData.getOverlays();
            ResourceManager resourceManager = new ServletResourceManager(deploymentRoot, overlays, explodedDeployment, mergedMetaData.isSymbolicLinkingEnabled(), servletContainer.isDisableFileWatchService(), externalOverlays);
            resourceManager = new CachingResourceManager(servletContainer.getFileCacheMetadataSize(), servletContainer.getFileCacheMaxFileSize(), servletContainer.getBufferCache(), resourceManager, servletContainer.getFileCacheTimeToLive() == null ? (explodedDeployment ? 2000 : -1) : servletContainer.getFileCacheTimeToLive());
            if (externalResources != null && !externalResources.isEmpty()) {
                // TODO: we don't cache external deployments, as they are intended for development use
                // should be make this configurable or something?
                List<ResourceManager> delegates = new ArrayList<>();
                for (File resource : externalResources) {
                    delegates.add(new FileResourceManager(resource.getCanonicalFile(), 1024, true, mergedMetaData.isSymbolicLinkingEnabled(), "/"));
                }
                delegates.add(resourceManager);
                resourceManager = new DelegatingResourceManager(delegates);
            }
            d.setResourceManager(resourceManager);
        } catch (IOException e) {
            throw new StartException(e);
        }
        d.setTempDir(tempDir);
        d.setClassLoader(module.getClassLoader());
        final String servletVersion = mergedMetaData.getServletVersion();
        if (servletVersion != null) {
            d.setMajorVersion(Integer.parseInt(servletVersion.charAt(0) + ""));
            d.setMinorVersion(Integer.parseInt(servletVersion.charAt(2) + ""));
        } else {
            d.setMajorVersion(3);
            d.setMinorVersion(1);
        }
        d.setDefaultCookieVersion(servletContainer.getDefaultCookieVersion());
        // in most cases flush just hurts performance for no good reason
        d.setIgnoreFlush(servletContainer.isIgnoreFlush());
        // controls initialization of filters on start of application
        d.setEagerFilterInit(servletContainer.isEagerFilterInit());
        d.setAllowNonStandardWrappers(servletContainer.isAllowNonStandardWrappers());
        d.setServletStackTraces(servletContainer.getStackTraces());
        d.setDisableCachingForSecuredPages(servletContainer.isDisableCachingForSecuredPages());
        if (servletContainer.isDisableSessionIdReuse()) {
            d.setCheckOtherSessionManagers(false);
        }
        if (servletContainer.getSessionPersistenceManager() != null) {
            d.setSessionPersistenceManager(servletContainer.getSessionPersistenceManager());
        }
        // for 2.2 apps we do not require a leading / in path mappings
        boolean is22OrOlder;
        if (d.getMajorVersion() == 1) {
            is22OrOlder = true;
        } else if (d.getMajorVersion() == 2) {
            is22OrOlder = d.getMinorVersion() < 3;
        } else {
            is22OrOlder = false;
        }
        JSPConfig jspConfig = servletContainer.getJspConfig();
        final Set<String> seenMappings = new HashSet<>();
        // default Jakarta Server Pages servlet
        final ServletInfo jspServlet = jspConfig != null ? jspConfig.createJSPServletInfo() : null;
        if (jspServlet != null) {
            // this would be null if jsp support is disabled
            HashMap<String, JspPropertyGroup> propertyGroups = createJspConfig(mergedMetaData);
            JspServletBuilder.setupDeployment(d, propertyGroups, tldInfo, new UndertowJSPInstanceManager(new CachingWebInjectionContainer(module.getClassLoader(), componentRegistry)));
            if (mergedMetaData.getJspConfig() != null) {
                Collection<JspPropertyGroup> values = new LinkedHashSet<>(propertyGroups.values());
                d.setJspConfigDescriptor(new JspConfigDescriptorImpl(tldInfo.values(), values));
            }
            d.addServlet(jspServlet);
            final Set<String> jspPropertyGroupMappings = propertyGroups.keySet();
            for (final String mapping : jspPropertyGroupMappings) {
                if (!jspServlet.getMappings().contains(mapping)) {
                    jspServlet.addMapping(mapping);
                }
            }
            seenMappings.addAll(jspPropertyGroupMappings);
            // setup Jakarta Server Pages application context initializing listener
            d.addListener(new ListenerInfo(JspInitializationListener.class));
            d.addServletContextAttribute(JspInitializationListener.CONTEXT_KEY, expressionFactoryWrappers);
        }
        d.setClassIntrospecter(new ComponentClassIntrospector(componentRegistry));
        final Map<String, List<ServletMappingMetaData>> servletMappings = new HashMap<>();
        if (mergedMetaData.getExecutorName() != null) {
            d.setExecutor(executorsByName.get(mergedMetaData.getExecutorName()).get());
        }
        Boolean proactiveAuthentication = mergedMetaData.getProactiveAuthentication();
        if (proactiveAuthentication == null) {
            proactiveAuthentication = container.get().isProactiveAuth();
        }
        d.setAuthenticationMode(proactiveAuthentication ? AuthenticationMode.PRO_ACTIVE : AuthenticationMode.CONSTRAINT_DRIVEN);
        if (servletExtensions != null) {
            for (ServletExtension extension : servletExtensions) {
                d.addServletExtension(extension);
            }
        }
        if (mergedMetaData.getServletMappings() != null) {
            for (final ServletMappingMetaData mapping : mergedMetaData.getServletMappings()) {
                List<ServletMappingMetaData> list = servletMappings.get(mapping.getServletName());
                if (list == null) {
                    servletMappings.put(mapping.getServletName(), list = new ArrayList<>());
                }
                list.add(mapping);
            }
        }
        if (jspServlet != null) {
            // we need to clear the file attribute if it is set (WFLY-4106)
            jspServlet.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(null));
            List<ServletMappingMetaData> list = servletMappings.get(jspServlet.getName());
            if (list != null && !list.isEmpty()) {
                for (final ServletMappingMetaData mapping : list) {
                    for (String urlPattern : mapping.getUrlPatterns()) {
                        jspServlet.addMapping(urlPattern);
                    }
                    seenMappings.addAll(mapping.getUrlPatterns());
                }
            }
        }
        for (final JBossServletMetaData servlet : mergedMetaData.getServlets()) {
            final ServletInfo s;
            if (servlet.getJspFile() != null) {
                s = new ServletInfo(servlet.getName(), JspServlet.class);
                s.addHandlerChainWrapper(JspFileHandler.jspFileHandlerWrapper(servlet.getJspFile()));
            } else {
                if (servlet.getServletClass() == null) {
                    if (DEFAULT_SERVLET_NAME.equals(servlet.getName())) {
                        s = new ServletInfo(servlet.getName(), DefaultServlet.class);
                    } else {
                        throw UndertowLogger.ROOT_LOGGER.servletClassNotDefined(servlet.getServletName());
                    }
                } else {
                    Class<? extends Servlet> servletClass = (Class<? extends Servlet>) module.getClassLoader().loadClass(servlet.getServletClass());
                    ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(servletClass, true);
                    if (creator != null) {
                        InstanceFactory<Servlet> factory = createInstanceFactory(creator);
                        s = new ServletInfo(servlet.getName(), servletClass, factory);
                    } else {
                        s = new ServletInfo(servlet.getName(), servletClass);
                    }
                }
            }
            s.setAsyncSupported(servlet.isAsyncSupported()).setJspFile(servlet.getJspFile()).setEnabled(servlet.isEnabled());
            if (servlet.getRunAs() != null) {
                s.setRunAs(servlet.getRunAs().getRoleName());
            }
            if (servlet.getLoadOnStartupSet()) {
                // todo why not cleanup api and just use int everywhere
                s.setLoadOnStartup(servlet.getLoadOnStartupInt());
            }
            if (servlet.getExecutorName() != null) {
                s.setExecutor(executorsByName.get(servlet.getExecutorName()).get());
            }
            handleServletMappings(is22OrOlder, seenMappings, servletMappings, s);
            if (servlet.getInitParam() != null) {
                for (ParamValueMetaData initParam : servlet.getInitParam()) {
                    if (!s.getInitParams().containsKey(initParam.getParamName())) {
                        s.addInitParam(initParam.getParamName(), initParam.getParamValue());
                    }
                }
            }
            if (servlet.getServletSecurity() != null) {
                ServletSecurityInfo securityInfo = new ServletSecurityInfo();
                s.setServletSecurityInfo(securityInfo);
                securityInfo.setEmptyRoleSemantic(servlet.getServletSecurity().getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT).setTransportGuaranteeType(transportGuaranteeType(servlet.getServletSecurity().getTransportGuarantee())).addRolesAllowed(servlet.getServletSecurity().getRolesAllowed());
                if (servlet.getServletSecurity().getHttpMethodConstraints() != null) {
                    for (HttpMethodConstraintMetaData method : servlet.getServletSecurity().getHttpMethodConstraints()) {
                        securityInfo.addHttpMethodSecurityInfo(new HttpMethodSecurityInfo().setEmptyRoleSemantic(method.getEmptyRoleSemantic() == EmptyRoleSemanticType.DENY ? DENY : PERMIT).setTransportGuaranteeType(transportGuaranteeType(method.getTransportGuarantee())).addRolesAllowed(method.getRolesAllowed()).setMethod(method.getMethod()));
                    }
                }
            }
            if (servlet.getSecurityRoleRefs() != null) {
                for (final SecurityRoleRefMetaData ref : servlet.getSecurityRoleRefs()) {
                    s.addSecurityRoleRef(ref.getRoleName(), ref.getRoleLink());
                }
            }
            if (servlet.getMultipartConfig() != null) {
                MultipartConfigMetaData mp = servlet.getMultipartConfig();
                s.setMultipartConfig(Servlets.multipartConfig(mp.getLocation(), mp.getMaxFileSize(), mp.getMaxRequestSize(), mp.getFileSizeThreshold()));
            }
            d.addServlet(s);
        }
        if (jspServlet != null) {
            if (!seenMappings.contains("*.jsp")) {
                jspServlet.addMapping("*.jsp");
            }
            if (!seenMappings.contains("*.jspx")) {
                jspServlet.addMapping("*.jspx");
            }
        }
        // we explicitly add the default servlet, to allow it to be mapped
        if (!mergedMetaData.getServlets().containsKey(ServletPathMatches.DEFAULT_SERVLET_NAME)) {
            ServletInfo defaultServlet = Servlets.servlet(DEFAULT_SERVLET_NAME, DefaultServlet.class);
            handleServletMappings(is22OrOlder, seenMappings, servletMappings, defaultServlet);
            d.addServlet(defaultServlet);
        }
        if (servletContainer.getDirectoryListingEnabled() != null) {
            ServletInfo defaultServlet = d.getServlets().get(DEFAULT_SERVLET_NAME);
            defaultServlet.addInitParam(DefaultServlet.DIRECTORY_LISTING, servletContainer.getDirectoryListingEnabled().toString());
        }
        if (mergedMetaData.getFilters() != null) {
            for (final FilterMetaData filter : mergedMetaData.getFilters()) {
                Class<? extends Filter> filterClass = (Class<? extends Filter>) module.getClassLoader().loadClass(filter.getFilterClass());
                ManagedReferenceFactory creator = componentRegistry.createInstanceFactory(filterClass);
                FilterInfo f;
                if (creator != null) {
                    InstanceFactory<Filter> instanceFactory = createInstanceFactory(creator);
                    f = new FilterInfo(filter.getName(), filterClass, instanceFactory);
                } else {
                    f = new FilterInfo(filter.getName(), filterClass);
                }
                f.setAsyncSupported(filter.isAsyncSupported());
                d.addFilter(f);
                if (filter.getInitParam() != null) {
                    for (ParamValueMetaData initParam : filter.getInitParam()) {
                        f.addInitParam(initParam.getParamName(), initParam.getParamValue());
                    }
                }
            }
        }
        if (mergedMetaData.getFilterMappings() != null) {
            for (final FilterMappingMetaData mapping : mergedMetaData.getFilterMappings()) {
                if (mapping.getUrlPatterns() != null) {
                    for (String url : mapping.getUrlPatterns()) {
                        if (is22OrOlder && !url.startsWith("*") && !url.startsWith("/")) {
                            url = "/" + url;
                        }
                        if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) {
                            for (DispatcherType dispatcher : mapping.getDispatchers()) {
                                d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.valueOf(dispatcher.name()));
                            }
                        } else {
                            d.addFilterUrlMapping(mapping.getFilterName(), url, javax.servlet.DispatcherType.REQUEST);
                        }
                    }
                }
                if (mapping.getServletNames() != null) {
                    for (String servletName : mapping.getServletNames()) {
                        if (mapping.getDispatchers() != null && !mapping.getDispatchers().isEmpty()) {
                            for (DispatcherType dispatcher : mapping.getDispatchers()) {
                                d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.valueOf(dispatcher.name()));
                            }
                        } else {
                            d.addFilterServletNameMapping(mapping.getFilterName(), servletName, javax.servlet.DispatcherType.REQUEST);
                        }
                    }
                }
            }
        }
        if (scisMetaData != null && scisMetaData.getHandlesTypes() != null) {
            for (final ServletContainerInitializer sci : scisMetaData.getScis()) {
                final ImmediateInstanceFactory<ServletContainerInitializer> instanceFactory = new ImmediateInstanceFactory<>(sci);
                d.addServletContainerInitalizer(new ServletContainerInitializerInfo(sci.getClass(), instanceFactory, scisMetaData.getHandlesTypes().get(sci)));
            }
        }
        if (mergedMetaData.getListeners() != null) {
            Set<String> tldListeners = new HashSet<>();
            for (Map.Entry<String, TagLibraryInfo> e : tldInfo.entrySet()) {
                tldListeners.addAll(Arrays.asList(e.getValue().getListeners()));
            }
            for (ListenerMetaData listener : mergedMetaData.getListeners()) {
                addListener(module.getClassLoader(), componentRegistry, d, listener, tldListeners.contains(listener.getListenerClass()));
            }
        }
        if (mergedMetaData.getContextParams() != null) {
            for (ParamValueMetaData param : mergedMetaData.getContextParams()) {
                d.addInitParameter(param.getParamName(), param.getParamValue());
            }
        }
        if (mergedMetaData.getWelcomeFileList() != null && mergedMetaData.getWelcomeFileList().getWelcomeFiles() != null) {
            List<String> welcomeFiles = mergedMetaData.getWelcomeFileList().getWelcomeFiles();
            for (String file : welcomeFiles) {
                if (file.startsWith("/")) {
                    d.addWelcomePages(file.substring(1));
                } else {
                    d.addWelcomePages(file);
                }
            }
        } else {
            d.addWelcomePages("index.html", "index.htm", "index.jsp");
        }
        d.addWelcomePages(servletContainer.getWelcomeFiles());
        if (mergedMetaData.getErrorPages() != null) {
            for (final ErrorPageMetaData page : mergedMetaData.getErrorPages()) {
                final ErrorPage errorPage;
                if (page.getExceptionType() != null && !page.getExceptionType().isEmpty()) {
                    errorPage = new ErrorPage(page.getLocation(), (Class<? extends Throwable>) module.getClassLoader().loadClass(page.getExceptionType()));
                } else if (page.getErrorCode() != null && !page.getErrorCode().isEmpty()) {
                    errorPage = new ErrorPage(page.getLocation(), Integer.parseInt(page.getErrorCode()));
                } else {
                    errorPage = new ErrorPage(page.getLocation());
                }
                d.addErrorPages(errorPage);
            }
        }
        for (Map.Entry<String, String> entry : servletContainer.getMimeMappings().entrySet()) {
            d.addMimeMapping(new MimeMapping(entry.getKey(), entry.getValue()));
        }
        if (mergedMetaData.getMimeMappings() != null) {
            for (final MimeMappingMetaData mapping : mergedMetaData.getMimeMappings()) {
                d.addMimeMapping(new MimeMapping(mapping.getExtension(), mapping.getMimeType()));
            }
        }
        d.setDenyUncoveredHttpMethods(mergedMetaData.getDenyUncoveredHttpMethods() != null);
        Set<String> securityRoleNames = mergedMetaData.getSecurityRoleNames();
        if (mergedMetaData.getSecurityConstraints() != null) {
            for (SecurityConstraintMetaData constraint : mergedMetaData.getSecurityConstraints()) {
                SecurityConstraint securityConstraint = new SecurityConstraint().setTransportGuaranteeType(transportGuaranteeType(constraint.getTransportGuarantee()));
                List<String> roleNames = constraint.getRoleNames();
                if (constraint.getAuthConstraint() == null) {
                    // no auth constraint means we permit the empty roles
                    securityConstraint.setEmptyRoleSemantic(PERMIT);
                } else if (roleNames.size() == 1 && roleNames.contains("*") && securityRoleNames.contains("*")) {
                    // AS7-6932 - Trying to do a * to * mapping which JBossWeb passed through, for Undertow enable
                    // authentication only mode.
                    // TODO - AS7-6933 - Revisit workaround added to allow switching between JBoss Web and Undertow.
                    securityConstraint.setEmptyRoleSemantic(AUTHENTICATE);
                } else {
                    securityConstraint.addRolesAllowed(roleNames);
                }
                if (constraint.getResourceCollections() != null) {
                    for (final WebResourceCollectionMetaData resourceCollection : constraint.getResourceCollections()) {
                        securityConstraint.addWebResourceCollection(new WebResourceCollection().addHttpMethods(resourceCollection.getHttpMethods()).addHttpMethodOmissions(resourceCollection.getHttpMethodOmissions()).addUrlPatterns(resourceCollection.getUrlPatterns()));
                    }
                }
                d.addSecurityConstraint(securityConstraint);
            }
        }
        final LoginConfigMetaData loginConfig = mergedMetaData.getLoginConfig();
        if (loginConfig != null) {
            List<AuthMethodConfig> authMethod = authMethod(loginConfig.getAuthMethod());
            if (loginConfig.getFormLoginConfig() != null) {
                d.setLoginConfig(new LoginConfig(loginConfig.getRealmName(), loginConfig.getFormLoginConfig().getLoginPage(), loginConfig.getFormLoginConfig().getErrorPage()));
            } else {
                d.setLoginConfig(new LoginConfig(loginConfig.getRealmName()));
            }
            for (AuthMethodConfig method : authMethod) {
                d.getLoginConfig().addLastAuthMethod(method);
            }
        }
        d.addSecurityRoles(mergedMetaData.getSecurityRoleNames());
        Map<String, Set<String>> principalVersusRolesMap = mergedMetaData.getPrincipalVersusRolesMap();
        if (isElytronActive()) {
            Map<String, RunAsIdentityMetaData> runAsIdentityMap = mergedMetaData.getRunAsIdentity();
            applyElytronSecurity(d, runAsIdentityMap::get);
        } else {
            if (securityDomain != null) {
                throw UndertowLogger.ROOT_LOGGER.legacySecurityUnsupported();
            }
        }
        if (principalVersusRolesMap != null) {
            for (Map.Entry<String, Set<String>> entry : principalVersusRolesMap.entrySet()) {
                d.addPrincipalVsRoleMappings(entry.getKey(), entry.getValue());
            }
        }
        // Setup an deployer configured ServletContext attributes
        if (attributes != null) {
            for (ServletContextAttribute attribute : attributes) {
                d.addServletContextAttribute(attribute.getName(), attribute.getValue());
            }
        }
        // now setup websockets if they are enabled
        if (servletContainer.isWebsocketsEnabled() && webSocketDeploymentInfo != null) {
            webSocketDeploymentInfo.setBuffers(servletContainer.getWebsocketsBufferPool());
            webSocketDeploymentInfo.setWorker(servletContainer.getWebsocketsWorker());
            webSocketDeploymentInfo.setDispatchToWorkerThread(servletContainer.isDispatchWebsocketInvocationToWorker());
            if (servletContainer.isPerMessageDeflate()) {
                PerMessageDeflateHandshake perMessageDeflate = new PerMessageDeflateHandshake(false, servletContainer.getDeflaterLevel());
                webSocketDeploymentInfo.addExtension(perMessageDeflate);
            }
            final AtomicReference<ServerActivity> serverActivity = new AtomicReference<>();
            webSocketDeploymentInfo.addListener(wsc -> {
                serverActivity.set(new ServerActivity() {

                    @Override
                    public void preSuspend(ServerActivityCallback listener) {
                        listener.done();
                    }

                    @Override
                    public void suspended(final ServerActivityCallback listener) {
                        if (wsc.getConfiguredServerEndpoints().isEmpty()) {
                            // TODO: remove this once undertow bug fix is upstream
                            listener.done();
                            return;
                        }
                        wsc.pause(new ServerWebSocketContainer.PauseListener() {

                            @Override
                            public void paused() {
                                listener.done();
                            }

                            @Override
                            public void resumed() {
                            }
                        });
                    }

                    @Override
                    public void resume() {
                        wsc.resume();
                    }
                });
                suspendController.get().registerActivity(serverActivity.get());
            });
            ServletContextListener sl = new ServletContextListener() {

                @Override
                public void contextInitialized(ServletContextEvent sce) {
                }

                @Override
                public void contextDestroyed(ServletContextEvent sce) {
                    final ServerActivity activity = serverActivity.get();
                    if (activity != null) {
                        suspendController.get().unRegisterActivity(activity);
                    }
                }
            };
            d.addListener(new ListenerInfo(sl.getClass(), new ImmediateInstanceFactory<EventListener>(sl)));
            d.addServletContextAttribute(WebSocketDeploymentInfo.ATTRIBUTE_NAME, webSocketDeploymentInfo);
        }
        if (mergedMetaData.getLocalEncodings() != null && mergedMetaData.getLocalEncodings().getMappings() != null) {
            for (LocaleEncodingMetaData locale : mergedMetaData.getLocalEncodings().getMappings()) {
                d.addLocaleCharsetMapping(locale.getLocale(), locale.getEncoding());
            }
        }
        if (predicatedHandlers != null && !predicatedHandlers.isEmpty()) {
            d.addOuterHandlerChainWrapper(new RewriteCorrectingHandlerWrappers.PostWrapper());
            d.addOuterHandlerChainWrapper(new HandlerWrapper() {

                @Override
                public HttpHandler wrap(HttpHandler handler) {
                    return Handlers.predicates(predicatedHandlers, handler);
                }
            });
            d.addOuterHandlerChainWrapper(new RewriteCorrectingHandlerWrappers.PreWrapper());
        }
        if (mergedMetaData.getDefaultEncoding() != null) {
            d.setDefaultEncoding(mergedMetaData.getDefaultEncoding());
        } else if (servletContainer.getDefaultEncoding() != null) {
            d.setDefaultEncoding(servletContainer.getDefaultEncoding());
        }
        d.setCrawlerSessionManagerConfig(servletContainer.getCrawlerSessionManagerConfig());
        d.setPreservePathOnForward(servletContainer.isPreservePathOnForward());
        return d;
    } catch (ClassNotFoundException e) {
        throw new StartException(e);
    }
}
Also used : ArrayList(java.util.ArrayList) ServletInfo(io.undertow.servlet.api.ServletInfo) ServletContainerInitializer(javax.servlet.ServletContainerInitializer) ManagedReferenceFactory(org.jboss.as.naming.ManagedReferenceFactory) MultipartConfigMetaData(org.jboss.metadata.web.spec.MultipartConfigMetaData) DefaultServlet(io.undertow.servlet.handlers.DefaultServlet) DispatcherType(org.jboss.metadata.web.spec.DispatcherType) HttpHandler(io.undertow.server.HttpHandler) JSPConfig(org.wildfly.extension.undertow.JSPConfig) ServerActivity(org.jboss.as.server.suspend.ServerActivity) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) WebResourceCollectionMetaData(org.jboss.metadata.web.spec.WebResourceCollectionMetaData) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) HandlerWrapper(io.undertow.server.HandlerWrapper) ServletContextAttribute(org.jboss.as.web.common.ServletContextAttribute) SecurityConstraintMetaData(org.jboss.metadata.web.spec.SecurityConstraintMetaData) FileResourceManager(io.undertow.server.handlers.resource.FileResourceManager) ListenerMetaData(org.jboss.metadata.web.spec.ListenerMetaData) DefaultServlet(io.undertow.servlet.handlers.DefaultServlet) Servlet(javax.servlet.Servlet) JspServlet(org.apache.jasper.servlet.JspServlet) CachingResourceManager(io.undertow.server.handlers.resource.CachingResourceManager) StartException(org.jboss.msc.service.StartException) FilterInfo(io.undertow.servlet.api.FilterInfo) CachingWebInjectionContainer(org.jboss.as.web.common.CachingWebInjectionContainer) LoginConfigMetaData(org.jboss.metadata.web.spec.LoginConfigMetaData) ServletContainerInitializerInfo(io.undertow.servlet.api.ServletContainerInitializerInfo) FilterMetaData(org.jboss.metadata.web.spec.FilterMetaData) ServletContainerService(org.wildfly.extension.undertow.ServletContainerService) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) HttpMethodSecurityInfo(io.undertow.servlet.api.HttpMethodSecurityInfo) LocaleEncodingMetaData(org.jboss.metadata.web.spec.LocaleEncodingMetaData) ImmediateInstanceFactory(io.undertow.servlet.util.ImmediateInstanceFactory) ServerActivityCallback(org.jboss.as.server.suspend.ServerActivityCallback) LinkedHashSet(java.util.LinkedHashSet) WebResourceCollection(io.undertow.servlet.api.WebResourceCollection) ErrorPage(io.undertow.servlet.api.ErrorPage) LinkedHashMap(java.util.LinkedHashMap) HashMap(java.util.HashMap) ServletContextListener(javax.servlet.ServletContextListener) JspPropertyGroup(org.apache.jasper.deploy.JspPropertyGroup) AuthMethodConfig(io.undertow.servlet.api.AuthMethodConfig) ArrayList(java.util.ArrayList) List(java.util.List) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) FilterMappingMetaData(org.jboss.metadata.web.spec.FilterMappingMetaData) ParamValueMetaData(org.jboss.metadata.javaee.spec.ParamValueMetaData) ErrorPageMetaData(org.jboss.metadata.web.spec.ErrorPageMetaData) ResourceManager(io.undertow.server.handlers.resource.ResourceManager) CachingResourceManager(io.undertow.server.handlers.resource.CachingResourceManager) FileResourceManager(io.undertow.server.handlers.resource.FileResourceManager) MimeMappingMetaData(org.jboss.metadata.web.spec.MimeMappingMetaData) ServletMappingMetaData(org.jboss.metadata.web.spec.ServletMappingMetaData) ListenerInfo(io.undertow.servlet.api.ListenerInfo) File(java.io.File) VirtualFile(org.jboss.vfs.VirtualFile) ServletSecurityInfo(io.undertow.servlet.api.ServletSecurityInfo) JBossServletMetaData(org.jboss.metadata.web.jboss.JBossServletMetaData) SecurityConstraint(io.undertow.servlet.api.SecurityConstraint) RunAsIdentityMetaData(org.jboss.metadata.javaee.jboss.RunAsIdentityMetaData) LoginConfig(io.undertow.servlet.api.LoginConfig) DeploymentInfo(io.undertow.servlet.api.DeploymentInfo) WebSocketDeploymentInfo(io.undertow.websockets.jsr.WebSocketDeploymentInfo) TagLibraryInfo(org.apache.jasper.deploy.TagLibraryInfo) MimeMapping(io.undertow.servlet.api.MimeMapping) JspServlet(org.apache.jasper.servlet.JspServlet) HttpMethodConstraintMetaData(org.jboss.metadata.web.spec.HttpMethodConstraintMetaData) SecurityRoleRefMetaData(org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData) ComponentRegistry(org.jboss.as.ee.component.ComponentRegistry) Filter(javax.servlet.Filter) PerMessageDeflateHandshake(io.undertow.websockets.extensions.PerMessageDeflateHandshake) ServletExtension(io.undertow.servlet.ServletExtension) ServletContextEvent(javax.servlet.ServletContextEvent)

Example 2 with SecurityConstraintMetaData

use of org.jboss.metadata.web.spec.SecurityConstraintMetaData 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 3 with SecurityConstraintMetaData

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

the class WebMetaDataCreator method createSecurityConstraints.

/**
 * Creates security constraints part of web.xml descriptor.
 * <p/>
 * <pre>
 * &lt;security-constraint&gt;
 *   &lt;web-resource-collection&gt;
 *     &lt;web-resource-name&gt;EJBEndpointShortName&lt;/web-resource-name&gt;
 *     &lt;url-pattern&gt;EJBEndpointURLPattern&lt;/url-pattern&gt;
 *     &lt;http-method&gt;GET&lt;/http-method&gt;
 *     &lt;http-method&gt;POST&lt;/http-method&gt;
 *   &lt;/web-resource-collection&gt;
 *   &lt;auth-constraint&gt;
 *     &lt;role-name&gt;*&lt;/role-name&gt;
 *   &lt;/auth-constraint&gt;
 *   &lt;user-data-constraint&gt;
 *     &lt;transport-guarantee&gt;EjbTransportGuarantee&lt;/transport-guarantee&gt;
 *   &lt;/user-data-constraint&gt;
 * &lt;/security-constraint&gt;
 * </pre>
 *
 * @param dep        webservice deployment
 * @param jbossWebMD jboss web meta data
 */
private void createSecurityConstraints(final Deployment dep, final JBossWebMetaData jbossWebMD) {
    WSLogger.ROOT_LOGGER.trace("Creating security constraints");
    for (final Endpoint ejbEndpoint : dep.getService().getEndpoints()) {
        final boolean secureWsdlAccess = ejb3SecurityAccessor.isSecureWsdlAccess(ejbEndpoint);
        final String transportGuarantee = ejb3SecurityAccessor.getTransportGuarantee(ejbEndpoint);
        final boolean hasTransportGuarantee = transportGuarantee != null;
        final String authMethod = ejb3SecurityAccessor.getAuthMethod(ejbEndpoint);
        final boolean hasAuthMethod = authMethod != null;
        if (ejbEndpoint instanceof HttpEndpoint && (hasAuthMethod || hasTransportGuarantee)) {
            final List<SecurityConstraintMetaData> securityConstraints = WebMetaDataHelper.getSecurityConstraints(jbossWebMD);
            // security-constraint
            final SecurityConstraintMetaData securityConstraint = WebMetaDataHelper.newSecurityConstraint(securityConstraints);
            // web-resource-collection
            final WebResourceCollectionsMetaData webResourceCollections = WebMetaDataHelper.getWebResourceCollections(securityConstraint);
            final String endpointName = ejbEndpoint.getShortName();
            final String urlPattern = ((HttpEndpoint) ejbEndpoint).getURLPattern();
            WSLogger.ROOT_LOGGER.tracef("Creating web resource collection for endpoint: %s, URL pattern: %s", endpointName, urlPattern);
            WebMetaDataHelper.newWebResourceCollection(endpointName, urlPattern, secureWsdlAccess, webResourceCollections);
            // auth-constraint
            if (hasAuthMethod) {
                WSLogger.ROOT_LOGGER.tracef("Creating auth constraint for endpoint: %s", endpointName);
                WebMetaDataHelper.newAuthConstraint(WebMetaDataHelper.getAllRoles(), securityConstraint);
            }
            // user-data-constraint
            if (hasTransportGuarantee) {
                WSLogger.ROOT_LOGGER.tracef("Creating new user data constraint for endpoint: %s, transport guarantee: %s", endpointName, transportGuarantee);
                WebMetaDataHelper.newUserDataConstraint(transportGuarantee, securityConstraint);
            }
        }
    }
}
Also used : WebResourceCollectionsMetaData(org.jboss.metadata.web.spec.WebResourceCollectionsMetaData) HttpEndpoint(org.jboss.wsf.spi.deployment.HttpEndpoint) Endpoint(org.jboss.wsf.spi.deployment.Endpoint) HttpEndpoint(org.jboss.wsf.spi.deployment.HttpEndpoint) SecurityConstraintMetaData(org.jboss.metadata.web.spec.SecurityConstraintMetaData)

Example 4 with SecurityConstraintMetaData

use of org.jboss.metadata.web.spec.SecurityConstraintMetaData 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)

Example 5 with SecurityConstraintMetaData

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

the class WebMetaDataHelper method newSecurityConstraint.

/**
 * Creates new security constraint meta data and associates them with security constraints meta data.
 *
 * @param securityConstraintsMD security constraints meta data
 * @return new security constraing meta data
 */
public static SecurityConstraintMetaData newSecurityConstraint(final List<SecurityConstraintMetaData> securityConstraintsMD) {
    final SecurityConstraintMetaData securityConstraintMD = new SecurityConstraintMetaData();
    securityConstraintsMD.add(securityConstraintMD);
    return securityConstraintMD;
}
Also used : SecurityConstraintMetaData(org.jboss.metadata.web.spec.SecurityConstraintMetaData)

Aggregations

SecurityConstraintMetaData (org.jboss.metadata.web.spec.SecurityConstraintMetaData)6 WebResourceCollectionMetaData (org.jboss.metadata.web.spec.WebResourceCollectionMetaData)4 ArrayList (java.util.ArrayList)3 HashMap (java.util.HashMap)3 List (java.util.List)3 JBossServletMetaData (org.jboss.metadata.web.jboss.JBossServletMetaData)3 ServletMappingMetaData (org.jboss.metadata.web.spec.ServletMappingMetaData)3 WebResourceCollectionsMetaData (org.jboss.metadata.web.spec.WebResourceCollectionsMetaData)3 HashSet (java.util.HashSet)2 Map (java.util.Map)2 Set (java.util.Set)2 SecurityRoleRefMetaData (org.jboss.metadata.javaee.spec.SecurityRoleRefMetaData)2 HttpMethodConstraintMetaData (org.jboss.metadata.web.spec.HttpMethodConstraintMetaData)2 HandlerWrapper (io.undertow.server.HandlerWrapper)1 HttpHandler (io.undertow.server.HttpHandler)1 CachingResourceManager (io.undertow.server.handlers.resource.CachingResourceManager)1 FileResourceManager (io.undertow.server.handlers.resource.FileResourceManager)1 ResourceManager (io.undertow.server.handlers.resource.ResourceManager)1 ServletExtension (io.undertow.servlet.ServletExtension)1 AuthMethodConfig (io.undertow.servlet.api.AuthMethodConfig)1