一個app 啟動之后,當訪問8083端口的URL發現出現redirect 死循環。 我們確實在servlet的filter(a filter) 里有個邏輯,如果訪問的端口不是8083 的話,就回redirect 到8083 (保證這個URL的訪問都是內部的). 所以出現redirect死循環,肯定是端口發生了變化。進來8083,到達filter 時候變成了別的端口。
所以當時第一個猜想就是是不是有另外一個filter (b filter) 把8083 redirect 到別的端口,然后這個端口的request 被a filter 重新redirect 到8083. 這個兩個filter 就形成了死循環。
我們的思路是先要看這個8083 的request被redirect 到哪個端口, 通過加入debug 信息發現端口是80. 由于這個app 用了shiro, Shiro過濾器里有個PortFilter,PortFilter 正好強制把端口轉向80。 所以我們開始查配置,發現8083請求request 配置了跳過Shiro ,所以跟Shiro無關。
通過下面代碼查過了所有的filter 發現沒有filter 在干redirect 的事情。
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.Map;
@Component
public class FilterLister {
private final ApplicationContext applicationContext;
public FilterLister(ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@PostConstruct
public void listAllFilters() {
Map<String, FilterRegistrationBean> filters = applicationContext.getBeansOfType(FilterRegistrationBean.class);
for (Map.Entry<String, FilterRegistrationBean> entry : filters.entrySet()) {
System.out.println("Filter name: " + entry.getKey());
System.out.println("Filter instance: " + entry.getValue().getFilter());
}
}
}
那么還有什么情況能改變request 端口呢,我們不得不在org.apache.coyote.Request 里的 setServerPort 方法打印 stack trace, 因為只有這里會 setServerPort。 通過這個方式發現了
org.apache.catalina.valves.RemoteIpValve
。
同時在配置中也發現用戶enable 了這個值
server.tomcat.remoteip.remote-ip-header=x-forwarded-for
server.tomcat.remoteip.protocol-header=x-forwarded-proto
這些配置到底有什么關聯呢? 首先看在RemoteIpValve是怎么進入到tomcat request pipeline里去的。
配置RemoteIpValve
在創建tomcat容器時的ServletWebServerApplicationContext#createWebServer。
ServletWebServerFactory factory = getWebServerFactory();
this.webServer = factory.getWebServer(getSelfInitializer());
getWebServerFactory()方法會從beanFactory中獲取ServletWebServerFactory對象。構造這個bean的過程中,會執行提前注冊好的WebServerFactoryCustomizerBeanPostProcessor。
WebServerFactoryCustomizerBeanPostProcessor.postProcessBeforeInitialization會獲取所有實現WebServerFactoryCustomizer的bean,并執行他們的customize()方法。
這其中就包括TomcatWebServerFactoryCustomizer,這里增加了tomcat專用的一些features.
Customization for Tomcat-specific features common for both Servlet and Reactive servers.
其中的customizeRemoteIpValve()方法會根據條件向tomcat中加入RemoteIpValve
private void customizeRemoteIpValve(ConfigurableTomcatWebServerFactory factory) {
Remoteip remoteIpProperties = this.serverProperties.getTomcat().getRemoteip();
String protocolHeader = remoteIpProperties.getProtocolHeader();
String remoteIpHeader = remoteIpProperties.getRemoteIpHeader();
// For back compatibility the valve is also enabled if protocol-header is set
if (StringUtils.hasText(protocolHeader) || StringUtils.hasText(remoteIpHeader)
|| getOrDeduceUseForwardHeaders()) {
RemoteIpValve valve = new RemoteIpValve();
valve.setProtocolHeader(StringUtils.hasLength(protocolHeader) ? protocolHeader : "X-Forwarded-Proto");
if (StringUtils.hasLength(remoteIpHeader)) {
valve.setRemoteIpHeader(remoteIpHeader);
}
// The internal proxies default to a list of "safe" internal IP addresses
valve.setInternalProxies(remoteIpProperties.getInternalProxies());
try {
valve.setHostHeader(remoteIpProperties.getHostHeader());
}
catch (NoSuchMethodError ex) {
// Avoid failure with war deployments to Tomcat 8.5 before 8.5.44 and
// Tomcat 9 before 9.0.23
}
valve.setPortHeader(remoteIpProperties.getPortHeader());
valve.setProtocolHeaderHttpsValue(remoteIpProperties.getProtocolHeaderHttpsValue());
// ... so it's safe to add this valve by default.
factory.addEngineValves(valve);
}
}
我本地用自己Sample 的項目,加上那兩個配置后,debug 走到這,分別是protocolHeader : x-forwarded-proto 和remoteIpHeader: x-forwarded-for ,這就體現application.proprties的配置作用。 配了任意一個都會激活RemoteIpValve,被加入到了tocat pipeline 中factory.addEngineValves(valve);
。從90.3 Enable HTTPS When Running behind a Proxy Server ,https://docs.spring.io/spring-boot/docs/2.1.x/reference/html/howto-security.html 也證明了我們的判斷。
RemoteIpValve 的作用
tomcat會將原始的http報文封裝成org.apache.catalina.connector.Request,我們可以從中獲取到remoteAddr和http header。
具體細節可以參考 : https://www.cnblogs.com/zhongchang/articles/10345333.html 以及https://blog.csdn.net/weixin_40562288/article/details/96131975
我們這個case 就是在enable RemoteIpValve,如果request header 里有x-forwarded-proto 就會導致severport 被改寫。
if (protocolHeader != null) {
String protocolHeaderValue = request.getHeader(protocolHeader);
if (protocolHeaderValue == null) {
// Don't modify the secure, scheme and serverPort attributes
// of the request
} else if (isForwardedProtoHeaderValueSecure(protocolHeaderValue)) {
request.setSecure(true);
request.getCoyoteRequest().scheme().setString("https");
setPorts(request, httpsServerPort);
} else {
request.setSecure(false);
request.getCoyoteRequest().scheme().setString("http");
setPorts(request, httpServerPort);
}
}
為啥我們的會多出來一個x-forwarded-proto ,就涉及到另外一個問題。我們app 是在istio 的環境中。X-Forwarded-Proto header set to http instead of https on subsequent request https://github.com/istio/istio/issues/36612
這就完全解釋了為啥端口會被設置成80, 導致8083 a filter 無限發生作用。
總結
如果讓端口發生變化,要有兩個條件
1 要配置tomcat,讓RemoteIpValve配置到pipeline 中去
server.tomcat.remoteip.remote-ip-header=x-forwarded-for
server.tomcat.remoteip.protocol-header=x-forwarded-proto
- 要在header 傳入x-forwarded-proto 或者x-forwarded-for 的值
兩者缺一不可。 我們的app 正好在code 配置了RemoteIpValve, 在istio 里加了x-forwarded-proto , 所以激活了RemoteIpValve set request port。
擴展
Tomcat 改port 的地方一共有三處 ,都在Http11Processor
server.tomcat.remoteip.remote-ip-header=x-forwarded-for
server.tomcat.remoteip.protocol-header=x-forwarded-proto
這兩行配置,訪問http://abc:8083時,內存中 request 端口的變化
- 在prepareRequest, prepareRequest(Http11Processor.java:784), 根據 URL 里面的 "冒號+port", 在 parseHost 去設置從 old ServerPort = -1 變成 newServerPort = 8083
java.base/java.lang.Thread.getStackTrace(Unknown Source)
org.apache.coyote.Request.setServerPort(Request.java:345)
org.apache.coyote.AbstractProcessor.parseHost(AbstractProcessor.java:311)
org.apache.coyote.http11.Http11Processor.prepareRequest(Http11Processor.java:784)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:928)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1794)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Unknown Source)
- 在(Http11Processor.java:390),CoyoteAdapter.serviceservicepipeline 中如果有 org.apache.catalina.valves.RemoteIpValve, 它又會改port
old ServerPort = 8083
newServerPort = 80
java.base/java.lang.Thread.getStackTrace(Unknown Source)
org.apache.coyote.Request.setServerPort(Request.java:345)
org.apache.coyote.AbstractProcessor.parseHost(AbstractProcessor.java:311)
org.apache.coyote.http11.Http11Processor.prepareRequest(Http11Processor.java:784)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:367)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:928)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1794)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Unknown Source)
- postParseRequest(CoyoteAdapter.java:585) 在前面兩個都不起作用的時候來設置port
org.apache.coyote.Request.setServerPort(Request.java:345)
org.apache.catalina.connector.CoyoteAdapter.postParseRequest(CoyoteAdapter.java:585)
org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:337)
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:390)
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:928)
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1794)
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
java.base/java.lang.Thread.run(Unknown Source)
例如 訪問 api: https://tmsapp-staging-2-tmsappcont.istio-staging.svc.130.tess.io/instance-access/10.42.231.252/api/v1/internal/get-request-info?ab=cd時, prepareRequest(Http11Processor.java:784)里面不會 setServerPort,因為這個 URL 里面不帶 "冒號+port",它里面在 parseHost 找不到端口去設置 隨后在 postParseRequest(CoyoteAdapter.java:585) 時,因為 req.getServerPort() 還是 -1,所以會基于 scheme 去改port。