fix:"修复媒体下载DNS重绑定并隔离出站传输"

This commit is contained in:
xpp committed 2026-10-21 22:49:57 +08:00
1 parent 926aa64ba3
commit 32f6f67b9f
15 files changed
+791 -56

No files matched your search

@@ -0,0 +1,59 @@
package com.moyi.controlplane.provider.media;
import com.moyi.controlplane.common.ApiException;
import com.moyi.controlplane.provider.transport.BoundedHttpTransport;
import com.moyi.controlplane.provider.transport.PinnedHttpsTransport;
import java.time.Duration;
import java.util.Locale;
/** Public reference-image input only. No provider credentials, routing, retries or billing. */
public final class MediaDownloader {
private static final int MAX_BYTES = 8 * 1024 * 1024;
private final PublicMediaAddressPolicy policy = new PublicMediaAddressPolicy();
private final PinnedHttpsTransport transport;
private final PinnedHttpsTransport.AddressResolver resolver;
public MediaDownloader() { this(new PinnedHttpsTransport(), new PublicMediaAddressPolicy()::resolve); }
MediaDownloader(PinnedHttpsTransport transport, PinnedHttpsTransport.AddressResolver resolver) {
this.transport = transport;
this.resolver = resolver;
}
public record MediaBytes(byte[] bytes, String contentType, String filename) {
@Override public String toString() { return "MediaBytes[type=" + contentType + ", bytes=" + bytes.length + "]"; }
}
public MediaBytes download(String value) {
java.net.URI uri;
try { uri = policy.requireUri(value); }
catch (IllegalArgumentException error) { throw invalidAddress(); }
BoundedHttpTransport.Response response;
try { response = transport.get(uri, resolver, Duration.ofSeconds(15), MAX_BYTES); }
catch (BoundedHttpTransport.Failure failure) {
if (failure.reason() == BoundedHttpTransport.Reason.INVALID_ADDRESS) throw invalidAddress();
if (failure.reason() == BoundedHttpTransport.Reason.BODY_TOO_LARGE) throw new ApiException("MEDIA_TOO_LARGE", "媒体输入超过 8 MiB", 400);
throw new ApiException("MEDIA_FETCH_FAILED", "无法在期限内读取媒体输入", 400);
}
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new ApiException("MEDIA_FETCH_FAILED", "无法读取媒体输入(HTTP " + response.statusCode() + ")", 400);
}
if (response.body().length == 0) throw new ApiException("MEDIA_TOO_LARGE", "媒体输入为空或超过 8 MiB", 400);
String contentType = response.headers().firstValue("Content-Type").orElse("application/octet-stream")
.split(";", 2)[0].trim().toLowerCase(Locale.ROOT);
if (!contentType.matches("image/[a-z0-9.+-]{1,64}")) {
throw new ApiException("MEDIA_TYPE_UNSUPPORTED", "图像编辑和视频参考图必须是 image/* 文件", 400);
}
String extension = switch (contentType) {
case "image/jpeg" -> ".jpg";
case "image/png" -> ".png";
case "image/webp" -> ".webp";
case "image/gif" -> ".gif";
default -> ".bin";
};
return new MediaBytes(response.body(), contentType, "input" + extension);
}
private ApiException invalidAddress() {
return new ApiException("INVALID_MEDIA_URL", "媒体地址必须是公开 HTTPS 地址,不能指向本机、内网或特殊用途地址", 400);
}
}
@@ -0,0 +1,53 @@
package com.moyi.controlplane.provider.media;
import com.moyi.controlplane.provider.transport.PinnedHttpsTransport;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
/** Fail closed for non-global and special-purpose targets, including mixed DNS answer sets. */
final class PublicMediaAddressPolicy {
URI requireUri(String value) {
try {
URI uri = URI.create(value);
if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null || uri.getHost().contains("%")
|| uri.getUserInfo() != null || uri.getRawFragment() != null || uri.getPort() == 0 || uri.getPort() > 65535) {
throw new IllegalArgumentException();
}
return uri;
} catch (RuntimeException error) { throw new IllegalArgumentException("Invalid public HTTPS media URL"); }
}
InetAddress[] resolve(String host) throws IOException {
return requirePublic(InetAddress.getAllByName(host));
}
InetAddress[] requirePublic(InetAddress[] addresses) throws PinnedHttpsTransport.AddressRejectedException {
if (addresses == null || addresses.length == 0 || addresses.length > 16) throw new PinnedHttpsTransport.AddressRejectedException();
for (var address : addresses) if (address == null || !isPublic(address)) throw new PinnedHttpsTransport.AddressRejectedException();
return addresses.clone();
}
boolean isPublic(InetAddress address) {
byte[] raw = address.getAddress();
int a = Byte.toUnsignedInt(raw[0]), b = Byte.toUnsignedInt(raw[1]);
if (raw.length == 4) {
int c = Byte.toUnsignedInt(raw[2]), d = Byte.toUnsignedInt(raw[3]);
return !(a == 0 || a == 10 || a == 127 || a >= 224
|| a == 100 && b >= 64 && b <= 127
|| a == 169 && b == 254 || a == 172 && b >= 16 && b <= 31
|| a == 192 && (b == 168 || b == 0 && (c == 0 || c == 2) || b == 88 && c == 99)
|| a == 198 && (b == 18 || b == 19 || b == 51 && c == 100)
|| a == 203 && b == 0 && c == 113
|| a == 168 && b == 63 && c == 129 && d == 16); // Azure platform virtual address
}
// Only native global unicast 2000::/3, excluding special/tunnel/documentation prefixes.
// This also rejects ULA, link/site local, multicast, compatible/mapped IPv4 and well-known NAT64.
if (raw.length != 16 || (a & 0xe0) != 0x20) return false;
int c = Byte.toUnsignedInt(raw[2]), d = Byte.toUnsignedInt(raw[3]);
return !(a == 0x20 && b == 0x01 && (c <= 1 || c == 0x0d && d == 0xb8)
|| a == 0x20 && b == 0x02 // 6to4 can encode a private IPv4 target
|| a == 0x3f && b == 0xfe // retired 6bone allocation
|| a == 0x3f && b == 0xff && (c & 0xf0) == 0); // 3fff::/20 documentation
}
}
@@ -27,11 +27,11 @@ public final class BoundedHttpTransport {
public record Response(int statusCode, HttpHeaders headers, byte[] body) {
@Override public String toString() { return "TransportResponse[status=" + statusCode + ", bytes=" + body.length + "]"; }
}
public enum Reason { TIMEOUT, INTERRUPTED, BODY_TOO_LARGE, IO }
public enum Reason { TIMEOUT, INTERRUPTED, BODY_TOO_LARGE, IO, INVALID_ADDRESS, BUSY }
public static final class Failure extends IOException {
private final Reason reason;
private final Integer observedStatus;
private Failure(Reason reason, Integer status) {
Failure(Reason reason, Integer status) {
super("Bounded HTTP attempt failed: " + reason);
this.reason = reason; this.observedStatus = status;
}
@@ -0,0 +1,187 @@
package com.moyi.controlplane.provider.transport;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Proxy;
import java.net.Socket;
import java.net.URI;
import java.net.UnknownHostException;
import java.net.http.HttpHeaders;
import java.time.Duration;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import javax.net.ssl.SSLContext;
import org.apache.hc.client5.http.DnsResolver;
import org.apache.hc.client5.http.classic.methods.HttpGet;
import org.apache.hc.client5.http.config.ConnectionConfig;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.config.TlsConfig;
import org.apache.hc.client5.http.impl.DefaultSchemePortResolver;
import org.apache.hc.client5.http.impl.classic.HttpClients;
import org.apache.hc.client5.http.impl.io.BasicHttpClientConnectionManager;
import org.apache.hc.client5.http.impl.io.DefaultHttpClientConnectionOperator;
import org.apache.hc.client5.http.impl.io.ManagedHttpClientConnectionFactory;
import org.apache.hc.client5.http.impl.routing.DefaultRoutePlanner;
import org.apache.hc.client5.http.ssl.DefaultClientTlsStrategy;
import org.apache.hc.client5.http.ssl.DefaultHostnameVerifier;
import org.apache.hc.client5.http.ssl.HostnameVerificationPolicy;
import org.apache.hc.core5.http.config.Http1Config;
import org.apache.hc.core5.io.CloseMode;
import org.apache.hc.core5.ssl.SSLContexts;
import org.apache.hc.core5.util.Timeout;
import static com.moyi.controlplane.provider.transport.BoundedHttpTransport.Reason;
/**
* A credential-free HTTPS GET with per-attempt DNS binding. The caller supplies address policy;
* this module owns only bounded transport. Never rewrite the URI to an IP: TLS/SNI and Host use
* the original authority. No proxy, cookies, redirects, retry or connection reuse across attempts.
*/
public final class PinnedHttpsTransport {
private static final ExecutorService WORKERS = new ThreadPoolExecutor(0, 8, 60, TimeUnit.SECONDS,
new SynchronousQueue<>(), task -> {
var thread = new Thread(task, "moyi-media-fetch");
thread.setDaemon(true);
return thread;
}, new ThreadPoolExecutor.AbortPolicy());
private final SSLContext sslContext;
private final ExecutorService workers;
public PinnedHttpsTransport() { this(SSLContexts.createDefault(), WORKERS); }
PinnedHttpsTransport(SSLContext sslContext, ExecutorService workers) {
this.sslContext = sslContext;
this.workers = workers;
}
@FunctionalInterface
public interface AddressResolver { InetAddress[] resolve(String host) throws IOException; }
public static final class AddressRejectedException extends IOException {
public AddressRejectedException() { super("Target address rejected"); }
}
public BoundedHttpTransport.Response get(URI uri, AddressResolver resolver, Duration deadline, int maxBytes)
throws BoundedHttpTransport.Failure {
if (uri == null || !"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null
|| uri.getUserInfo() != null || uri.getRawFragment() != null || uri.getHost().contains("%")
|| uri.getPort() == 0 || uri.getPort() > 65535) throw new IllegalArgumentException("Invalid HTTPS target");
if (maxBytes < 1 || maxBytes > 32 * 1024 * 1024 || deadline == null || deadline.isNegative()
|| deadline.isZero() || deadline.compareTo(Duration.ofMinutes(1)) > 0) throw new IllegalArgumentException("Invalid transport limits");
var request = new HttpGet(uri);
var observed = new AtomicInteger();
Future<BoundedHttpTransport.Response> attempt;
try {
attempt = workers.submit(() -> execute(uri, resolver, request, deadline, maxBytes, observed));
} catch (RejectedExecutionException error) {
throw failure(Reason.BUSY, observed);
}
try {
return attempt.get(Math.max(1, deadline.toMillis()), TimeUnit.MILLISECONDS);
} catch (TimeoutException error) {
cancel(request, attempt);
throw failure(Reason.TIMEOUT, observed);
} catch (InterruptedException error) {
cancel(request, attempt);
Thread.currentThread().interrupt();
throw failure(Reason.INTERRUPTED, observed);
} catch (ExecutionException error) {
cancel(request, attempt);
if (error.getCause() instanceof BoundedHttpTransport.Failure safe) throw safe;
if (error.getCause() instanceof AddressRejectedException) throw failure(Reason.INVALID_ADDRESS, observed);
if (error.getCause() instanceof java.net.SocketTimeoutException) throw failure(Reason.TIMEOUT, observed);
// Do not attach causes: TLS/DNS/parser exceptions can contain signed URLs or response data.
throw failure(Reason.IO, observed);
}
}
private BoundedHttpTransport.Response execute(URI uri, AddressResolver resolver, HttpGet request,
Duration deadline, int maxBytes, AtomicInteger observed) throws IOException {
String host = unbracket(uri.getHost());
InetAddress[] addresses = resolver.resolve(host);
if (addresses == null || addresses.length == 0 || addresses.length > 16
|| java.util.Arrays.stream(addresses).anyMatch(java.util.Objects::isNull)) throw new AddressRejectedException();
// DNS lookup may ignore interruption. Once timed out, it must never resume with a late HTTP GET.
if (request.isCancelled() || Thread.currentThread().isInterrupted()) throw failure(Reason.INTERRUPTED, observed);
InetAddress[] pinned = addresses.clone();
var timeout = Timeout.ofMilliseconds(Math.max(1, deadline.toMillis()));
var boundDns = new DnsResolver() {
@Override public InetAddress[] resolve(String target) throws UnknownHostException {
if (!host.equalsIgnoreCase(unbracket(target))) throw new UnknownHostException("Unexpected target");
return pinned.clone();
}
@Override public String resolveCanonicalHostname(String target) throws UnknownHostException {
if (!host.equalsIgnoreCase(unbracket(target))) throw new UnknownHostException("Unexpected target");
return host;
}
};
var tls = new DefaultClientTlsStrategy(sslContext, HostnameVerificationPolicy.BOTH, new DefaultHostnameVerifier());
// A direct HTTP route alone is insufficient: new Socket() can still use the JVM's SOCKS selector.
var operator = new DefaultHttpClientConnectionOperator(ignored -> new Socket(Proxy.NO_PROXY),
DefaultSchemePortResolver.INSTANCE, boundDns, scheme -> "https".equalsIgnoreCase(scheme) ? tls : null);
var manager = new BasicHttpClientConnectionManager(operator, ManagedHttpClientConnectionFactory.builder()
.http1Config(Http1Config.custom().setMaxLineLength(8192).setMaxHeaderCount(64).build()).build());
manager.setConnectionConfig(ConnectionConfig.custom().setConnectTimeout(timeout).setSocketTimeout(timeout).build());
manager.setTlsConfig(TlsConfig.custom().setHandshakeTimeout(timeout).build());
request.setConfig(RequestConfig.custom().setResponseTimeout(timeout).setConnectionRequestTimeout(timeout)
.setHardCancellationEnabled(true).setAuthenticationEnabled(false).setRedirectsEnabled(false).build());
request.setHeader("Accept", "image/*");
request.setHeader("Accept-Encoding", "identity");
request.setHeader("Connection", "close");
try (var client = HttpClients.custom().setConnectionManager(manager)
.setRoutePlanner(new DefaultRoutePlanner(DefaultSchemePortResolver.INSTANCE))
.disableAutomaticRetries().disableRedirectHandling().disableCookieManagement()
.disableAuthCaching().disableContentCompression().disableDefaultUserAgent().build()) {
try {
var response = client.executeOpen(null, request, null);
try {
observed.set(response.getCode());
var entity = response.getEntity();
int limit = response.getCode() >= 200 && response.getCode() < 300 ? maxBytes : Math.min(maxBytes, 64 * 1024);
if (entity != null && entity.getContentLength() > limit) throw failure(Reason.BODY_TOO_LARGE, observed);
// Compressed images are already encoded; do not accept a decompression bomb or compressed MIME wrapper.
if (entity != null && entity.getContentEncoding() != null
&& !"identity".equalsIgnoreCase(entity.getContentEncoding())) throw failure(Reason.IO, observed);
var body = new ByteArrayOutputStream();
if (entity != null) {
var input = entity.getContent();
byte[] chunk = new byte[8192];
int count;
while ((count = input.read(chunk)) != -1) {
if (request.isCancelled() || Thread.currentThread().isInterrupted()) throw failure(Reason.INTERRUPTED, observed);
if (count > limit - body.size()) throw failure(Reason.BODY_TOO_LARGE, observed);
body.write(chunk, 0, count);
}
}
var headers = new LinkedHashMap<String, List<String>>();
for (var header : response.getHeaders()) headers.computeIfAbsent(header.getName(), ignored -> new ArrayList<>()).add(header.getValue());
return new BoundedHttpTransport.Response(response.getCode(), HttpHeaders.of(headers, (key, value) -> true), body.toByteArray());
} finally {
// Cancel BEFORE closing the entity: close/consume must not drain an oversized/never-ending body.
request.cancel();
try { response.close(); }
catch (IOException expectedAfterCancellation) { /* Never replace the primary outcome with a closed-socket cleanup error. */ }
}
} finally {
request.cancel();
client.close(CloseMode.IMMEDIATE);
}
}
}
private static String unbracket(String host) {
return host.startsWith("[") && host.endsWith("]") ? host.substring(1, host.length() - 1) : host;
}
private static void cancel(HttpGet request, Future<?> attempt) { request.cancel(); attempt.cancel(true); }
private static BoundedHttpTransport.Failure failure(Reason reason, AtomicInteger observed) {
return new BoundedHttpTransport.Failure(reason, observed.get() == 0 ? null : observed.get());
}
}
@@ -8,8 +8,9 @@ import com.moyi.controlplane.security.SecretCipher;
import com.moyi.controlplane.provider.credentials.UpstreamCredentialResolver;
import com.moyi.controlplane.provider.transport.ProviderRequestException;
import com.moyi.controlplane.provider.transport.BoundedHttpTransport;
import com.moyi.controlplane.provider.media.MediaDownloader;
import com.moyi.controlplane.provider.media.MediaDownloader.MediaBytes;
import java.net.URI;
import java.net.InetAddress;
import java.net.http.HttpRequest;
import java.time.Duration;
import java.io.ByteArrayOutputStream;
@@ -42,6 +43,7 @@ public class AsyncProviderClient {
* every request otherwise selected the first upstream key forever. */
private final ConcurrentMap<String, AtomicInteger> keyCursors = new ConcurrentHashMap<>();
private final BoundedHttpTransport transport = new BoundedHttpTransport();
private final MediaDownloader mediaDownloader = new MediaDownloader();
public AsyncProviderClient(JdbcTemplate jdbc, SecretCipher cipher, ObjectMapper mapper, Environment environment) {
this.jdbc = jdbc; this.cipher = cipher; this.mapper = mapper; this.environment = environment;
@@ -221,7 +223,7 @@ public class AsyncProviderClient {
String media=mediaUrl(input);
if(media!=null) {
try {
MediaBytes file=downloadMedia(media);
MediaBytes file=mediaDownloader.download(media);
parts.add(Map.of("inlineData",Map.of("mimeType",file.contentType(),"data",Base64.getEncoder().encodeToString(file.bytes()))));
} catch(ApiException e) { throw e; }
catch(Exception e) { throw new ApiException("MEDIA_FETCH_FAILED","无法读取参考图",400); }
@@ -351,7 +353,7 @@ public class AsyncProviderClient {
multipartField(out, boundary, entry.getKey(), String.valueOf(entry.getValue()));
}
if (fileField != null && media != null) {
MediaBytes file = downloadMedia(media);
MediaBytes file = mediaDownloader.download(media);
multipartFile(out, boundary, fileField, file.filename(), file.contentType(), file.bytes());
}
out.write(("--" + boundary + "--\r\n").getBytes(java.nio.charset.StandardCharsets.UTF_8));
@@ -400,52 +402,6 @@ public class AsyncProviderClient {
out.write("\r\n".getBytes(java.nio.charset.StandardCharsets.UTF_8));
}
private MediaBytes downloadMedia(String value) throws IOException, InterruptedException {
URI uri = URI.create(value);
if (!"https".equalsIgnoreCase(uri.getScheme()) || uri.getHost() == null || uri.getUserInfo() != null) {
throw new ApiException("INVALID_MEDIA_URL", "媒体地址必须是可公开访问的 HTTPS URL", 400);
}
for (InetAddress address : InetAddress.getAllByName(uri.getHost())) {
if (address.isAnyLocalAddress() || address.isLoopbackAddress() || address.isLinkLocalAddress()
|| address.isSiteLocalAddress() || address.isMulticastAddress()) {
throw new ApiException("INVALID_MEDIA_URL", "媒体地址不能指向内网或本机地址", 400);
}
}
HttpRequest request = HttpRequest.newBuilder(uri).timeout(Duration.ofSeconds(15)).GET().build();
BoundedHttpTransport.Response response;
try { response = transport.send(request, 8 * 1024 * 1024); }
catch (BoundedHttpTransport.Failure failure) {
if (failure.reason() == BoundedHttpTransport.Reason.BODY_TOO_LARGE) throw new ApiException("MEDIA_TOO_LARGE", "媒体输入超过 8 MiB", 400);
throw new ApiException("MEDIA_FETCH_FAILED", "无法在期限内读取媒体输入", 400);
}
if (response.statusCode() < 200 || response.statusCode() >= 300) {
throw new ApiException("MEDIA_FETCH_FAILED", "无法读取媒体输入(HTTP " + response.statusCode() + ")", 400);
}
byte[] bytes = response.body();
if (bytes.length == 0 || bytes.length > 8 * 1024 * 1024) {
throw new ApiException("MEDIA_TOO_LARGE", "媒体输入为空或超过 8 MiB", 400);
}
String contentType = response.headers().firstValue("Content-Type").orElse("application/octet-stream")
.split(";", 2)[0].trim().toLowerCase(java.util.Locale.ROOT);
if (!contentType.startsWith("image/")) {
throw new ApiException("MEDIA_TYPE_UNSUPPORTED", "图像编辑和视频参考图必须是 image/* 文件", 400);
}
String filename = "input" + extension(contentType);
return new MediaBytes(bytes, contentType, filename);
}
private String extension(String contentType) {
return switch (contentType) {
case "image/jpeg" -> ".jpg";
case "image/png" -> ".png";
case "image/webp" -> ".webp";
case "image/gif" -> ".gif";
default -> ".bin";
};
}
private record MediaBytes(byte[] bytes, String contentType, String filename) {}
private Map<String,Object> request(String method, String url, String key, Map<String,Object> body, String message) {
boolean sending = false;
try {