Java 类org.elasticsearch.common.settings.SecureString 实例源码

项目:elasticsearch_my    文件:InternalAwsS3Service.java   
public static AWSCredentialsProvider buildCredentials(Logger logger, DeprecationLogger deprecationLogger,
                                                      Settings settings, Settings repositorySettings, String clientName) {
    try (SecureString key = getConfigValue(repositorySettings, settings, clientName, S3Repository.ACCESS_KEY_SETTING,
                                           S3Repository.Repository.KEY_SETTING, S3Repository.Repositories.KEY_SETTING);
         SecureString secret = getConfigValue(repositorySettings, settings, clientName, S3Repository.SECRET_KEY_SETTING,
                                              S3Repository.Repository.SECRET_SETTING, S3Repository.Repositories.SECRET_SETTING)) {

        if (key.length() == 0 && secret.length() == 0) {
            logger.debug("Using instance profile credentials");
            return new PrivilegedInstanceProfileCredentialsProvider();
        } else {
            logger.debug("Using basic key/secret credentials");
            return new StaticCredentialsProvider(new BasicAWSCredentials(key.toString(), secret.toString()));
        }
    }
}
项目:shield-custom-realm-example    文件:CustomCachingRealm.java   
/**
 * Method that handles the actual authentication of the token. This method will only be called if the token is a
 * supported token. The method validates the credentials of the user and if they match, a {@link User} will be
 * returned as the argument to the {@code listener}'s {@link ActionListener#onResponse(Object)} method. Else
 * {@code null} is returned.
 * @param authenticationToken the token to authenticate
 * @param listener return authentication result by calling {@link ActionListener#onResponse(Object)}
 */
@Override
public void authenticate(AuthenticationToken authenticationToken, ActionListener<AuthenticationResult> listener) {
    try {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        UserHolder userHolder = cache.get(token.principal());
        // NOTE the null check for the password. This is done because a cache is shared between authentication and lookup
        // lookup will not store the password...
        if (userHolder == null || userHolder.password == null) {
            super.authenticate(token, ActionListener.wrap(authenticationResult -> {
                if (authenticationResult.isAuthenticated()) {
                    cache.put(token.principal(),
                            new UserHolder(token.credentials().clone().getChars(), authenticationResult.getUser()));
                }
                listener.onResponse(authenticationResult);
            }, listener::onFailure));
        } else if (token.credentials().equals(new SecureString(userHolder.password))) {
            listener.onResponse(AuthenticationResult.success(userHolder.user));
        } else {
            listener.onResponse(AuthenticationResult.notHandled());
        }
    } catch (Exception e) {
        listener.onFailure(e);
    }
}
项目:shield-custom-realm-example    文件:CustomRealmTests.java   
public void testAuthenticateBadUser() {
    Settings globalSettings = Settings.builder().put("path.home", createTempDir()).build();
    Settings realmSettings = Settings.builder()
            .put("type", CustomRealm.TYPE)
            .put("users.john.password", "doe")
            .put("users.john.roles", "user")
            .put("users.jane.password", "test")
            .putList("users.jane.roles", "user", "admin")
            .build();

    CustomRealm realm = new CustomRealm(new RealmConfig("test", realmSettings, globalSettings,
            new Environment(globalSettings, createTempDir()), new ThreadContext(globalSettings)));
    UsernamePasswordToken token =
            new UsernamePasswordToken("john1", new SecureString(randomAlphaOfLengthBetween(4, 16).toCharArray()));
    realm.authenticate(token, ActionListener.wrap(result -> {
        assertFalse(result.isAuthenticated());
        assertThat(result.getUser(), nullValue());
    }, e -> fail("Failed with exception: " + e.getMessage())));
}
项目:elasticsearch_my    文件:InternalSettingsPreparerTests.java   
public void testSecureSettings() {
    MockSecureSettings secureSettings = new MockSecureSettings();
    secureSettings.setString("foo", "secret");
    Settings input = Settings.builder().put(baseEnvSettings).setSecureSettings(secureSettings).build();
    Environment env = InternalSettingsPreparer.prepareEnvironment(input, null);
    Setting<SecureString> fakeSetting = SecureSetting.secureString("foo", null, false);
    assertEquals("secret", fakeSetting.get(env.settings()).toString());
}
项目:elasticsearch_my    文件:S3RepositoryTests.java   
public void testSettingsResolution() throws Exception {
    Settings localSettings = Settings.builder().put(Repository.KEY_SETTING.getKey(), "key1").build();
    Settings globalSettings = Settings.builder().put(Repositories.KEY_SETTING.getKey(), "key2").build();

    assertEquals(new SecureString("key1".toCharArray()),
                 getValue(localSettings, globalSettings, Repository.KEY_SETTING, Repositories.KEY_SETTING));
    assertEquals(new SecureString("key1".toCharArray()),
                 getValue(localSettings, Settings.EMPTY, Repository.KEY_SETTING, Repositories.KEY_SETTING));
    assertEquals(new SecureString("key2".toCharArray()),
                 getValue(Settings.EMPTY, globalSettings, Repository.KEY_SETTING, Repositories.KEY_SETTING));
    assertEquals(new SecureString("".toCharArray()),
                 getValue(Settings.EMPTY, Settings.EMPTY, Repository.KEY_SETTING, Repositories.KEY_SETTING));
    assertSettingDeprecationsAndWarnings(new Setting<?>[]{Repository.KEY_SETTING, Repositories.KEY_SETTING});
}
项目:shield-custom-realm-example    文件:CustomRealm.java   
/**
 * This method will extract a token from the given {@link RestRequest} if possible. This implementation of token
 * extraction looks for two headers, the <code>User</code> header for the username and the <code>Password</code>
 * header for the plaintext password
 * @param threadContext the {@link ThreadContext} that contains headers and transient objects for a request
 * @return the {@link AuthenticationToken} if possible to extract or <code>null</code>
 */
