activator: health checks don't follow redirects; hosts aren't reasons
A Rails app with force_ssl answers the health probe with a 301 to https://carlos/. The probe followed it, started TLS on the plain socket and failed every attempt until the deadline, so the instance never became healthy and crash-looped (discussion #845). Both probes (unix socket and TCP) now stop at the first answer, so a 3xx counts as healthy under the "under 500" rule, and say X-Forwarded-Proto: https as the edge does on real requests, so the app takes its normal path. nextDue keeps the plain socketClient. The rollout then reported "the copy on the box did not match the release" because reasonWord matched "staging" inside the host name tito-pro.bae.staging.platform.tito.io. reasonWord now drops dotted names (hosts, addresses, versions) before reading the platform's words; names inside paths are kept.
Prompt
Can we take carlos/platform discussion #845 ?
From this commit's own message. The prompt ledger has no entries for it — which is what a squashed, rebased or amended commit looks like, and what every commit looks like in a repo without a ledger.
Summary
Health probes stop following redirects and send X-Forwarded-Proto: https; reasonWord ignores host names, so a health failure no longer reads as a staging failure.
internal/activator/backend_exec.go+35 −10internal/activator/backend_unit.go+3 −10internal/activator/healthcheck_redirect_test.go+117 −0internal/rollout/events.go+11 −1internal/rollout/reason_host_test.go+37 −0
CI cancelled — superseded by a newer push — run details
Intent
Attributed to this commit: 36.0 g CO₂e (3,316,457 tokens). This is an attribution, not a measurement — usage counted from this commit's own marker forward to the next one on health-check-no-redirects-845, never backward from it. A turn that produced more than one commit books all of its tokens to the last one, and a concurrent session on this branch can add to the same figure. Some of it was priced using the shared default rate, because no model-specific factor row exists yet for at least one model involved. The Carbon view has the repo total, which is never derived from this attribution.
diff --git a/internal/activator/backend_exec.go b/internal/activator/backend_exec.go| index 0fa4851f3..1bd77ff5e 100644 |
| --- a/internal/activator/backend_exec.go |
| +++ b/internal/activator/backend_exec.go |
| @@ -3880,19 +3880,12 @@ func socketClient(socket string) *http.Client { |
| // process) — and a broken binary that never becomes healthy fails the wake. |
| func waitHealthy(socket string, timeout time.Duration) error { |
| deadline := time.Now().Add(timeout) |
| - client := socketClient(socket) |
| + client := healthClient(socketClient(socket)) |
| var last error |
| var poll time.Duration |
| for time.Now().Before(deadline) { |
| - resp, err := client.Get("http://carlos/") |
| - if err == nil { |
| - resp.Body.Close() |
| - if resp.StatusCode < 500 { |
| - return nil |
| - } |
| - last = fmt.Errorf("unhealthy: HTTP %d", resp.StatusCode) |
| - } else { |
| - last = err |
| + if last = probeHealth(client, "http://carlos/"); last == nil { |
| + return nil |
| } |
| poll = nextHealthPoll(poll) |
| time.Sleep(poll) |
| @@ -3900,6 +3893,38 @@ func waitHealthy(socket string, timeout time.Duration) error { |
| return fmt.Errorf("instance not healthy within %s: %v", timeout, last) |
| } |
| +// healthClient is c made fit for a health probe: it never follows a |
| +// redirect. A redirect is an answer, and under 500, so the app is up. |
| +// Following one is worse than pointless: an app with Rails' force_ssl |
| +// redirects to https://carlos/, and the client then starts a TLS handshake |
| +// on a plain socket, so the probe fails until the deadline and the wake |
| +// with it (discussion #845). |
| +func healthClient(c *http.Client) *http.Client { |
| + c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| + return c |
| +} |
| + |
| +// probeHealth makes one health request: nil for any answer under 500. It |
| +// says X-Forwarded-Proto: https, as the edge does on every real request |
| +// (they all arrive over TLS), so an app that redirects plain http takes its |
| +// normal path rather than answering the probe with a redirect (#845). |
| +func probeHealth(client *http.Client, url string) error { |
| + req, err := http.NewRequest(http.MethodGet, url, nil) |
| + if err != nil { |
| + return err |
| + } |
| + req.Header.Set("X-Forwarded-Proto", "https") |
| + resp, err := client.Do(req) |
| + if err != nil { |
| + return err |
| + } |
| + resp.Body.Close() |
| + if resp.StatusCode >= 500 { |
| + return fmt.Errorf("unhealthy: HTTP %d", resp.StatusCode) |
| + } |
| + return nil |
| +} |
| + |
| // The wait between health probes. A request is held open for the whole of |
| // a wake, and a fixed 150 ms gap cost it 75 ms on average after the app was |
| // already listening. A refused dial costs microseconds, so the wait starts |
diff --git a/internal/activator/backend_unit.go b/internal/activator/backend_unit.go| index 9576469e3..7f2151505 100644 |
| --- a/internal/activator/backend_unit.go |
| +++ b/internal/activator/backend_unit.go |
| @@ -265,19 +265,12 @@ func (unitRep) Close(context.Context) error { return nil } |
| // fallback note). |
| func waitHealthyAddr(addr string, timeout time.Duration) error { |
| deadline := time.Now().Add(timeout) |
| - client := &http.Client{Timeout: 3 * time.Second} |
| + client := healthClient(&http.Client{Timeout: 3 * time.Second}) |
| var last error |
| var poll time.Duration |
| for time.Now().Before(deadline) { |
| - resp, err := client.Get("http://" + addr + "/") |
| - if err == nil { |
| - resp.Body.Close() |
| - if resp.StatusCode < 500 { |
| - return nil |
| - } |
| - last = fmt.Errorf("unhealthy: HTTP %d", resp.StatusCode) |
| - } else { |
| - last = err |
| + if last = probeHealth(client, "http://"+addr+"/"); last == nil { |
| + return nil |
| } |
| poll = nextHealthPoll(poll) |
| time.Sleep(poll) |
diff --git a/internal/activator/healthcheck_redirect_test.go b/internal/activator/healthcheck_redirect_test.go| new file mode 100644 |
| index 000000000..c7d98be84 |
| --- /dev/null |
| +++ b/internal/activator/healthcheck_redirect_test.go |
| @@ -0,0 +1,117 @@ |
| +package activator |
| + |
| +import ( |
| + "net" |
| + "net/http" |
| + "strings" |
| + "sync/atomic" |
| + "testing" |
| + "time" |
| +) |
| + |
| +// forceSSLApp answers the way a Rails app with config.force_ssl does: a 301 |
| +// to https for any request that does not say it arrived over TLS. A request |
| +// that follows that redirect is a TLS handshake on a plain listener, which |
| +// the server sees as a malformed request and the client as a failed probe |
| +// (discussion #845). It counts every request that said https. |
| +func forceSSLApp(t *testing.T, ln net.Listener) *atomic.Int32 { |
| + t.Helper() |
| + var https atomic.Int32 |
| + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + if r.Header.Get("X-Forwarded-Proto") != "https" { |
| + http.Redirect(w, r, "https://"+r.Host+r.URL.RequestURI(), http.StatusMovedPermanently) |
| + return |
| + } |
| + https.Add(1) |
| + w.WriteHeader(http.StatusOK) |
| + })} |
| + go srv.Serve(ln) |
| + t.Cleanup(func() { srv.Close() }) |
| + return &https |
| +} |
| + |
| +// redirectingApp redirects every request to https, whatever it says. |
| +func redirectingApp(t *testing.T, ln net.Listener) { |
| + t.Helper() |
| + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + http.Redirect(w, r, "https://"+r.Host+"/", http.StatusMovedPermanently) |
| + })} |
| + go srv.Serve(ln) |
| + t.Cleanup(func() { srv.Close() }) |
| +} |
| + |
| +// A force_ssl app on its unix socket becomes healthy: the probe says it |
| +// came over https, as the edge does on a real request, so the app takes its |
| +// normal path (#845). |
| +func TestWaitHealthySaysHTTPS(t *testing.T) { |
| + requireUnixSockets(t) |
| + sock := tmpSock(t) |
| + ln, err := net.Listen("unix", sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + https := forceSSLApp(t, ln) |
| + if err := waitHealthy(sock, 2*time.Second); err != nil { |
| + t.Fatalf("waitHealthy: %v", err) |
| + } |
| + if https.Load() == 0 { |
| + t.Fatal("the probe never said https") |
| + } |
| +} |
| + |
| +// A redirect is an answer under 500, so it is healthy. Following it would |
| +// start TLS on a plain socket and fail every probe until the deadline (#845). |
| +func TestWaitHealthyDoesNotFollowRedirects(t *testing.T) { |
| + requireUnixSockets(t) |
| + sock := tmpSock(t) |
| + ln, err := net.Listen("unix", sock) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + redirectingApp(t, ln) |
| + if err := waitHealthy(sock, 2*time.Second); err != nil { |
| + t.Fatalf("waitHealthy on a redirecting app: %v", err) |
| + } |
| +} |
| + |
| +// The TCP probe behaves the same way. |
| +func TestWaitHealthyAddrSaysHTTPSAndDoesNotFollowRedirects(t *testing.T) { |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + https := forceSSLApp(t, ln) |
| + if err := waitHealthyAddr(ln.Addr().String(), 2*time.Second); err != nil { |
| + t.Fatalf("waitHealthyAddr: %v", err) |
| + } |
| + if https.Load() == 0 { |
| + t.Fatal("the probe never said https") |
| + } |
| + |
| + ln2, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + redirectingApp(t, ln2) |
| + if err := waitHealthyAddr(ln2.Addr().String(), 2*time.Second); err != nil { |
| + t.Fatalf("waitHealthyAddr on a redirecting app: %v", err) |
| + } |
| +} |
| + |
| +// A 500 is still unhealthy, and the error names the status rather than a |
| +// redirect target. |
| +func TestWaitHealthyStillFailsA500(t *testing.T) { |
| + ln, err := net.Listen("tcp", "127.0.0.1:0") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.WriteHeader(http.StatusInternalServerError) |
| + })} |
| + go srv.Serve(ln) |
| + t.Cleanup(func() { srv.Close() }) |
| + err = waitHealthyAddr(ln.Addr().String(), 200*time.Millisecond) |
| + if err == nil || !strings.Contains(err.Error(), "HTTP 500") { |
| + t.Fatalf("waitHealthyAddr on a 500 = %v, want HTTP 500", err) |
| + } |
| +} |
diff --git a/internal/rollout/events.go b/internal/rollout/events.go| index 88f78163b..cd83757f8 100644 |
| --- a/internal/rollout/events.go |
| +++ b/internal/rollout/events.go |
| @@ -2,6 +2,7 @@ package rollout |
| import ( |
| "fmt" |
| + "regexp" |
| "strings" |
| "time" |
| @@ -26,6 +27,15 @@ const ( |
| EvStagingRefused EventCode = "staging.refused" |
| ) |
| +// dottedName matches a dotted name standing on its own: a host, an IP |
| +// address, a version. reasonWord drops them before it reads the text, |
| +// because a host is words its owner chose: a health check failed by a host |
| +// under staging.example.com read as a staging failure (discussion #845). |
| +// The submatch is the character before the name, kept. A name inside a |
| +// path (after a slash) is not dropped: a staged path is the platform's |
| +// word for what went wrong. |
| +var dottedName = regexp.MustCompile(`(^|[^a-z0-9_./-])[a-z0-9_-]+(?:\.[a-z0-9_-]+)+`) |
| + |
| // reasonWord turns an attempt's diagnostic text (SwapResult.Reason, an error) |
| // into one of status's reason words (status.Reason*, the one vocabulary the |
| // events and the status report share), so no free text, which can name paths |
| @@ -34,7 +44,7 @@ const ( |
| // swap's checks are the health check, the settle and the exit watch, and the |
| // health check is the one a spawn or start error also fails. |
| func reasonWord(text string) string { |
| - t := strings.ToLower(text) |
| + t := dottedName.ReplaceAllString(strings.ToLower(text), "$1") |
| switch { |
| // A release command's failure (rootfs apps Plan 3, Group R) first: |
| // its text names the build's exit ("exited") and could name staging, |
diff --git a/internal/rollout/reason_host_test.go b/internal/rollout/reason_host_test.go| new file mode 100644 |
| index 000000000..d5a92b634 |
| --- /dev/null |
| +++ b/internal/rollout/reason_host_test.go |
| @@ -0,0 +1,37 @@ |
| +package rollout |
| + |
| +import ( |
| + "testing" |
| + |
| + "github.com/carlosframework/platform/internal/status" |
| +) |
| + |
| +// A host name is not a reason. Failure texts name the host they failed on, |
| +// and a host is any words its owner chose: one under staging.example.com |
| +// that failed its health check read as "the copy on the box did not match |
| +// the release" (discussion #845). reasonWord reads the platform's words, |
| +// never the names in between them. |
| +func TestReasonWordIgnoresHostNames(t *testing.T) { |
| + for text, want := range map[string]string{ |
| + // The text from #845. |
| + `wake tito-pro.bae.staging.platform.tito.io: start g20: instance not healthy within 2m0s: Get "https://carlos/": http: server gave HTTP response to HTTPS client`: status.ReasonHealth, |
| + "shop.staging.example.com: instance not healthy within 30s: unhealthy: HTTP 502": status.ReasonHealth, |
| + "staged.example.com: exited before it was ready": status.ReasonExit, |
| + "digest.example.com: worker exited before it was observed": status.ReasonExit, |
| + "settle.example.com: instance not healthy within 30s: EOF": status.ReasonHealth, |
| + "reused.example.com: instance not healthy within 30s: EOF": status.ReasonHealth, |
| + "release.example.com: instance not healthy within 30s: EOF": status.ReasonHealth, |
| + `wake "app.staging.example.com": instance not healthy within 30s: EOF`: status.ReasonHealth, |
| + // The platform's own words still win, host or no host. |
| + "staging fallback for shop.staging.example.com: no such build": status.ReasonStaging, |
| + "shop.example.com: build v2 is staged at /a, not at its version's path /b": status.ReasonStaging, |
| + "staging: digest mismatch for shop.example.com": status.ReasonStaging, |
| + "shop.example.com: worker exited before it was observed": status.ReasonExit, |
| + `staged path "/opt/carlos/staging/app.bin" is not a regular file`: status.ReasonStaging, |
| + "release: the release command of build v2 exited with status 1 on shop.example.com": status.ReasonRelease, |
| + } { |
| + if got := reasonWord(text); got != want { |
| + t.Errorf("reasonWord(%q) = %q, want %q", text, got, want) |
| + } |
| + } |
| +} |