dalelane commented on code in PR #1188:
URL:
https://github.com/apache/flink-kubernetes-operator/pull/1188#discussion_r4792893392
##########
flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/artifact/HttpArtifactFetcher.java:
##########
@@ -264,4 +293,112 @@ private static boolean isRedirect(int status) {
|| status == 307 // Temporary Redirect
|| status == 308; // Permanent Redirect
}
+
+ @VisibleForTesting
+ static Optional<InetAddress> validateHop(
+ String uri, Collection<String> allowedSchemes, boolean
disallowRestrictedHosts)
+ throws IOException {
+ var validation =
+ JarUriValidationUtils.validateAndResolve(
+ uri, allowedSchemes, disallowRestrictedHosts);
+ if (validation.error() != null) {
+ throw new IOException(
+ "Refusing to fetch artifact from '" + uri + "': " +
validation.error());
+ }
+ return Optional.ofNullable(validation.checkedAddress());
+ }
+
+ private static Proxy selectProxy(String uri) {
+ var selector = ProxySelector.getDefault();
+ var proxies = selector == null ? List.<Proxy>of() :
selector.select(URI.create(uri));
+ return proxies.isEmpty() ? Proxy.NO_PROXY : proxies.get(0);
+ }
+
+ private static HttpURLConnection openPinnedConnection(URL url, InetAddress
checkedAddress)
+ throws IOException {
+ // Drop the hostname so the JDK cannot resolve it again.
+ var address = InetAddress.getByAddress(checkedAddress.getAddress());
+ if ("https".equalsIgnoreCase(url.getProtocol())) {
+ var conn = (HttpsURLConnection) url.openConnection(Proxy.NO_PROXY);
+ conn.setSSLSocketFactory(
+ new PinnedSSLSocketFactory(conn.getSSLSocketFactory(),
address));
+ return conn;
+ }
+ // Plain HTTP has no socket hook, so treat the address as a proxy
(absolute-form request,
Review Comment:
Routing plain HTTP through the checked address pretending it is a proxy is a
neat trick - I've not seen that done before.
I've been trying to look at what unintended differences this might bring in.
I found a few bits and pieces. It means we'd get a `Proxy-Connection`
keep-alive header instead of a `Connection` header, but I don't think we care
because we don't use that anyway. It means we'd send all requests in
absolute-form (e.g. `GET http://host:port/something.jar` instead of `GET
/something.jar`) but I assume that all servers are okay with this so that
doesn't matter?
I guess I'm essentially asking whether you're confident that there's no
unintended consequences, or other impacts, implications or compatibility
changes we'd pick up because of this.
I've tried searching for some and couldn't come up with anything, but this
is a little out of my wheelhouse!
##########
flink-kubernetes-operator/src/main/java/org/apache/flink/kubernetes/operator/artifact/HttpArtifactFetcher.java:
##########
@@ -93,22 +121,23 @@ public File fetch(
+ uri
+ "'");
}
- var validationError =
- JarUriValidationUtils.validateJarURI(
- currentUri, allowedSchemes,
disallowRestrictedHosts);
- if (validationError.isPresent()) {
- throw new IOException(
- "Refusing to fetch artifact from '"
- + currentUri
- + "': "
- + validationError.get());
- }
+ var pinnedAddress =
+ uriValidator.validate(currentUri, allowedSchemes,
disallowRestrictedHosts);
currentUrl = new URL(currentUri);
if (originalUrl == null) {
originalUrl = currentUrl;
}
- conn = (HttpURLConnection) currentUrl.openConnection();
+ if (pinnedAddress.isEmpty()) {
+ conn = (HttpURLConnection) currentUrl.openConnection();
+ } else {
+ // Only the first proxy is used: the JDK's fallback to DIRECT
would connect by name.
Review Comment:
I think it might be worth adding the proxy behaviour to the docs.
security.md says how disallow-restricted-hosts stops the operator using
cluster-internal endpoints
([ref](https://github.com/apache/flink-kubernetes-operator/blob/main/docs/content/docs/deployment/security.md?plain=1#L66))
But if you're using a proxy, the proxy gets to do the resolution, so the
address that it connects to might not be the one that passes the check.
I don't think that's a problem, but perhaps worth calling out.
##########
flink-kubernetes-operator/src/test/java/org/apache/flink/kubernetes/operator/artifact/HttpArtifactFetcherTest.java:
##########
@@ -0,0 +1,411 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements. See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.
+ * The ASF licenses this file to You 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.apache.flink.kubernetes.operator.artifact;
+
+import org.apache.flink.configuration.Configuration;
+import org.apache.flink.kubernetes.operator.config.FlinkOperatorConfiguration;
+import
org.apache.flink.kubernetes.operator.config.KubernetesOperatorConfigOptions;
+
+import com.sun.net.httpserver.Headers;
+import com.sun.net.httpserver.HttpExchange;
+import com.sun.net.httpserver.HttpHandler;
+import com.sun.net.httpserver.HttpServer;
+import com.sun.net.httpserver.HttpsConfigurator;
+import com.sun.net.httpserver.HttpsExchange;
+import com.sun.net.httpserver.HttpsServer;
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.Timeout;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.ValueSource;
+
+import javax.net.ssl.ExtendedSSLSession;
+import javax.net.ssl.HttpsURLConnection;
+import javax.net.ssl.KeyManagerFactory;
+import javax.net.ssl.SNIHostName;
+import javax.net.ssl.SSLContext;
+import javax.net.ssl.TrustManagerFactory;
+
+import java.io.Closeable;
+import java.io.File;
+import java.io.IOException;
+import java.net.Authenticator;
+import java.net.ConnectException;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.net.PasswordAuthentication;
+import java.net.Proxy;
+import java.net.ProxySelector;
+import java.net.ServerSocket;
+import java.net.Socket;
+import java.net.SocketAddress;
+import java.net.SocketTimeoutException;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Path;
+import java.security.KeyStore;
+import java.time.Duration;
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+import java.util.concurrent.Callable;
+import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.stream.Collectors;
+
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.assertj.core.api.Assertions.assertThatThrownBy;
+
+/** Tests for {@link HttpArtifactFetcher}. */
+class HttpArtifactFetcherTest {
+
+ private static final byte[] ARTIFACT =
"artifact-bytes".getBytes(StandardCharsets.UTF_8);
+ private static final byte[] LOOPBACK_BYTES = {127, 0, 0, 1};
+ private static final char[] KEYSTORE_PASSWORD = "changeit".toCharArray();
+
+ @TempDir Path tempDir;
+
+ private final List<RecordedRequest> requests = new
CopyOnWriteArrayList<>();
+ private final List<HttpServer> servers = new ArrayList<>();
+ private final List<Closeable> sockets = new ArrayList<>();
+ private final RecordingValidator validator = new RecordingValidator();
+ private final HttpArtifactFetcher fetcher = new
HttpArtifactFetcher(validator);
+ private HttpServer server;
+ private int port;
+
+ @BeforeEach
+ void startServer() throws IOException {
+ server = start(HttpServer.create(new InetSocketAddress(loopback(), 0),
0));
+ server.createContext("/job.jar", serveArtifact(requests));
+ port = server.getAddress().getPort();
+ }
+
+ @AfterEach
+ void stopServers() throws IOException {
+ servers.forEach(s -> s.stop(0));
+ for (var socket : sockets) {
+ socket.close();
+ }
+ }
+
+ @Test
+ void connectsToCheckedAddressAndSendsOriginalHost() throws Exception {
+ var file = fetch("http://artifact.invalid:" + port + "/job.jar",
Map.of());
+
+ assertThat(file).hasBinaryContent(ARTIFACT);
+ assertThat(requests).hasSize(1);
+
assertThat(requests.get(0).header("Host")).isEqualTo("artifact.invalid:" +
port);
+ }
+
+ @Test
+ void
validatesAndPinsEachRedirectHopAndDropsConfiguredHeadersOnHostChange() throws
Exception {
Review Comment:
I think a test that redirects between http and https would be useful to add
e.g.
```
@Test
void switching() throws Exception {
var httpsPort = startHttpsServer().getAddress().getPort();
var start = "http://artifact.invalid:" + port + "/start";
var target = "https://artifact.invalid:" + httpsPort + "/job.jar";
server.createContext("/start", exchange -> redirect(exchange, target));
var file = fetchTrustingTestCertificate(start);
}
```
--
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
To unsubscribe, e-mail: [email protected]
For queries about this service, please contact Infrastructure at:
[email protected]