@Override
public UsernamePasswordToken token(ThreadContext threadContext) {
    String user = threadContext.getHeader(USER_HEADER);
    if (user != null) {
        String password = threadContext.getHeader(PW_HEADER);
        if (password != null) {
            return new UsernamePasswordToken(user, new SecureString(password.toCharArray()));
        }
    }
    return null;
}
项目:elasticsearch_my    文件:InternalAwsS3Service.java   
static ClientConfiguration buildConfiguration(Logger logger, Settings repositorySettings, Settings settings,
                                                     String clientName, Integer maxRetries, String endpoint,
                                                     boolean useThrottleRetries) {
    ClientConfiguration clientConfiguration = new ClientConfiguration();
    // the response metadata cache is only there for diagnostics purposes,
    // but can force objects from every response to the old generation.
    clientConfiguration.setResponseMetadataCacheSize(0);
    Protocol protocol = getConfigValue(repositorySettings, settings, clientName, S3Repository.PROTOCOL_SETTING,
                                       S3Repository.Repository.PROTOCOL_SETTING, S3Repository.Repositories.PROTOCOL_SETTING);
    clientConfiguration.setProtocol(protocol);

    String proxyHost = getConfigValue(null, settings, clientName,
                                      S3Repository.PROXY_HOST_SETTING, null, CLOUD_S3.PROXY_HOST_SETTING);
    if (Strings.hasText(proxyHost)) {
        Integer proxyPort = getConfigValue(null, settings, clientName,
                                           S3Repository.PROXY_PORT_SETTING, null, CLOUD_S3.PROXY_PORT_SETTING);
        try (SecureString proxyUsername = getConfigValue(null, settings, clientName,
                                                         S3Repository.PROXY_USERNAME_SETTING, null, CLOUD_S3.PROXY_USERNAME_SETTING);
             SecureString proxyPassword = getConfigValue(null, settings, clientName,
                                                         S3Repository.PROXY_PASSWORD_SETTING, null, CLOUD_S3.PROXY_PASSWORD_SETTING)) {

            clientConfiguration
                .withProxyHost(proxyHost)
                .withProxyPort(proxyPort)
                .withProxyUsername(proxyUsername.toString())
                .withProxyPassword(proxyPassword.toString());
        }
    }

    if (maxRetries != null) {
        // If not explicitly set, default to 3 with exponential backoff policy
        clientConfiguration.setMaxErrorRetry(maxRetries);
    }
    clientConfiguration.setUseThrottleRetries(useThrottleRetries);

    // #155: we might have 3rd party users using older S3 API version
    String awsSigner = CLOUD_S3.SIGNER_SETTING.get(settings);
    if (Strings.hasText(awsSigner)) {
        logger.debug("using AWS API signer [{}]", awsSigner);
        AwsSigner.configureSigner(awsSigner, clientConfiguration, endpoint);
    }

    TimeValue readTimeout = getConfigValue(null, settings, clientName,
                                           S3Repository.READ_TIMEOUT_SETTING, null, CLOUD_S3.READ_TIMEOUT);
    clientConfiguration.setSocketTimeout((int)readTimeout.millis());

    return clientConfiguration;
}