Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
51d780e
fix(errors): expose internal error text only in an explicit developme…
juicycleff Nov 16, 2026
9b5ab10
fix(health): keep raw check errors out of public health responses
juicycleff Nov 16, 2026
eb9f7c0
perf(metrics): share one render between scrapes and bound concurrent …
juicycleff Nov 16, 2026
cf000c5
fix(http): put a write deadline on every response that does not stream
juicycleff Nov 16, 2026
17495ae
fix(http): drop a WriteHeader that follows a failed body write
juicycleff Nov 16, 2026
a0e4f9e
fix(lifecycle): bound every shutdown step and exit on a second signal
juicycleff Nov 16, 2026
b5b75c2
fix(health): make readiness report the real result from the start and…
juicycleff Nov 16, 2026
2443b98
fix(config): leave the value out of invalid config warnings
juicycleff Nov 16, 2026
30c6434
fix(tracing): stop letting clients force trace sampling
juicycleff Nov 16, 2026
ee19049
fix(resilience): stop the circuit breaker serializing calls and getti…
juicycleff Nov 16, 2026
0b8b4dc
fix(debug): accept only local tools on the forge_debug server
juicycleff Nov 16, 2026
74881b1
style: satisfy golangci-lint in the ops fixes
juicycleff Nov 16, 2026
8c49966
test(config): match the invalid sample_ratio warning by key
juicycleff Nov 16, 2026
20080ce
Merge remote-tracking branch 'origin/main' into fix/ops-lifecycle
juicycleff Nov 18, 2026
d3bc3b7
test(lifecycle): keep the signal-driven shutdown tests off Windows
juicycleff Nov 18, 2026
6e418fd
test(observability): disable the health grace period so windows sees …
juicycleff Nov 18, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
158 changes: 156 additions & 2 deletions app.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"net/http"
"os"
"strings"
"time"
)

Expand Down Expand Up @@ -121,12 +122,72 @@ type AppConfig struct {
// "*.example.com", or "*" to allow any origin.
WebSocketOrigins []string

// HTTPWriteTimeout bounds how long the server spends writing one response.
// A client that requests a large body and never reads it otherwise pins a
// handler goroutine and a connection forever. Responses that stream (a
// WebSocket or other Upgrade, an SSE request, gRPC, or any route the router
// classifies as a stream) are exempt, so long-lived connections keep
// working. Zero means the default of 60s; negative disables the deadline.
HTTPWriteTimeout time.Duration

// Shutdown
ShutdownTimeout time.Duration // Default: 30s
ShutdownTimeout time.Duration // HTTP drain budget. Default: 30s
ShutdownSignals []os.Signal // Default: SIGINT, SIGTERM

// StopTimeout bounds the second half of a graceful shutdown: lifecycle
// hooks, extension stops and the DI container. It is separate from
// ShutdownTimeout, which the HTTP drain spends, so a slow drain cannot
// leave the extensions with no time at all. A step that overruns is
// abandoned and logged instead of blocking shutdown forever. Zero means
// the same value as ShutdownTimeout.
StopTimeout time.Duration

// ObservabilityGuard authorizes access to the detailed observability
// endpoints: the per-check detail of /_/health, /_/info and /_/metrics.
// Return false to deny. A denied /_/health caller still gets the overall
// status and the status of each check, without messages or details, and a
// denied /_/info or /_/metrics caller gets a 404. /_/health/live and
// /_/health/ready never consult the guard, so orchestrator probes keep
// working without credentials.
//
// Nil means /_/metrics and an enabled /_/info are open, and /_/health
// shows details only when Environment is explicitly a development one
// (development, dev, local or test).
ObservabilityGuard func(*http.Request) bool

// EnableInfoEndpoint registers /_/info, which lists the services,
// extensions, versions and Go version the app runs. Default: false.
EnableInfoEndpoint bool

// MetricsScrapeCacheTTL is how long a rendered /_/metrics response is
// reused. Concurrent scrapes inside the window share one render, so a
// burst of scrapers costs one gather and one encode. Zero means the
// default of 1s; negative disables the cache.
MetricsScrapeCacheTTL time.Duration

// TrustRemoteSampling makes the default trace sampler follow the sampled
// flag of an incoming traceparent. Off by default: the flag is whatever
// the client sent, so following it let any client have every request it
// made sampled and exported. Off, a request that carries a traceparent
// keeps its trace ID but is sampled at the configured ratio. Turn it on
// for a service only internal callers reach, so their traces stay whole.
// The forge config key tracing.trust_remote_sampling turns it on too.
TrustRemoteSampling bool

// ExposeInternalErrors decides whether 5xx responses carry the internal
// error text. Nil means it follows Environment: only an explicitly set
// development, dev, local or test environment exposes it. An unset or
// unrecognised environment, including staging and prod, redacts.
ExposeInternalErrors *bool

// Health
HealthGracePeriod time.Duration // Grace period after startup during which health endpoints always return 200. Default: 60s
// HealthGracePeriod is how long after startup /_/health answers 200 with
// status "starting" whatever the checks say, so a platform that uses it as
// a liveness probe does not kill an app whose dependencies are still
// warming up. Readiness (/_/health/ready) ignores it and reports the real
// result, so traffic is not routed to an instance that cannot serve it.
// Default: 60s
HealthGracePeriod time.Duration

// Extensions
Extensions []Extension // Extensions to register with the app
Expand Down Expand Up @@ -171,6 +232,11 @@ type AppConfig struct {
// metricsConfigSet records a WithAppMetricsConfig call, so a config equal
// to the defaults still counts as set in code.
metricsConfigSet bool

// environmentDefaulted marks the "development" that DefaultAppConfig puts
// in Environment as a placeholder rather than a choice. Security defaults
// treat it as unset; see environmentIsDevelopment.
environmentDefaulted bool
}

// DefaultAppConfig returns a default application configuration.
Expand Down Expand Up @@ -206,6 +272,8 @@ func DefaultAppConfig() AppConfig {
EnableEnvConfig: true, // Enabled by default
EnvSeparator: "_", // Standard separator
EnvOverridesFile: true, // Env takes precedence over files by default

environmentDefaulted: true,
}
}

