Skip to content

fix: lock down observability endpoints, bound shutdown and stop leaking internal errors - #125

Merged
juicycleff merged 16 commits into
mainfrom
fix/ops-lifecycle
Nov 18, 2026
Merged

juicycleff merged 16 commits into
mainfrom
fix/ops-lifecycle

Conversation

@juicycleff

Copy link
Copy Markdown
Contributor

Fixes in the operational endpoints and app lifecycle, from a security and performance review. Every fix has a regression test.

Fixes

  • Health exposure: /_/health returned each extension's raw health error. In testing that included a database URL with its password. Raw errors now go to the log only. A new WithObservabilityGuard protects health details, /_/info and /_/metrics. Without a guard, health shows only statuses outside an explicit development environment. /_/info is opt-in.
  • Internal errors: 500 bodies included err.Error() in any environment not spelled exactly production. Text is now exposed only in an explicit development, dev, local or test environment. WithExposeInternalErrors overrides it.
  • Metrics: each anonymous scrape rebuilt everything, about 7 ms and 6 MB with 200 routes. Scrapes are now cached for 1 s (about 1 µs per cached scrape) and filtered scrapes are capped at 4 at once.
  • Slow readers: there was no write timeout, so clients that never read pinned handlers indefinitely. Non-streaming responses now get a write deadline (HTTPWriteTimeout, default 60 s). WebSocket, SSE, gRPC and stream routes are exempt.
  • Shutdown:
    • An extension whose Stop ignored its context hung Run forever, and later signals were swallowed. Every stop step now has its own deadline, and a second signal exits.
    • Failed BeforeRun hooks and a failed listen now stop the app.
    • AfterRun hook panics are recovered.
  • Trace sampling: any client could force 100% sampling by sending a sampled traceparent. Remote sampled parents are now sampled at the configured ratio, unless WithTrustRemoteSampling is set.
  • Circuit breaker: it ran calls one at a time under its lock and never recovered after its first trip. Both are fixed.
  • Readiness: it reported 200 for the first 60 s regardless of health. It now reports real status immediately and 503 during shutdown.
  • Debug server (forge_debug builds): now requires a loopback Host and Origin, and caps frame size.
  • Config warnings no longer log the invalid value.
  • A WriteHeader after a failed write is no longer passed on.

Behaviour changes

  • A plain New() redacts internal error text.
  • /_/info is off by default.
  • Without a guard and outside dev, /_/health returns only statuses. Status codes are unchanged.
  • Metrics responses are cached for 1 s.
  • Non-streaming responses served by Run have a 60 s write deadline. Long downloads need a higher or negative HTTPWriteTimeout.
  • Stop steps are bounded, and a second signal exits with status 1.
  • Readiness has no grace period and returns 503 while shutting down.
  • A client's sampled traceparent no longer forces sampling.
  • New options: WithHTTPWriteTimeout, WithStopTimeout, WithObservabilityGuard, WithInfoEndpoint, WithMetricsScrapeCacheTTL, WithTrustRemoteSampling, WithExposeInternalErrors.

Testing

  • go test -race passes for the root package, internal/metrics, internal/telemetry, internal/resilience, internal/shared and internal/health.
  • go build -tags forge_debug ./... compiles.
  • go test ./... passes except the tsc-gated TypeScript generator tests, which fail on main too.

…nt environment

5xx bodies carried the raw error text in every environment except exactly
"production". An app deployed with the environment unset, or set to "prod"
or "staging", sent driver errors to any client that could trigger one, and a
pq error names the host, the database and the user.

Error text is now exposed only when Environment is explicitly development,
dev, local or test (case-insensitive). Anything else redacts, including an
unset environment. Environment still defaults to "development" for
everything else it drives (log format, sampling ratio, the banner), but that
default is now recorded as a placeholder: an app built from New() or
DefaultAppConfig() without choosing an environment counts as unset and
redacts. WithAppEnvironment("development") or a literal AppConfig with
Environment "development" still exposes.

AppConfig.ExposeInternalErrors and WithExposeInternalErrors override the
environment either way. Logs keep the full error in every case.
/_/health, /_/info and /_/metrics are served on the main listener with no
way to restrict them. The extension health check put err.Error() into the
result's details, so /_/health returned whatever the extension's error
said: in practice a driver error with the DSN, user and password. /_/info
listed every service, extension and version to anyone, and an unhealthy
app logged a warning on every probe, since every probe reads the same
cached report.

- The extension check no longer puts the error in its result. The error is
  logged instead, once per distinct error rather than every check round,
  with a line when the extension recovers.
- AppConfig.ObservabilityGuard (WithObservabilityGuard) authorizes the
  detailed endpoints. A denied caller gets only the overall status and each
  check's status from /_/health, and a 404 from /_/info and /_/metrics.
  Without a guard, /_/health shows details only in an explicit development
  environment, since check messages are free text.
- /_/info is opt-in (EnableInfoEndpoint, WithInfoEndpoint), and warns when
  enabled outside development without a guard.
- The unhealthy warning is logged once per report instead of per request,
  and names the failing checks.

