Skip to content
Open
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -5,96 +5,39 @@

package org.opensearch.ml.common.httpclient;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import static org.opensearch.secure_sm.AccessController.doPrivileged;

import java.time.Duration;
import java.util.Arrays;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;

import org.opensearch.common.util.concurrent.ThreadContextAccess;

import lombok.extern.log4j.Log4j2;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;
import software.amazon.awssdk.http.nio.netty.NettyNioAsyncHttpClient;

@Log4j2
public class MLHttpClientFactory {

public static SdkAsyncHttpClient getAsyncHttpClient(Duration connectionTimeout, Duration readTimeout, int maxConnections) {
return ThreadContextAccess
.doPrivileged(
() -> NettyNioAsyncHttpClient
.builder()
.connectionTimeout(connectionTimeout)
.readTimeout(readTimeout)
.maxConcurrency(maxConnections)
.build()
);
}

/**
* Validate the input parameters, such as protocol, host and port.
* @param protocol The protocol supported in remote inference, currently only http and https are supported.
* @param host The host name of the remote inference server, host must be a valid ip address or domain name and must not be localhost.
* @param port The port number of the remote inference server, port number must be in range [0, 65536].
* @param connectorPrivateIpEnabled The port number of the remote inference server, port number must be in range [0, 65536].
* @throws UnknownHostException Allow to use private IP or not.
*/
public static void validate(String protocol, String host, int port, AtomicBoolean connectorPrivateIpEnabled)
throws UnknownHostException {
if (protocol != null && !"http".equalsIgnoreCase(protocol) && !"https".equalsIgnoreCase(protocol)) {
log.error("Remote inference protocol is not http or https: {}", protocol);
throw new IllegalArgumentException("Protocol is not http or https: " + protocol);
}
// When port is not specified, the default port is -1, and we need to set it to 80 or 443 based on protocol.
if (port == -1) {
if (protocol == null || "http".equals(protocol.toLowerCase(Locale.getDefault()))) {
port = 80;
} else {
port = 443;
}
}
if (port < 0 || port > 65536) {
log.error("Remote inference port out of range: {}", port);
throw new IllegalArgumentException("Port out of range: " + port);
}
validateIp(host, connectorPrivateIpEnabled);
}

private static void validateIp(String hostName, AtomicBoolean connectorPrivateIpEnabled) throws UnknownHostException {
InetAddress[] addresses = InetAddress.getAllByName(hostName);
if ((connectorPrivateIpEnabled == null || !connectorPrivateIpEnabled.get()) && hasPrivateIpAddress(addresses)) {
log.error("Remote inference host name has private ip address: {}", hostName);
throw new IllegalArgumentException("Remote inference host name has private ip address: " + hostName);
}
}

private static boolean hasPrivateIpAddress(InetAddress[] ipAddress) {
for (InetAddress ip : ipAddress) {
if (ip instanceof Inet4Address) {
byte[] bytes = ip.getAddress();
if (bytes.length != 4) {
return true;
} else {
if (isPrivateIPv4(bytes)) {
return true;
}
}
}
}
return Arrays.stream(ipAddress).anyMatch(x -> x.isSiteLocalAddress() || x.isLoopbackAddress() || x.isAnyLocalAddress());
}

private static boolean isPrivateIPv4(byte[] bytes) {
int first = bytes[0] & 0xff;
int second = bytes[1] & 0xff;

// 127.0.0.1, 10.x.x.x, 172.16-31.x.x, 192.168.x.x, 169.254.x.x
return (first == 10)
|| (first == 172 && second >= 16 && second <= 31)
|| (first == 192 && second == 168)
|| (first == 169 && second == 254);
public static SdkAsyncHttpClient getAsyncHttpClient(
Duration connectionTimeout,
Duration readTimeout,
int maxConnections,
AtomicBoolean connectorPrivateIpEnabled
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we use bool here? what's the reason to use atomicBoolean

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree that boolean is better, I tried to change all the occurrence of this connectorPrivateIpEnabled to boolean all the way back to where it's defined, but there's more UTs need to be changed. But changing to boolean is correct direction, let me try again this change.

) {
return doPrivileged(() -> {
log
.debug(
"Creating MLHttpClient with connectionTimeout: {}, readTimeout: {}, maxConnections: {}",
connectionTimeout,
readTimeout,
maxConnections
);
SdkAsyncHttpClient delegate = NettyNioAsyncHttpClient
.builder()
.connectionTimeout(connectionTimeout)
.readTimeout(readTimeout)
.maxConcurrency(maxConnections)
.build();
return new ValidatingHttpClient(delegate, connectorPrivateIpEnabled);
});
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
/*
* Copyright OpenSearch Contributors
* SPDX-License-Identifier: Apache-2.0
*/

package org.opensearch.ml.common.httpclient;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;
import java.util.Locale;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.atomic.AtomicBoolean;

import lombok.extern.log4j.Log4j2;
import software.amazon.awssdk.http.async.AsyncExecuteRequest;
import software.amazon.awssdk.http.async.SdkAsyncHttpClient;

@Log4j2
public class ValidatingHttpClient implements SdkAsyncHttpClient {
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggest use a better class name.

private final SdkAsyncHttpClient delegate;
private final AtomicBoolean connectorPrivateIpEnabled;

protected ValidatingHttpClient(SdkAsyncHttpClient client, AtomicBoolean connectorPrivateIpEnabled) {
this.delegate = client;
this.connectorPrivateIpEnabled = connectorPrivateIpEnabled;
}

@Override
public CompletableFuture<Void> execute(AsyncExecuteRequest request) {
String protocol = request.request().protocol();
String host = request.request().host();
int port = request.request().port();
try {
validate(protocol, host, port, connectorPrivateIpEnabled);
return delegate.execute(request);
} catch (Exception e) {
log.error("Failed to validate request!", e);
throw new IllegalArgumentException(e.getMessage(), e);
}
}

@Override
public void close() {
delegate.close();
}

/**
* Validate the input parameters, such as protocol, host and port.
* @param protocol The protocol supported in remote inference, currently only http and https are supported.
* @param host The host name of the remote inference server, host must be a valid ip address or domain name and must not be localhost.
* @param port The port number of the remote inference server, port number must be in range [0, 65536].
* @param connectorPrivateIpEnabled The port number of the remote inference server, port number must be in range [0, 65536].
* @throws UnknownHostException Allow to use private IP or not.
*/
public void validate(String protocol, String host, int port, AtomicBoolean connectorPrivateIpEnabled) throws UnknownHostException {
if (protocol != null && !"http".equalsIgnoreCase(protocol) && !"https".equalsIgnoreCase(protocol)) {
log.error("Remote inference protocol is not http or https: {}", protocol);
throw new IllegalArgumentException("Protocol is not http or https: " + protocol);
}
// When port is not specified, the default port is -1, and we need to set it to 80 or 443 based on protocol.
if (port == -1) {
if (protocol == null || "http".equals(protocol.toLowerCase(Locale.getDefault()))) {
port = 80;
} else {
port = 443;
}
}
if (port < 0 || port > 65536) {
log.error("Remote inference port out of range: {}", port);
throw new IllegalArgumentException("Port out of range: " + port);
}
validateIp(host, connectorPrivateIpEnabled);
}

private void validateIp(String hostName, AtomicBoolean connectorPrivateIpEnabled) throws UnknownHostException {
InetAddress[] addresses = InetAddress.getAllByName(hostName);
if (connectorPrivateIpEnabled != null && !connectorPrivateIpEnabled.get() && hasPrivateIpAddress(addresses)) {
log.error("Remote inference host name has private ip address: {}", hostName);
throw new IllegalArgumentException("Remote inference host name has private ip address: " + hostName);
}
}

private boolean hasPrivateIpAddress(InetAddress[] ipAddress) {
for (InetAddress ip : ipAddress) {
if (ip instanceof Inet4Address) {
byte[] bytes = ip.getAddress();
if (bytes.length != 4) {
return true;
} else {
if (isPrivateIPv4(bytes)) {
return true;
}
}
}
}
return Arrays.stream(ipAddress).anyMatch(x -> x.isSiteLocalAddress() || x.isLoopbackAddress() || x.isAnyLocalAddress());
}

private boolean isPrivateIPv4(byte[] bytes) {
int first = bytes[0] & 0xff;
int second = bytes[1] & 0xff;

// 127.0.0.1, 10.x.x.x, 172.16-31.x.x, 192.168.x.x, 169.254.x.x
return (first == 10)
|| (first == 172 && second >= 16 && second <= 31)
|| (first == 192 && second == 168)
|| (first == 169 && second == 254);
}
}
Loading
Loading