<commit_before>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.wildfly.security.auth.client;

import static org.wildfly.security._private.ElytronMessages.log;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.function.UnaryOperator;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslClientFactory;
import javax.security.sasl.SaslException;

import org.wildfly.common.Assert;
import org.wildfly.security.SecurityFactory;
import org.wildfly.security.auth.principal.AnonymousPrincipal;
import org.wildfly.security.permission.ElytronPermission;

/**
 * A client for consuming authentication context configurations.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public final class AuthenticationContextConfigurationClient {

    private static final ElytronPermission CREATE_PERMISSION = new ElytronPermission("createAuthenticationContextConfigurationClient");

    /**
     * A reusable privileged action to create a new configuration client.
     */
    public static final PrivilegedAction<AuthenticationContextConfigurationClient> ACTION = AuthenticationContextConfigurationClient::new;

    /**
     * Construct a new instance.
     *
     * @throws SecurityException if the caller does not have permission to instantiate this class
     */
    public AuthenticationContextConfigurationClient() throws SecurityException {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(CREATE_PERMISSION);
        }
    }

    /**
     * Get the authentication configuration which matches the given URI, or {@link AuthenticationConfiguration#EMPTY} if there is none.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @return the matching configuration
     */
    public AuthenticationConfiguration getAuthenticationConfiguration(URI uri, AuthenticationContext authenticationContext) {
        return getAuthenticationConfiguration(uri, authenticationContext, -1);
    }

    /**
     * Get the authentication configuration which matches the given URI, or {@link AuthenticationConfiguration#EMPTY} if there is none, setting
     * a default protocol port.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @param protocolDefaultPort the protocol-default port
     * @return the matching configuration
     */
    public AuthenticationConfiguration getAuthenticationConfiguration(URI uri, AuthenticationContext authenticationContext, int protocolDefaultPort) {
        return getAuthenticationConfiguration(uri, authenticationContext, protocolDefaultPort, null, null);
    }

    /**
     * Get the authentication configuration which matches the given URI and type, or {@link AuthenticationConfiguration#EMPTY} if there is none, setting
     * a default protocol port.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @param protocolDefaultPort the protocol-default port
     * @param abstractType the abstract type (may be {@code null})
     * @param abstractTypeAuthority the abstract type authority (may be {@code null})
     * @return the matching configuration
     */
    public AuthenticationConfiguration getAuthenticationConfiguration(URI uri, AuthenticationContext authenticationContext, int protocolDefaultPort, String abstractType, String abstractTypeAuthority) {
        Assert.checkNotNullParam("uri", uri);
        Assert.checkNotNullParam("authenticationContext", authenticationContext);
        final RuleNode<AuthenticationConfiguration> node = authenticationContext.authRuleMatching(uri, abstractType, abstractTypeAuthority);
        AuthenticationConfiguration configuration = node != null ? node.getConfiguration() : AuthenticationConfiguration.empty();
        final String uriHost = uri.getHost();
        if (uriHost != null && configuration.setHost == null) {
            configuration = configuration.useHost(uriHost);
        }
        int port = uri.getPort();
        if (port == -1) port = protocolDefaultPort;
        if (port != -1 && configuration.setPort == -1) {
            // use the URI port in this configuration
            configuration = configuration.usePort(port);
        }
        final String userInfo = uri.getUserInfo();
        if (userInfo != null && configuration.getPrincipal() == AnonymousPrincipal.getInstance()) {
            configuration = configuration.useName(userInfo);
        }

        log.tracef("getAuthenticationConfiguration uri=%s, protocolDefaultPort=%d, abstractType=%s, abstractTypeAuthority=%s, MatchRule=[%s], AuthenticationConfiguration=[%s]",
                uri, protocolDefaultPort, abstractType, abstractTypeAuthority, node != null ? node.rule : null, configuration);

        return configuration;
    }

    /**
     * Get the SSL context which matches the given URI, or {@link SSLContext#getDefault()} if there is none.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @return the matching SSL context
     */
    public SSLContext getSSLContext(URI uri, AuthenticationContext authenticationContext) throws GeneralSecurityException {
        return getSSLContext(uri, authenticationContext, null, null);
    }

    /**
     * Get the SSL context which matches the given URI and type, or {@link SSLContext#getDefault()} if there is none.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @param abstractType the abstract type (may be {@code null})
     * @param abstractTypeAuthority the abstract type authority (may be {@code null})
     * @return the matching SSL context
     */
    public SSLContext getSSLContext(URI uri, AuthenticationContext authenticationContext, String abstractType, String abstractTypeAuthority) throws GeneralSecurityException {
        return getSSLContextFactory(uri, authenticationContext, abstractType, abstractTypeAuthority).create();
    }

    /**
     * Get the SSL context factory which matches the given URI and type, or {@link SSLContext#getDefault()} if there is none.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @param abstractType the abstract type (may be {@code null})
     * @param abstractTypeAuthority the abstract type authority (may be {@code null})
     * @return the matching SSL context factory (not {@code null})
     */
    public SecurityFactory<SSLContext> getSSLContextFactory(URI uri, AuthenticationContext authenticationContext, String abstractType, String abstractTypeAuthority) {
        Assert.checkNotNullParam("uri", uri);
        Assert.checkNotNullParam("authenticationContext", authenticationContext);
        final RuleNode<SecurityFactory<SSLContext>> node = authenticationContext.sslRuleMatching(uri, abstractType, abstractTypeAuthority);
        if (node == null) return SSLContext::getDefault;
        return node.getConfiguration();
    }

    /**
     * Get an authentication callback handler for the given configuration.
     *
     * @param configuration the configuration (must not be {@code null})
     * @return the callback handler
     */
    public CallbackHandler getCallbackHandler(AuthenticationConfiguration configuration) {
        Assert.checkNotNullParam("configuration", configuration);
        final CallbackHandler callbackHandler = configuration.getUserCallbackHandler();
        return callbackHandler == null ? configuration.createCallbackHandler() : callbackHandler;
    }

    /**
     * Get the actual host to use for the given configuration and URI.
     *
     * @param uri the URI (must not be {@code null})
     * @param configuration the configuration (must not be {@code null})
     * @return the real host to use
     */
    public String getRealHost(URI uri, AuthenticationConfiguration configuration) {
        Assert.checkNotNullParam("uri", uri);
        Assert.checkNotNullParam("configuration", configuration);<commit_msg>Revert "Revert "[ELT-1213] Temporarily restore removed methods for compatibility.""<commit_after>/*
 * JBoss, Home of Professional Open Source.
 * Copyright 2014 Red Hat, Inc., and individual contributors
 * as indicated by the @author tags.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.wildfly.security.auth.client;

import static org.wildfly.security._private.ElytronMessages.log;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.security.Principal;
import java.security.PrivilegedAction;
import java.util.Collection;
import java.util.function.UnaryOperator;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.security.auth.callback.CallbackHandler;
import javax.security.sasl.SaslClient;
import javax.security.sasl.SaslClientFactory;
import javax.security.sasl.SaslException;

import org.wildfly.common.Assert;
import org.wildfly.security.SecurityFactory;
import org.wildfly.security.auth.principal.AnonymousPrincipal;
import org.wildfly.security.permission.ElytronPermission;

/**
 * A client for consuming authentication context configurations.
 *
 * @author <a href="mailto:<EMAIL>"><NAME></a>
 */
public final class AuthenticationContextConfigurationClient {

    private static final ElytronPermission CREATE_PERMISSION = new ElytronPermission("createAuthenticationContextConfigurationClient");

    /**
     * A reusable privileged action to create a new configuration client.
     */
    public static final PrivilegedAction<AuthenticationContextConfigurationClient> ACTION = AuthenticationContextConfigurationClient::new;

    /**
     * Construct a new instance.
     *
     * @throws SecurityException if the caller does not have permission to instantiate this class
     */
    public AuthenticationContextConfigurationClient() throws SecurityException {
        final SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(CREATE_PERMISSION);
        }
    }

    /**
     * Get the authentication configuration which matches the given URI, or {@link AuthenticationConfiguration#EMPTY} if there is none.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @return the matching configuration
     */
    public AuthenticationConfiguration getAuthenticationConfiguration(URI uri, AuthenticationContext authenticationContext) {
        return getAuthenticationConfiguration(uri, authenticationContext, -1);
    }

    /**
     * Get the authentication configuration which matches the given URI, or {@link AuthenticationConfiguration#EMPTY} if there is none, setting
     * a default protocol port.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @param protocolDefaultPort the protocol-default port
     * @return the matching configuration
     */
    public AuthenticationConfiguration getAuthenticationConfiguration(URI uri, AuthenticationContext authenticationContext, int protocolDefaultPort) {
        return getAuthenticationConfiguration(uri, authenticationContext, protocolDefaultPort, null, null);
    }

    /**
     * Get the authentication configuration which matches the given URI and type, or {@link AuthenticationConfiguration#EMPTY} if there is none, setting
     * a default protocol port.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @param protocolDefaultPort the protocol-default port
     * @param abstractType the abstract type (may be {@code null})
     * @param abstractTypeAuthority the abstract type authority (may be {@code null})
     * @return the matching configuration
     */
    public AuthenticationConfiguration getAuthenticationConfiguration(URI uri, AuthenticationContext authenticationContext, int protocolDefaultPort, String abstractType, String abstractTypeAuthority) {
        Assert.checkNotNullParam("uri", uri);
        Assert.checkNotNullParam("authenticationContext", authenticationContext);
        final RuleNode<AuthenticationConfiguration> node = authenticationContext.authRuleMatching(uri, abstractType, abstractTypeAuthority);
        AuthenticationConfiguration configuration = node != null ? node.getConfiguration() : AuthenticationConfiguration.empty();
        final String uriHost = uri.getHost();
        if (uriHost != null && configuration.setHost == null) {
            configuration = configuration.useHost(uriHost);
        }
        int port = uri.getPort();
        if (port == -1) port = protocolDefaultPort;
        if (port != -1 && configuration.setPort == -1) {
            // use the URI port in this configuration
            configuration = configuration.usePort(port);
        }
        final String userInfo = uri.getUserInfo();
        if (userInfo != null && configuration.getPrincipal() == AnonymousPrincipal.getInstance()) {
            configuration = configuration.useName(userInfo);
        }

        log.tracef("getAuthenticationConfiguration uri=%s, protocolDefaultPort=%d, abstractType=%s, abstractTypeAuthority=%s, MatchRule=[%s], AuthenticationConfiguration=[%s]",
                uri, protocolDefaultPort, abstractType, abstractTypeAuthority, node != null ? node.rule : null, configuration);

        return configuration;
    }

    @Deprecated
    public AuthenticationConfiguration getAuthenticationConfiguration(URI uri, AuthenticationContext authenticationContext, int protocolDefaultPort, String abstractType, String abstractTypeAuthority, String purpose) {
        return getAuthenticationConfiguration(uri, authenticationContext, protocolDefaultPort, abstractType, abstractTypeAuthority);
    }

    /**
     * Get the SSL context which matches the given URI, or {@link SSLContext#getDefault()} if there is none.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @return the matching SSL context
     */
    public SSLContext getSSLContext(URI uri, AuthenticationContext authenticationContext) throws GeneralSecurityException {
        return getSSLContext(uri, authenticationContext, null, null);
    }

    /**
     * Get the SSL context which matches the given URI and type, or {@link SSLContext#getDefault()} if there is none.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @param abstractType the abstract type (may be {@code null})
     * @param abstractTypeAuthority the abstract type authority (may be {@code null})
     * @return the matching SSL context
     */
    public SSLContext getSSLContext(URI uri, AuthenticationContext authenticationContext, String abstractType, String abstractTypeAuthority) throws GeneralSecurityException {
        return getSSLContextFactory(uri, authenticationContext, abstractType, abstractTypeAuthority).create();
    }

    @Deprecated
    public SSLContext getSSLContext(URI uri, AuthenticationContext authenticationContext, String abstractType, String abstractTypeAuthority, String purpose) throws GeneralSecurityException {
        return getSSLContext(uri, authenticationContext, abstractType, abstractTypeAuthority);
    }

    /**
     * Get the SSL context factory which matches the given URI and type, or {@link SSLContext#getDefault()} if there is none.
     *
     * @param uri the URI to match (must not be {@code null})
     * @param authenticationContext the authentication context to examine (must not be {@code null})
     * @param abstractType the abstract type (may be {@code null})
     * @param abstractTypeAuthority the abstract type authority (may be {@code null})
     * @return the matching SSL context factory (not {@code null})
     */
    public SecurityFactory<SSLContext> getSSLContextFactory(URI uri, AuthenticationContext authenticationContext, String abstractType, String abstractTypeAuthority) {
        Assert.checkNotNullParam("uri", uri);
        Assert.checkNotNullParam("authenticationContext", authenticationContext);
        final RuleNode<SecurityFactory<SSLContext>> node = authenticationContext.sslRuleMatching(uri, abstractType, abstractTypeAuthority);
        if (node == null) return SSLContext::getDefault;
        return node.getConfiguration();
    }

    @Deprecated
    public SecurityFactory<SSLContext> getSSLContextFactory(URI uri, AuthenticationContext authenticationContext, String abstractType, String abstractTypeAuthority, String purpose) {
        return getSSLContextFactory(uri, authenticationContext, abstractType, abstractTypeAuthority);
    }

    /**
     * Get an authentication callback handler for the given configuration.
     *
     * @param configuration the configuration (must not be {@code null})
     * @return the callback handler
     */
    public CallbackHandler getCallbackHandler(AuthenticationConfiguration configuration) {
        Assert.checkNotNullParam("configuration", configuration);
        final CallbackHandler callbackHandler = configuration.getUserCallbackHandler();
        return callbackHandler == null ? configuration.createCallbackHandler() : callbackHandler;
    }

    /**
     * Get the actual host to use for the given configuration and URI.
     *
     * @param uri the URI (must not be {@code null})
     * @param configuration the configuration (must not be {@code null})
     * @return the real host to use
     */
    public String getRealHost(URI uri, AuthenticationConfiguration configuration) {
        Assert.checkNotNullParam("uri", uri);
        Assert.checkNotNullParam("configuration", configuration);
{'fraction_non_alphanumeric': 0.08124032556049333, 'fraction_numerical': 0.0013981125480601187, 'mean_word_length': 4.008252063015754, 'pattern_counts': {'":': 0, '<': 22, '<?xml version=': 0, '>': 22, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '381398', 'n_tokens_mistral': 4677, 'n_tokens_neox': 4607, 'n_words': 1688}