Expand Down Expand Up @@ -244,6 +312,7 @@ func WithAppDescription(description string) AppOption {
func WithAppEnvironment(environment string) AppOption {
return func(c *AppConfig) {
c.Environment = environment
c.environmentDefaulted = false
}
}

Expand Down Expand Up @@ -485,6 +554,91 @@ func WithWebSocketOrigins(origins ...string) AppOption {
}
}

// WithHTTPWriteTimeout bounds how long the server spends writing one
// non-streaming response. See AppConfig.HTTPWriteTimeout. Pass a negative
// value to disable it.
func WithHTTPWriteTimeout(timeout time.Duration) AppOption {
return func(c *AppConfig) { c.HTTPWriteTimeout = timeout }
}

// WithStopTimeout sets the budget for stopping hooks, extensions and the DI
// container during shutdown. See AppConfig.StopTimeout.
func WithStopTimeout(timeout time.Duration) AppOption {
return func(c *AppConfig) { c.StopTimeout = timeout }
}

// WithObservabilityGuard restricts the detailed observability endpoints. The
// guard runs on every request to /_/health, /_/info and /_/metrics; see
// AppConfig.ObservabilityGuard for what a denied caller sees.
//
// forge.WithObservabilityGuard(func(r *http.Request) bool {
// return subtle.ConstantTimeCompare(
// []byte(r.Header.Get("X-Ops-Token")), []byte(token)) == 1
// })
func WithObservabilityGuard(guard func(*http.Request) bool) AppOption {
return func(c *AppConfig) { c.ObservabilityGuard = guard }
}

// WithInfoEndpoint registers /_/info. It is off by default because it lists
// the app's services, extensions and versions to whoever asks; pair it with
// WithObservabilityGuard anywhere beyond localhost.
func WithInfoEndpoint() AppOption {
return func(c *AppConfig) { c.EnableInfoEndpoint = true }
}

// WithMetricsScrapeCacheTTL sets how long a rendered /_/metrics response is
// reused. See AppConfig.MetricsScrapeCacheTTL.
func WithMetricsScrapeCacheTTL(ttl time.Duration) AppOption {
return func(c *AppConfig) { c.MetricsScrapeCacheTTL = ttl }
}