/_/health/live and /_/health/ready never consult the guard, so orchestrator
probes need no credentials.
…scrapes

/_/metrics handed every scrape to promhttp with no limits, and each one
walked every series and encoded all of them. With 200 routes that saw three
statuses each, a scrape cost about 7 ms of CPU and 5.9 MB of allocation for
a 1.7 MB body, so a handful of clients scraping in a loop could keep a core
busy for free.

The endpoint now goes through a scrape cache. Scrapes within
MetricsScrapeCacheTTL (default 1s, WithMetricsScrapeCacheTTL, negative to
disable) of each other are served from the last render, keyed by the
negotiated exposition format and by whether the client accepts gzip, so the
cache cannot grow with request headers. Renders run one at a time behind
the cache lock, which makes a burst of concurrent scrapes cost one render.
Scrapes that filter by name skip the cache and are capped at 4 in flight;
more get a 503. The promhttp handler is built once and each render is cut
off after 10s, Prometheus' default scrape timeout.

BenchmarkMetricsScrape (Apple M5 Max), per scrape:

  routes=0    180 us, 103 KB, 901 allocs  ->  1.1 us, 1.1 KB, 14 allocs
  routes=50   2.1 ms, 1.6 MB, 25771       ->  1.0 us, 1.1 KB, 14 allocs
  routes=200  6.9 ms, 5.9 MB, 100042      ->  0.8 us, 1.1 KB, 14 allocs

A scrape that misses the cache costs what it did before; at most one does
per TTL and format.
Run served with WriteTimeout 0 so that SSE, WebSocket and gRPC streams
would not be cut, and per-route timeouts default to 0 as well, so nothing
bounded a write. A client that requested a large body and never read it
pinned the handler goroutine and the connection indefinitely; twenty such
clients pinned twenty handlers.

Run now serves the router behind a per-request write deadline set with
http.ResponseController, HTTPWriteTimeout (WithHTTPWriteTimeout), 60s by
default and disabled when negative. Streams are exempt in two ways:

- by request headers, before routing: an Upgrade or Connection: upgrade, an
  extended CONNECT, Accept: text/event-stream, or a gRPC content type;
- by route kind, after routing: an outer middleware that shares the
  tracing and metrics route-match holder lifts the deadline when the router
  stamps a stream route (SSE, WebSocket, WebTransport), so an event stream
  opened without the Accept header is not cut either.

A handler that streams on an ordinary route can lift the deadline itself
with http.NewResponseController(w).SetWriteDeadline(time.Time{}). The
router is untouched; the deadline only applies when the app serves through
Run, not to a.Router() mounted in a server of the caller's own.
When a body write fails, the connection is already broken: the client went
away or a write deadline fired. The handler then returns the write error and
the error handler tries to send a 500, which reached net/http as a second
WriteHeader and was logged as "superfluous response.WriteHeader call" against
beforewrite.go, once per failed request, for what is not a handler bug.

The wrapper now remembers a failed Write or ReadFrom and drops a WriteHeader
after it. A second WriteHeader without a failed write in between still goes
through, so net/http keeps reporting real double writes.
An extension whose Stop ignored its context (select{} in the reproduction,
a driver Close or a queue drain in practice) blocked Run forever, and the
signal channel was read once, so every later SIGINT or SIGTERM was swallowed
and only kill -9 ended the process. Stop also reused the context the HTTP
drain had already spent, so every extension stop ran with a context that was
done before it started.

- The HTTP drain keeps ShutdownTimeout. Stop gets a fresh budget of its
  own, StopTimeout (WithStopTimeout), which defaults to ShutdownTimeout.
- Each stop step (hooks, health manager, every extension, the container,
  the metrics collector) runs in a goroutine and is waited on only until
  the budget is spent. A step that overruns is abandoned and logged and the
  following steps still run. A panicking step is logged too.
- Stop with a context that has no deadline is bounded by StopTimeout, and
  Stop with one that is already done still gives the steps StopTimeout
  instead of failing them all at once.
- The final metrics push, span export, profiler stop and log export each
  get their own 5s budget, so they still run when the stop budget is gone.
- A second shutdown signal logs and exits with status 1. The channel has
  two slots and is released with signal.Stop when Run returns.
- Run now stops the app when a BeforeRun hook fails or ListenAndServe
  fails (an address in use, typically) instead of returning with every
  extension still running.
- AfterRun hooks run on their own goroutine, where a panic killed the
  process; it is recovered and logged.
… 503 on shutdown

Readiness answered "ready" for the whole HealthGracePeriod (60s by default)
whatever the checks said. The extension health checks were registered after
the health manager's first round, so the cached report did not include them
until the next scheduled round, 30s later. And readiness stayed 200 while
the app shut down.

- /_/health/ready no longer applies the grace period. A failing readiness
  probe only takes the instance out of rotation, so there is nothing to
  protect, and routing traffic to an instance with a dead dependency is
  exactly what the probe is for. /_/health keeps the grace period, since
  platforms commonly use it as a liveness probe.
- Start runs a check round right after registering the extension checks,
  so the first report readiness answers from covers them.
