forked from mtusi2026/mtusi2026lab7
fix(tls): drain rejected API input within a bounded deadline
This commit is contained in:
+42
-1
@@ -359,6 +359,47 @@ func (l *boundedListener) Accept() (net.Conn, error) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type drainingRequestBody struct {
|
||||
io.ReadCloser
|
||||
mu sync.Mutex
|
||||
once sync.Once
|
||||
deadline func()
|
||||
}
|
||||
|
||||
func (b *drainingRequestBody) Read(data []byte) (int, error) {
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
return b.ReadCloser.Read(data)
|
||||
}
|
||||
|
||||
func (b *drainingRequestBody) Close() error {
|
||||
b.once.Do(func() {
|
||||
b.deadline()
|
||||
b.mu.Lock()
|
||||
defer b.mu.Unlock()
|
||||
// Drain within a short deadline after an early response so closing TLS does
|
||||
// not reset a load balancer still transmitting the rejected body.
|
||||
_, _ = io.Copy(io.Discard, b.ReadCloser)
|
||||
_ = b.ReadCloser.Close()
|
||||
})
|
||||
return nil
|
||||
}
|
||||
|
||||
func serveLoopbackProxy(c Config, proxy *httputil.ReverseProxy, w http.ResponseWriter, r *http.Request) {
|
||||
if c.Role == "api" && r.Body != nil && r.Body != http.NoBody {
|
||||
controller := http.NewResponseController(w)
|
||||
_ = controller.EnableFullDuplex()
|
||||
_ = controller.SetReadDeadline(time.Now().Add(25 * time.Second))
|
||||
body := &drainingRequestBody{ReadCloser: r.Body, deadline: func() {
|
||||
_ = controller.SetReadDeadline(time.Now().Add(2 * time.Second))
|
||||
}}
|
||||
r.Body = body
|
||||
defer body.Close()
|
||||
}
|
||||
proxy.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
func loopbackProxy(c Config, target *url.URL) *httputil.ReverseProxy {
|
||||
proxy := httputil.NewSingleHostReverseProxy(target)
|
||||
if c.Role == "api" {
|
||||
@@ -418,7 +459,7 @@ func runHTTP(c Config, b Boundary) error {
|
||||
}
|
||||
r.Header.Del("X-Forwarded-Client-Cert")
|
||||
r.Header.Del("X-TLS-Identity")
|
||||
proxy.ServeHTTP(w, r)
|
||||
serveLoopbackProxy(c, proxy, w, r)
|
||||
})
|
||||
listener, e := net.Listen("tcp", b.Listen)
|
||||
if e != nil {
|
||||
|
||||
Reference in New Issue
Block a user