package com.ard.web.controller.sample.media; import com.ard.oss.model.CredentialsDTO; import com.ard.oss.service.impl.OssServiceContext; import io.swagger.annotations.Api; import io.swagger.annotations.ApiOperation; import lombok.extern.slf4j.Slf4j; import okhttp3.*; import okio.BufferedSink; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Value; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.net.ssl.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; 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; @Api(tags = "机场上传minio") @Slf4j @RestController @RequestMapping("/minioTransfer") public class MinioStsProxyController { // ==================== 常量配置 ==================== private static final String PROXY_PREFIX = "/minioTransfer"; private static final int BUFFER_SIZE = 65536; 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"; // 配置注入 @Value("${oss.endpoint}") private String minioEndpoint; private static final Integer connectTimeout = 30; private static final Integer readWriteTimeout = 1800; @Autowired private OssServiceContext ossService; // OkHttp客户端(全局) private static OkHttpClient httpClient; // 静态初始化:全局禁用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"); TrustManager[] trustAllCerts = new TrustManager[]{ new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] certs, String authType) {} @Override public void checkServerTrusted(X509Certificate[] certs, String authType) {} @Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } } }; 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编译错误) 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) // 调用总超时 .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) // 缩短保活间隔 .build(); log.info("OkHttp客户端初始化完成(兼容MinIO TLS 1.2)"); } 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()); String targetUrl = buildTargetUrl(requestUri, queryString); if (targetUrl == null) { sendError(response, HttpServletResponse.SC_BAD_REQUEST, "请求路径非法"); return; } CredentialsDTO credentials = getCredentials(); if (credentials == null) { sendError(response, HttpServletResponse.SC_FORBIDDEN, "STS凭证无效"); return; } try { Request okRequest = buildRequest(request, method, targetUrl, credentials); forwardResponse(okRequest, response); log.info("STS代理请求成功 | 目标地址:{}", targetUrl); } catch (Exception e) { log.error("STS代理请求执行异常", e); sendError(response, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "代理服务异常:" + e.getMessage()); } } private String buildTargetUrl(String requestUri, String queryString) { try { String targetPath = requestUri.substring(PROXY_PREFIX.length()); StringBuilder urlBuilder = new StringBuilder(minioEndpoint).append(targetPath); if (queryString != null && !queryString.isBlank()) { urlBuilder.append("?").append(queryString); } return urlBuilder.toString(); } catch (Exception e) { log.error("目标地址构造失败", e); return null; } } private CredentialsDTO getCredentials() { try { CredentialsDTO dto = ossService.getCredentials(); if (dto == null || dto.getAccessKeyId() == null || dto.getSecurityToken() == null) { log.error("STS凭证核心字段缺失"); return null; } log.info("STS凭证获取成功 | AK前缀:{}", dto.getAccessKeyId().substring(0, 4) + "***"); return dto; } catch (Exception e) { log.error("获取STS凭证异常", e); return null; } } private Request buildRequest(HttpServletRequest request, String method, String url, CredentialsDTO credentials) throws IOException { Request.Builder builder = new Request.Builder().url(url); // 透传请求头 Enumeration headerNames = request.getHeaderNames(); while (headerNames.hasMoreElements()) { String name = headerNames.nextElement(); if (name.equalsIgnoreCase(HOST)) { continue; } builder.addHeader(name, request.getHeader(name)); } // 添加STS令牌 builder.addHeader(X_AMZ_SECURITY_TOKEN, credentials.getSecurityToken()); // 构建请求体 RequestBody body = null; if (!"GET".equalsIgnoreCase(method) && !"HEAD".equalsIgnoreCase(method)) { long contentLength = request.getContentLengthLong(); InputStream inputStream = request.getInputStream(); // 小文件预读取 if (contentLength > 0 && contentLength <= MAX_MEMORY_SIZE) { 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"); body = RequestBody.create(content, mediaType); } 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"); } @Override public long contentLength() { return contentLength; } @Override public void writeTo(BufferedSink sink) throws IOException { byte[] buffer = new byte[BUFFER_SIZE]; int len; long totalWritten = 0; try (InputStream in = inputStream) { while ((len = in.read(buffer)) != -1) { sink.write(buffer, 0, len); totalWritten += len; if (totalWritten % (1024 * 1024 * 100) == 0) { sink.flush(); log.info("已上传:{:.2f}MB", totalWritten / 1024.0 / 1024.0); } } 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(); } private byte[] readInputStreamToBytes(InputStream inputStream) throws IOException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = inputStream.read(buffer)) != -1) { bos.write(buffer, 0, len); } bos.flush(); byte[] result = bos.toByteArray(); bos.close(); return result; } 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()); // 透传响应头 Headers headers = okResponse.headers(); for (String name : headers.names()) { if (TRANSFER_ENCODING.equalsIgnoreCase(name)) { continue; } response.setHeader(name, headers.get(name)); } // 透传响应体 ResponseBody responseBody = okResponse.body(); if (responseBody != null) { try (InputStream in = responseBody.byteStream()) { byte[] buffer = new byte[BUFFER_SIZE]; int len; while ((len = in.read(buffer)) != -1) { 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); } } }