fix: harden health probe responses

This commit is contained in:
2026-09-20 20:35:34 +08:00
parent 8aef89f179
commit 9e87249ca4
3 changed files with 18 additions and 0 deletions

View File

@@ -50,6 +50,9 @@ func (r *Readiness) BeginDrain() {
func New(addr string, ready Checker, tasks ...*service.Service) *http.Server {
mux := http.NewServeMux()
write := func(w http.ResponseWriter, status int, body map[string]string) {
// 探针响应不能被代理或浏览器缓存,否则下线节点可能继续被路由流量。
w.Header().Set("Cache-Control", "no-store")
w.Header().Set("X-Content-Type-Options", "nosniff")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
_ = json.NewEncoder(w).Encode(body)
@@ -61,6 +64,8 @@ func New(addr string, ready Checker, tasks ...*service.Service) *http.Server {
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
defer cancel()
if ready == nil || ready(ctx) != nil {
// 给负载均衡器一个明确的短暂重试提示;真正的重试节奏仍由探针策略控制。
w.Header().Set("Retry-After", "1")
write(w, http.StatusServiceUnavailable, map[string]string{"status": "not_ready"})
return
}

View File

@@ -19,6 +19,14 @@ func TestHealthSeparatesLivenessAndReadiness(t *testing.T) {
if rr.Code != want || strings.Contains(rr.Body.String(), "internal-database-details") {
t.Fatalf("%s: %d %s", path, rr.Code, rr.Body.String())
}
if strings.HasPrefix(path, "/health/") {
if rr.Header().Get("Cache-Control") != "no-store" || rr.Header().Get("X-Content-Type-Options") != "nosniff" {
t.Fatalf("%s: missing anti-cache/security headers: %#v", path, rr.Header())
}
if path == "/health/ready" && rr.Header().Get("Retry-After") != "1" {
t.Fatalf("readiness failure missing retry hint: %#v", rr.Header())
}
}
}
}
@@ -40,6 +48,9 @@ func TestReadinessEntersDrainBeforeShutdown(t *testing.T) {
if draining.Code != http.StatusServiceUnavailable || checks != 1 || strings.Contains(draining.Body.String(), "server is draining") {
t.Fatalf("during drain: status=%d checks=%d body=%s", draining.Code, checks, draining.Body.String())
}
if draining.Header().Get("Retry-After") != "1" || draining.Header().Get("Cache-Control") != "no-store" {
t.Fatalf("draining readiness headers: %#v", draining.Header())
}
}
func TestVersionIsPublicAndBounded(t *testing.T) {