- Readiness answers 503 "shutting down" as soon as a graceful shutdown or
  Stop begins. Liveness is unaffected.
bindConfig logged the raw value of every config key that failed to convert.
A value in the wrong place is often a secret: a bearer token set where a
headers map or a number belongs ends up in the log as plain text. The
warning now carries the key and the expected type only, which is enough to
find the bad value in the config source.
The default sampler was ParentBased(TraceIDRatioBased), and the server
middleware extracts the incoming traceparent, so a request whose
traceparent said "sampled" was always sampled. Any client could have every
request it made sampled and exported: 1000 of 1000 in production at a 0.1
ratio, against about 100 without the header. Sampling by the trace ID's
ratio alone would not stop it either, because TraceIDRatioBased reads the
ID's low bits and a client chooses the ID; sequential IDs all pass.

By default a remote parent that says "sampled" is now sampled at the
configured ratio, decided by a hash of the trace ID keyed with a random
per-process seed. A client cannot pick IDs that pass, and every span of a
trace still gets the same decision in this process. A remote "not sampled"
is still followed, since it can only lower a client's own share. The trace
ID and trace state are the caller's either way, so propagation is unchanged.

AppConfig.TrustRemoteSampling (WithTrustRemoteSampling, or
tracing.trust_remote_sampling in the forge config) restores following the
caller's decision, for services that only internal callers reach. Without
it, traces that cross several forge services are sampled again at each one.
Explicit OTEL_TRACES_SAMPLER choices other than the default are unchanged.
…ng stuck half-open

Execute held the breaker's mutex while fn ran, so every caller of a breaker
ran one at a time, and a caller with a short deadline waited behind a slow
call for as long as it took. Half-open never recovered: it compared
cumulative stats that were never reset against HalfOpenMaxRequests, so after
one trip every probe was rejected, and closing needed MaxRequests results
while only HalfOpenMaxRequests were admitted. Metrics were looked up in the
registry under the breaker's lock on every call, and the state-change
counter was incremented on every call after the first change.

- The lock covers admission and result recording only; fn runs unlocked.
- Each state keeps a window of its own results, reset on every change;
  the decisions read the window. GetStats still reports cumulative totals.
- Half-open counts its in-flight probes and admits HalfOpenMaxRequests
  (at least one). It closes once enough probes succeed to meet
  SuccessThreshold and reopens as soon as too many fail to reach it.
- A result from a call admitted before a state change updates the totals
  but not the new state's window.
- A context that is already done returns its error without running fn.
- Metric instruments are looked up once (again on UpdateConfig) and written
  after the lock is released; the state-change counter counts changes.
- The state-change log line reports the old state correctly.
The debug server listens on 127.0.0.1, but a browser on the same machine
can still reach it. Any web page could open a WebSocket to the debug port,
since browsers do not apply CORS to upgrades and the upgrade had no Origin
check, and read the snapshot: routes, config keys, services, extensions and
health. /state had no Host check, so DNS rebinding could read it through
any hostname. The read loop also sized a buffer from the frame length the
client sent.

Every route now requires a loopback Host (localhost, 127.0.0.1 or ::1, any
port) and an Origin that is empty or on a loopback host. The CLI and the
editor extension send neither a foreign Host nor an Origin, so they are
unaffected. Client frames over 64 KB close the connection, and payloads are
discarded as they are read instead of being buffered.

Only built with -tags forge_debug.
Rename the abandoned-step error to stepAbandonedError, give the new tests
request contexts, canonical header names and the blank lines wsl wants, and
spread the debug server's frame loop out the same way.
The warning no longer carries the value, so the test that looked for
"lots" in it now looks for the tracing.sample_ratio key.
@vercel

vercel Bot commented Nov 16, 2026 •

Copy link
Copy Markdown
Contributor

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated
forge Ready Ready Preview Nov 18, 2026 1:35am UTC

Request Review

@github-actions

Copy link
Copy Markdown
Contributor

Conventional Commits Validation

PR Title: valid
Commits: all 13 follow conventional format

@github-actions github-actions Bot added the fix label Nov 16, 2026
@codecov

codecov Bot commented Nov 16, 2026

Copy link
Copy Markdown

Two shutdown budget tests deliver SIGTERM and SIGINT to the test process
with syscall.Kill, which does not exist on Windows, so the root package
failed to compile there and the Windows test job failed. They now live in
lifecycle_shutdown_signal_test.go behind a !windows build tag. The other
shutdown budget tests still run on every platform.
@github-actions

Copy link
Copy Markdown
Contributor

Conventional Commits Validation

PR Title: valid
Commits: all 15 follow conventional format

@github-actions

Copy link
Copy Markdown
Contributor

Conventional Commits Validation

PR Title: valid
Commits: all 16 follow conventional format

@github-actions github-actions Bot added fix and removed fix labels Nov 18, 2026
@juicycleff
juicycleff merged commit 420b317 into main Nov 18, 2026
45 checks passed

This branch was successfully deployed

1 active deployment
Preview — 6e418fd2 Deployed Nov 18, 2026 by vercel[bot]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant