use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project wildfly by wildfly.
the class MicroProfileMetricsSecuredEndpointTestCase method securedHTTPEndpoint.
@Test
public void securedHTTPEndpoint() throws Exception {
final String endpointURL = "http://" + managementClient.getMgmtAddress() + ":" + managementClient.getMgmtPort() + "/metrics";
try (CloseableHttpClient client = HttpClients.createDefault()) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testSuite", "testSuitePassword"));
HttpClientContext hcContext = HttpClientContext.create();
hcContext.setCredentialsProvider(credentialsProvider);
CloseableHttpResponse resp = client.execute(new HttpGet(endpointURL), hcContext);
assertEquals(200, resp.getStatusLine().getStatusCode());
String content = EntityUtils.toString(resp.getEntity());
resp.close();
// MicroProfile Metrics 2.0 has changed its Prometheus conversion format from "base:x" to "base_x"
String expectedMetric = "base_jvm_uptime_seconds";
assertTrue(expectedMetric + " metric is expected in the response", content.contains(expectedMetric));
}
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project wildfly by wildfly.
the class BootCheckApplication method invoke.
private Response invoke(final String url) throws IOException {
HttpClientBuilder builder = HttpClients.custom();
builder.setDefaultRequestConfig(RequestConfig.copy(RequestConfig.DEFAULT).setConnectTimeout(5000).build());
builder.setDefaultSocketConfig(SocketConfig.copy(SocketConfig.DEFAULT).setSoTimeout(5000).build());
try (CloseableHttpClient client = builder.build()) {
CredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("testSuite", "testSuitePassword"));
HttpClientContext hcContext = HttpClientContext.create();
hcContext.setCredentialsProvider(credentialsProvider);
CloseableHttpResponse resp = client.execute(new HttpGet(url), hcContext);
int respCode = resp.getStatusLine().getStatusCode();
HttpEntity entity = resp.getEntity();
String content = entity == null ? null : EntityUtils.toString(entity);
resp.close();
return new Response(respCode, content);
}
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project platform_external_apache-http by android.
the class DefaultRequestDirector method createTunnelToTarget.
// establishConnection
/**
* Creates a tunnel to the target server.
* The connection must be established to the (last) proxy.
* A CONNECT request for tunnelling through the proxy will
* be created and sent, the response received and checked.
* This method does <i>not</i> update the connection with
* information about the tunnel, that is left to the caller.
*
* @param route the route to establish
* @param context the context for request execution
*
* @return <code>true</code> if the tunnelled route is secure,
* <code>false</code> otherwise.
* The implementation here always returns <code>false</code>,
* but derived classes may override.
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
protected boolean createTunnelToTarget(HttpRoute route, HttpContext context) throws HttpException, IOException {
HttpHost proxy = route.getProxyHost();
HttpHost target = route.getTargetHost();
HttpResponse response = null;
boolean done = false;
while (!done) {
done = true;
if (!this.managedConn.isOpen()) {
this.managedConn.open(route, context, this.params);
}
HttpRequest connect = createConnectRequest(route, context);
String agent = HttpProtocolParams.getUserAgent(params);
if (agent != null) {
connect.addHeader(HTTP.USER_AGENT, agent);
}
connect.addHeader(HTTP.TARGET_HOST, target.toHostString());
AuthScheme authScheme = this.proxyAuthState.getAuthScheme();
AuthScope authScope = this.proxyAuthState.getAuthScope();
Credentials creds = this.proxyAuthState.getCredentials();
if (creds != null) {
if (authScope != null || !authScheme.isConnectionBased()) {
try {
connect.addHeader(authScheme.authenticate(creds, connect));
} catch (AuthenticationException ex) {
if (this.log.isErrorEnabled()) {
this.log.error("Proxy authentication error: " + ex.getMessage());
}
}
}
}
response = requestExec.execute(connect, this.managedConn, context);
int status = response.getStatusLine().getStatusCode();
if (status < 200) {
throw new HttpException("Unexpected response to CONNECT request: " + response.getStatusLine());
}
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
this.log.debug("Proxy requested authentication");
Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
try {
processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
break;
}
}
updateAuthState(this.proxyAuthState, proxy, credsProvider);
if (this.proxyAuthState.getCredentials() != null) {
done = false;
// Retry request
if (this.reuseStrategy.keepAlive(response, context)) {
this.log.debug("Connection kept alive");
// Consume response content
HttpEntity entity = response.getEntity();
if (entity != null) {
entity.consumeContent();
}
} else {
this.managedConn.close();
}
}
} else {
// Reset proxy auth scope
this.proxyAuthState.setAuthScope(null);
}
}
}
int status = response.getStatusLine().getStatusCode();
if (status > 299) {
// Buffer response content
HttpEntity entity = response.getEntity();
if (entity != null) {
response.setEntity(new BufferedHttpEntity(entity));
}
this.managedConn.close();
throw new TunnelRefusedException("CONNECT refused by proxy: " + response.getStatusLine(), response);
}
this.managedConn.markReusable();
// Leave it to derived classes, consider insecure by default here.
return false;
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project platform_external_apache-http by android.
the class DefaultRequestDirector method handleResponse.
/**
* Analyzes a response to check need for a followup.
*
* @param roureq the request and route.
* @param response the response to analayze
* @param context the context used for the current request execution
*
* @return the followup request and route if there is a followup, or
* <code>null</code> if the response should be returned as is
*
* @throws HttpException in case of a problem
* @throws IOException in case of an IO problem
*/
protected RoutedRequest handleResponse(RoutedRequest roureq, HttpResponse response, HttpContext context) throws HttpException, IOException {
HttpRoute route = roureq.getRoute();
HttpHost proxy = route.getProxyHost();
RequestWrapper request = roureq.getRequest();
HttpParams params = request.getParams();
if (HttpClientParams.isRedirecting(params) && this.redirectHandler.isRedirectRequested(response, context)) {
if (redirectCount >= maxRedirects) {
throw new RedirectException("Maximum redirects (" + maxRedirects + ") exceeded");
}
redirectCount++;
URI uri = this.redirectHandler.getLocationURI(response, context);
HttpHost newTarget = new HttpHost(uri.getHost(), uri.getPort(), uri.getScheme());
HttpGet redirect = new HttpGet(uri);
HttpRequest orig = request.getOriginal();
redirect.setHeaders(orig.getAllHeaders());
RequestWrapper wrapper = new RequestWrapper(redirect);
wrapper.setParams(params);
HttpRoute newRoute = determineRoute(newTarget, wrapper, context);
RoutedRequest newRequest = new RoutedRequest(wrapper, newRoute);
if (this.log.isDebugEnabled()) {
this.log.debug("Redirecting to '" + uri + "' via " + newRoute);
}
return newRequest;
}
CredentialsProvider credsProvider = (CredentialsProvider) context.getAttribute(ClientContext.CREDS_PROVIDER);
if (credsProvider != null && HttpClientParams.isAuthenticating(params)) {
if (this.targetAuthHandler.isAuthenticationRequested(response, context)) {
HttpHost target = (HttpHost) context.getAttribute(ExecutionContext.HTTP_TARGET_HOST);
if (target == null) {
target = route.getTargetHost();
}
this.log.debug("Target requested authentication");
Map<String, Header> challenges = this.targetAuthHandler.getChallenges(response, context);
try {
processChallenges(challenges, this.targetAuthState, this.targetAuthHandler, response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
return null;
}
}
updateAuthState(this.targetAuthState, target, credsProvider);
if (this.targetAuthState.getCredentials() != null) {
// Re-try the same request via the same route
return roureq;
} else {
return null;
}
} else {
// Reset target auth scope
this.targetAuthState.setAuthScope(null);
}
if (this.proxyAuthHandler.isAuthenticationRequested(response, context)) {
this.log.debug("Proxy requested authentication");
Map<String, Header> challenges = this.proxyAuthHandler.getChallenges(response, context);
try {
processChallenges(challenges, this.proxyAuthState, this.proxyAuthHandler, response, context);
} catch (AuthenticationException ex) {
if (this.log.isWarnEnabled()) {
this.log.warn("Authentication error: " + ex.getMessage());
return null;
}
}
updateAuthState(this.proxyAuthState, proxy, credsProvider);
if (this.proxyAuthState.getCredentials() != null) {
// Re-try the same request via the same route
return roureq;
} else {
return null;
}
} else {
// Reset proxy auth scope
this.proxyAuthState.setAuthScope(null);
}
}
return null;
}
use of org.graylog.shaded.elasticsearch7.org.apache.http.client.CredentialsProvider in project midpoint by Evolveum.
the class SmsMessageTransport method send.
@Override
public void send(Message message, String transportName, Event event, Task task, OperationResult parentResult) {
OperationResult result = parentResult.createSubresult(DOT_CLASS + "send");
result.addArbitraryObjectCollectionAsParam("message recipient(s)", message.getTo());
result.addParam("message subject", message.getSubject());
String logToFile = configuration.getLogToFile();
if (logToFile != null) {
TransportUtil.logToFile(logToFile, TransportUtil.formatToFileNew(message, transportName), LOGGER);
}
String file = configuration.getRedirectToFile();
int optionsForFilteringRecipient = TransportUtil.optionsForFilteringRecipient(configuration);
List<String> allowedRecipientTo = new ArrayList<>();
List<String> forbiddenRecipientTo = new ArrayList<>();
if (optionsForFilteringRecipient != 0) {
TransportUtil.validateRecipient(allowedRecipientTo, forbiddenRecipientTo, message.getTo(), configuration, task, result, transportSupport.expressionFactory(), MiscSchemaUtil.getExpressionProfile(), LOGGER);
if (file != null) {
if (!forbiddenRecipientTo.isEmpty()) {
message.setTo(forbiddenRecipientTo);
writeToFile(message, file, null, emptyList(), null, result);
}
message.setTo(allowedRecipientTo);
}
} else if (file != null) {
writeToFile(message, file, null, emptyList(), null, result);
return;
}
if (configuration.getGateway().isEmpty()) {
String msg = "SMS gateway(s) are not defined, notification to " + message.getTo() + " will not be sent.";
LOGGER.warn(msg);
result.recordWarning(msg);
return;
}
String from;
if (message.getFrom() != null) {
from = message.getFrom();
} else if (configuration.getDefaultFrom() != null) {
from = configuration.getDefaultFrom();
} else {
from = "";
}
if (message.getTo().isEmpty()) {
if (optionsForFilteringRecipient != 0) {
String msg = "After recipient validation there is no recipient to send the notification to.";
LOGGER.debug(msg);
result.recordSuccess();
} else {
String msg = "There is no recipient to send the notification to.";
LOGGER.warn(msg);
result.recordWarning(msg);
}
return;
}
List<String> to = message.getTo();
assert to.size() > 0;
for (SmsGatewayConfigurationType smsGatewayConfigurationType : configuration.getGateway()) {
OperationResult resultForGateway = result.createSubresult(DOT_CLASS + "send.forGateway");
resultForGateway.addContext("gateway name", smsGatewayConfigurationType.getName());
try {
VariablesMap variables = getDefaultVariables(from, to, message);
HttpMethodType method = defaultIfNull(smsGatewayConfigurationType.getMethod(), HttpMethodType.GET);
ExpressionType urlExpression = defaultIfNull(smsGatewayConfigurationType.getUrlExpression(), null);
String url = evaluateExpressionChecked(urlExpression, variables, "sms gateway request url", task, result);
String proxyHost = smsGatewayConfigurationType.getProxyHost();
String proxyPort = smsGatewayConfigurationType.getProxyPort();
LOGGER.debug("Sending SMS to URL {} via proxy host {} and port {} (method {})", url, proxyHost, proxyPort, method);
if (url == null) {
throw new IllegalArgumentException("No URL specified");
}
List<String> headersList = evaluateExpressionsChecked(smsGatewayConfigurationType.getHeadersExpression(), variables, "sms gateway request headers", task, result);
LOGGER.debug("Using request headers:\n{}", headersList);
String encoding = defaultIfNull(smsGatewayConfigurationType.getBodyEncoding(), StandardCharsets.ISO_8859_1.name());
String body = evaluateExpressionChecked(smsGatewayConfigurationType.getBodyExpression(), variables, "sms gateway request body", task, result);
LOGGER.debug("Using request body text (encoding: {}):\n{}", encoding, body);
if (smsGatewayConfigurationType.getLogToFile() != null) {
TransportUtil.logToFile(smsGatewayConfigurationType.getLogToFile(), formatToFile(message, url, headersList, body), LOGGER);
}
if (smsGatewayConfigurationType.getRedirectToFile() != null) {
writeToFile(message, smsGatewayConfigurationType.getRedirectToFile(), url, headersList, body, resultForGateway);
result.computeStatus();
return;
} else {
HttpClientBuilder builder = HttpClientBuilder.create();
String username = smsGatewayConfigurationType.getUsername();
ProtectedStringType password = smsGatewayConfigurationType.getPassword();
CredentialsProvider provider = new BasicCredentialsProvider();
if (username != null) {
String plainPassword = password != null ? transportSupport.protector().decryptString(password) : null;
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(username, plainPassword);
provider.setCredentials(AuthScope.ANY, credentials);
builder = builder.setDefaultCredentialsProvider(provider);
}
String proxyUsername = smsGatewayConfigurationType.getProxyUsername();
ProtectedStringType proxyPassword = smsGatewayConfigurationType.getProxyPassword();
if (StringUtils.isNotBlank(proxyHost)) {
HttpHost proxy;
if (StringUtils.isNotBlank(proxyPort) && isInteger(proxyPort)) {
int port = Integer.parseInt(proxyPort);
proxy = new HttpHost(proxyHost, port);
} else {
proxy = new HttpHost(proxyHost);
}
if (StringUtils.isNotBlank(proxyUsername)) {
String plainProxyPassword = proxyPassword != null ? transportSupport.protector().decryptString(proxyPassword) : null;
UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(proxyUsername, plainProxyPassword);
provider.setCredentials(new AuthScope(proxy), credentials);
}
builder = builder.setDefaultCredentialsProvider(provider);
builder = builder.setProxy(proxy);
}
HttpClient client = builder.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(client);
ClientHttpRequest request = requestFactory.createRequest(new URI(url), HttpUtil.toHttpMethod(method));
setHeaders(request, headersList);
if (body != null) {
request.getBody().write(body.getBytes(encoding));
}
ClientHttpResponse response = request.execute();
LOGGER.debug("Result: " + response.getStatusCode() + "/" + response.getStatusText());
if (response.getStatusCode().series() != HttpStatus.Series.SUCCESSFUL) {
throw new SystemException("SMS gateway communication failed: " + response.getStatusCode() + ": " + response.getStatusText());
}
LOGGER.debug("Message sent successfully to {} via gateway {}.", message.getTo(), smsGatewayConfigurationType.getName());
resultForGateway.recordSuccess();
result.recordSuccess();
return;
}
} catch (Throwable t) {
String msg = "Couldn't send SMS to " + message.getTo() + " via " + smsGatewayConfigurationType.getName() + ", trying another gateway, if there is any";
LoggingUtils.logException(LOGGER, msg, t);
resultForGateway.recordFatalError(msg, t);
}
}
LOGGER.warn("No more SMS gateways to try, notification to " + message.getTo() + " will not be sent.");
result.recordWarning("Notification to " + message.getTo() + " could not be sent.");
}
Aggregations