zhaowenyu
2026-02-11 b0a4ce6982a3b3694679f69c39c59df84ecdcb06
ard-admin/src/main/java/com/ard/web/controller/sample/media/MinioStsProxyController.java
@@ -18,12 +18,8 @@
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.concurrent.TimeUnit;
@@ -35,11 +31,10 @@
    // ==================== 常量配置 ====================
    private static final String PROXY_PREFIX = "/minioTransfer";
    private static final int BUFFER_SIZE = 65536;
    private static final int BUFFER_SIZE = 65536; // 64K缓冲区
    private static final long MAX_MEMORY_SIZE = 1024 * 1024 * 100; // 100MB
    private static final String X_AMZ_SECURITY_TOKEN = "X-Amz-Security-Token";
    private static final String TRANSFER_ENCODING = "Transfer-Encoding";
    private static final String CONTENT_LENGTH = "Content-Length";
    private static final String HOST = "Host";
    // 配置注入
@@ -51,177 +46,73 @@
    @Autowired
    private OssServiceContext ossService;
    // OkHttp客户端(全局)
    // OkHttp客户端(全局单例,极简配置)
    private static OkHttpClient httpClient;
    // 静态初始化:全局禁用SSL校验 + 强制兼容加密套件
    // 静态初始化:仅做最必要的SSL配置,避免过度封装
    static {
        // 第一步:全局禁用SSL证书校验(终极兜底)
        disableSslVerification();
        // 第二步:创建兼容MinIO的OkHttp客户端
        createOkHttpClient();
    }
    /**
     * 全局禁用SSL证书校验(绕过所有SSL检查,仅内网/测试环境使用)
     */
    private static void disableSslVerification() {
        try {
            // 获取信任所有证书的TrustManager
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        public X509Certificate[] getAcceptedIssuers() { return null; }
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                    }
            };
            // 获取SSL上下文,强制TLS 1.2
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sslContext.getSocketFactory());
            // 禁用主机名验证
            HostnameVerifier allHostsValid = (hostname, session) -> true;
            HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
            log.info("全局SSL证书校验已禁用(仅测试环境)");
        } catch (NoSuchAlgorithmException | KeyManagementException e) {
            log.error("全局禁用SSL校验失败", e);
        }
    }
    /**
     * 创建兼容MinIO的OkHttp客户端(强制加密套件 + TCP优化)
     */
    private static void createOkHttpClient() {
        try {
            // 1. 初始化SSL上下文(强制TLS 1.2 + 信任所有证书)
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            // 1. 全局禁用SSL证书校验(内网环境专用)
            TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(X509Certificate[] certs, String authType) {}
                        public void checkClientTrusted(X509Certificate[] chain, String authType) {}
                        @Override
                        public void checkServerTrusted(X509Certificate[] certs, String authType) {}
                        public void checkServerTrusted(X509Certificate[] chain, String authType) {}
                        @Override
                        public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
                    }
            };
            // 2. 强制TLS 1.2
            SSLContext sslContext = SSLContext.getInstance("TLSv1.2");
            sslContext.init(null, trustAllCerts, new SecureRandom());
            SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();
            // 2. 配置MinIO兼容的加密套件(关键!解决握手后断开)
            String[] compatibleCiphers = {
                    "TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256",
                    "TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384",
                    "TLS_RSA_WITH_AES_128_GCM_SHA256",
                    "TLS_RSA_WITH_AES_256_GCM_SHA384"
            };
            // 3. 自定义SSLSocketFactory,强制加密套件
            SSLSocketFactory customSslSocketFactory = new SSLSocketFactory() {
                @Override
                public String[] getDefaultCipherSuites() {
                    return compatibleCiphers;
                }
                @Override
                public String[] getSupportedCipherSuites() {
                    return compatibleCiphers;
                }
                @Override
                public Socket createSocket(Socket s, String host, int port, boolean autoClose) throws IOException {
                    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(s, host, port, autoClose);
                    sslSocket.setEnabledCipherSuites(compatibleCiphers);
                    sslSocket.setEnabledProtocols(new String[]{"TLSv1.2"});
                    return sslSocket;
                }
                @Override
                public Socket createSocket(String host, int port) throws IOException {
                    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
                    sslSocket.setEnabledCipherSuites(compatibleCiphers);
                    sslSocket.setEnabledProtocols(new String[]{"TLSv1.2"});
                    return sslSocket;
                }
                @Override
                public Socket createSocket(String host, int port, java.net.InetAddress localHost, int localPort) throws IOException {
                    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port, localHost, localPort);
                    sslSocket.setEnabledCipherSuites(compatibleCiphers);
                    sslSocket.setEnabledProtocols(new String[]{"TLSv1.2"});
                    return sslSocket;
                }
                @Override
                public Socket createSocket(java.net.InetAddress host, int port) throws IOException {
                    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(host, port);
                    sslSocket.setEnabledCipherSuites(compatibleCiphers);
                    sslSocket.setEnabledProtocols(new String[]{"TLSv1.2"});
                    return sslSocket;
                }
                @Override
                public Socket createSocket(java.net.InetAddress address, int port, java.net.InetAddress localAddress, int localPort) throws IOException {
                    SSLSocket sslSocket = (SSLSocket) sslSocketFactory.createSocket(address, port, localAddress, localPort);
                    sslSocket.setEnabledCipherSuites(compatibleCiphers);
                    sslSocket.setEnabledProtocols(new String[]{"TLSv1.2"});
                    return sslSocket;
                }
            };
            // 4. 构建OkHttp客户端(简化TCP优化,避免SocketFactory编译错误)
            // 3. 构建OkHttp客户端(原生配置,无自定义封装)
            httpClient = new OkHttpClient.Builder()
                    .sslSocketFactory(customSslSocketFactory, (X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier((hostname, session) -> true)
                    // 强制TLS 1.2和兼容加密套件
                    .connectionSpecs(Arrays.asList(
                            new ConnectionSpec.Builder(ConnectionSpec.MODERN_TLS)
                                    .tlsVersions(TlsVersion.TLS_1_2)
                                    .cipherSuites(compatibleCiphers)
                                    .build()
                    ))
                    // TCP优化:禁用Nagle算法(通过JVM参数或OkHttp的callTimeout间接优化)
                    .callTimeout(30, TimeUnit.SECONDS) // 调用总超时
                    .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustAllCerts[0])
                    .hostnameVerifier((hostname, session) -> true) // 禁用主机名校验
                    .connectTimeout(connectTimeout, TimeUnit.SECONDS)
                    .readTimeout(readWriteTimeout, TimeUnit.SECONDS)
                    .writeTimeout(readWriteTimeout, TimeUnit.SECONDS)
                    .connectionPool(new ConnectionPool(20, 10, TimeUnit.MINUTES))
                    .retryOnConnectionFailure(true)
                    .pingInterval(10, TimeUnit.SECONDS) // 缩短保活间隔
                    .retryOnConnectionFailure(true) // 开启重试
                    .pingInterval(10, TimeUnit.SECONDS) // TCP保活
                    .callTimeout(60, TimeUnit.SECONDS) // 全局调用超时
                    .build();
            log.info("OkHttp客户端初始化完成(兼容MinIO TLS 1.2)");
            log.info("OkHttp客户端初始化完成(极简SSL配置)");
        } catch (Exception e) {
            log.error("OkHttp初始化失败,使用默认客户端", e);
            httpClient = new OkHttpClient();
        }
    }
    // ========== 以下方法与之前一致,无需修改 ==========
    @ApiOperation("MinIO STS临时凭证通用代理")
    @RequestMapping("/**")
    public void proxyRequest(HttpServletRequest request, HttpServletResponse response) {
        String method = request.getMethod();
        String requestUri = request.getRequestURI();
        String queryString = request.getQueryString();
        log.info("STS代理请求开始 | 方法:{} | URI:{} | 参数:{} | 内容长度:{}",
                method, requestUri, queryString, request.getContentLengthLong());
        long contentLength = request.getContentLengthLong();
        log.info("STS代理请求开始 | 方法:{} | URI:{} | 参数:{} | 内容长度:{}B",
                method, requestUri, queryString, contentLength);
        // 1. 构造目标地址
        String targetUrl = buildTargetUrl(requestUri, queryString);
        if (targetUrl == null) {
            sendError(response, HttpServletResponse.SC_BAD_REQUEST, "请求路径非法");
            return;
        }
        // 2. 获取STS凭证
        CredentialsDTO credentials = getCredentials();
        if (credentials == null) {
            sendError(response, HttpServletResponse.SC_FORBIDDEN, "STS凭证无效");
            return;
        }
        // 3. 构建并执行请求
        try {
            Request okRequest = buildRequest(request, method, targetUrl, credentials);
            forwardResponse(okRequest, response);
@@ -232,6 +123,9 @@
        }
    }
    /**
     * 构造MinIO目标地址
     */
    private String buildTargetUrl(String requestUri, String queryString) {
        try {
            String targetPath = requestUri.substring(PROXY_PREFIX.length());
@@ -246,6 +140,9 @@
        }
    }
    /**
     * 获取并校验STS凭证
     */
    private CredentialsDTO getCredentials() {
        try {
            CredentialsDTO dto = ossService.getCredentials();
@@ -261,48 +158,49 @@
        }
    }
    /**
     * 构建OkHttp请求(核心:分文件大小处理)
     */
    private Request buildRequest(HttpServletRequest request, String method, String url, CredentialsDTO credentials) throws IOException {
        Request.Builder builder = new Request.Builder().url(url);
        // 透传请求头
        // 透传请求头:仅过滤Host(OkHttp自动处理)
        Enumeration<String> headerNames = request.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String name = headerNames.nextElement();
            if (name.equalsIgnoreCase(HOST)) {
                continue;
            }
            if (!name.equalsIgnoreCase(HOST)) {
            builder.addHeader(name, request.getHeader(name));
        }
        }
        // 添加STS令牌
        // 添加STS安全令牌
        builder.addHeader(X_AMZ_SECURITY_TOKEN, credentials.getSecurityToken());
        // 构建请求体
        // 构建请求体(GET/HEAD无请求体)
        RequestBody body = null;
        if (!"GET".equalsIgnoreCase(method) && !"HEAD".equalsIgnoreCase(method)) {
            long contentLength = request.getContentLengthLong();
            InputStream inputStream = request.getInputStream();
            long contentLength = request.getContentLengthLong();
            // 小文件预读取
            // 小文件:预读取到内存(稳定)
            if (contentLength > 0 && contentLength <= MAX_MEMORY_SIZE) {
                log.info("小文件上传:预读取到内存,长度:{:.2f}MB", contentLength / 1024.0 / 1024.0);
                log.info("小文件上传:预读取到内存,大小:{:.2f}MB", contentLength / 1024.0 / 1024.0);
                byte[] content = readInputStreamToBytes(inputStream);
                MediaType mediaType = request.getContentType() != null
                        ? MediaType.parse(request.getContentType())
                        : MediaType.parse("application/octet-stream");
                MediaType mediaType = MediaType.parse(request.getContentType() == null ? "application/octet-stream" : request.getContentType());
                body = RequestBody.create(content, mediaType);
            } else {
            }
            // 大文件:流式上传(省内存)
            else {
                log.info("大文件/未知长度上传:使用流式传输");
                body = new RequestBody() {
                    @Override
                    public MediaType contentType() {
                        String contentType = request.getContentType();
                        return contentType != null ? MediaType.parse(contentType) : MediaType.parse("application/octet-stream");
                        return MediaType.parse(request.getContentType() == null ? "application/octet-stream" : request.getContentType());
                    }
                    @Override
                    public long contentLength() {
                        return contentLength;
                        return contentLength; // 避免chunked编码
                    }
                    @Override
@@ -314,6 +212,7 @@
                            while ((len = in.read(buffer)) != -1) {
                                sink.write(buffer, 0, len);
                                totalWritten += len;
                                // 每100MB刷新一次
                                if (totalWritten % (1024 * 1024 * 100) == 0) {
                                    sink.flush();
                                    log.info("已上传:{:.2f}MB", totalWritten / 1024.0 / 1024.0);
@@ -321,19 +220,18 @@
                            }
                            sink.flush();
                            log.info("流式上传完成,总写入:{:.2f}MB", totalWritten / 1024.0 / 1024.0);
                        } catch (IOException e) {
                            log.error("流式上传失败,已写入:{:.2f}MB", totalWritten / 1024.0 / 1024.0, e);
                            throw e;
                        }
                    }
                };
            }
        }
        builder.method(method, body);
        return builder.build();
        return builder.method(method, body).build();
    }
    /**
     * 读取InputStream到字节数组(小文件专用)
     */
    private byte[] readInputStreamToBytes(InputStream inputStream) throws IOException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        byte[] buffer = new byte[BUFFER_SIZE];