// WithTrustRemoteSampling makes the default trace sampler follow the sampled
// flag of incoming traceparent headers. Use it only for services that
// untrusted clients cannot reach. See AppConfig.TrustRemoteSampling.
func WithTrustRemoteSampling() AppOption {
return func(c *AppConfig) { c.TrustRemoteSampling = true }
}

// WithExposeInternalErrors overrides whether 5xx responses carry the internal
// error text, whatever the environment. See AppConfig.ExposeInternalErrors.
func WithExposeInternalErrors(expose bool) AppOption {
return func(c *AppConfig) { c.ExposeInternalErrors = &expose }
}

// developmentEnvironments are the Environment values that turn on the
// debugging defaults. Compared case-insensitively.
var developmentEnvironments = map[string]bool{
"development": true,
"dev": true,
"local": true,
"test": true,
}

// environmentIsDevelopment reports whether config names a development
// environment on purpose. An empty Environment is unset, and so is the
// "development" placeholder DefaultAppConfig fills in when nothing replaced
// it: an app deployed without setting its environment must get the
// production-safe behaviour, not the debugging one.
func environmentIsDevelopment(config AppConfig) bool {
env := strings.ToLower(strings.TrimSpace(config.Environment))
if env == "" || (config.environmentDefaulted && env == "development") {
return false
}

return developmentEnvironments[env]
}

// resolveExposeInternalErrors applies an explicit ExposeInternalErrors first
// and otherwise exposes error text only in an explicit development
// environment.
func resolveExposeInternalErrors(config AppConfig, devEnvironment bool) bool {
if config.ExposeInternalErrors != nil {
return *config.ExposeInternalErrors
}

return devEnvironment
}

// NewApp creates a new Forge application.
func NewApp(config AppConfig) App {
return newApp(config)
Expand Down
71 changes: 71 additions & 0 deletions app_error_exposure_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
package forge

import (
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/xraph/forge/internal/shared"
)

// 5xx bodies used to carry the internal error text in every environment
// except exactly "production", so an unset environment, "prod" or "staging"
// sent driver errors with hosts, users and databases to any client.
func TestExposeInternalErrors_OnlyExplicitDevelopment(t *testing.T) {
t.Setenv("OTEL_EXPORTER_OTLP_ENDPOINT", "")
t.Cleanup(func() { shared.SetExposeInternalErrors(false) })

tru, fals := true, false

cases := []struct {
name string
build func() App
expose bool
}{
{"New with no environment", func() App { return New() }, false},
{"DefaultAppConfig untouched", func() App { return NewApp(DefaultAppConfig()) }, false},
{"empty literal", func() App { return NewApp(AppConfig{}) }, false},
{"prod", func() App { return New(WithAppEnvironment("prod")) }, false},
{"staging", func() App { return New(WithAppEnvironment("staging")) }, false},
{"production", func() App { return New(WithAppEnvironment("production")) }, false},
{"qa", func() App { return New(WithAppEnvironment("qa")) }, false},
{"development option", func() App { return New(WithAppEnvironment("development")) }, true},
{"Development literal", func() App { return NewApp(AppConfig{Environment: "Development"}) }, true},
{"dev", func() App { return New(WithAppEnvironment("dev")) }, true},
{"local", func() App { return New(WithAppEnvironment("local")) }, true},
{"test", func() App { return New(WithAppEnvironment("test")) }, true},
{"override on in production", func() App {
return NewApp(AppConfig{Environment: "production", ExposeInternalErrors: &tru})
}, true},
{"override off in development", func() App {
return New(WithAppEnvironment("development"), WithExposeInternalErrors(false))
}, false},
{"override off literal", func() App {
return NewApp(AppConfig{Environment: "test", ExposeInternalErrors: &fals})
}, false},
}

for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
a := tc.build()

_ = a.Router().GET("/boom", func(Context) error {
return InternalError(errors.New(`pq: password authentication failed for user "app_rw" host=10.0.3.17 database=prod`))
})

w := httptest.NewRecorder()
a.Router().ServeHTTP(w, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/boom", nil))

if w.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500", w.Code)
}

leaked := strings.Contains(w.Body.String(), "10.0.3.17")
if leaked != tc.expose {
t.Errorf("error text in body = %v, want %v; body %s", leaked, tc.expose, w.Body.String())
}
})
}
}
Loading
Loading