@@ -347,24 +245,25 @@
        return result;
    }
    /**
     * 转发MinIO响应到客户端
     */
    private void forwardResponse(Request request, HttpServletResponse response) throws IOException {
        try (Response okResponse = httpClient.newCall(request).execute()) {
            // 新增:确保响应编码和类型正确
            response.setCharacterEncoding("UTF-8");
            String responseContentType = okResponse.header("Content-Type");
            if (responseContentType != null) {
                response.setContentType(responseContentType);
            }
            // 配置响应头
            response.setStatus(okResponse.code());
            response.setCharacterEncoding("UTF-8");
            String contentType = okResponse.header("Content-Type");
            if (contentType != null) {
                response.setContentType(contentType);
            }
            // 透传响应头
            Headers headers = okResponse.headers();
            for (String name : headers.names()) {
                if (TRANSFER_ENCODING.equalsIgnoreCase(name)) {
                    continue;
                }
                if (!name.equalsIgnoreCase(TRANSFER_ENCODING)) {
                response.setHeader(name, headers.get(name));
                }
            }
            // 透传响应体
@@ -377,18 +276,19 @@
                        response.getOutputStream().write(buffer, 0, len);
                    }
                    response.getOutputStream().flush();
                } catch (IOException e) {
                    log.warn("响应体转发失败(客户端可能已断开连接)", e);
                }
            }
        }
    }
    /**
     * 统一返回错误响应
     */
    private void sendError(HttpServletResponse response, int code, String msg) {
        try {
            response.sendError(code, msg);
        } catch (IOException e) {
            log.error("响应错误信息失败", e);
            log.error("发送错误响应失败", e);
        }
    }
}