Skip to content

High-performance browser automation bridge and multi-instance orchestrator with advanced stealth injection and real-time dashboard.

fix: the dashboard config PUT mutates the live RuntimeConfig every save (PIN-268)

Luigi Agosti4b702dbd8f52
diff --git a/internal/config/live.go b/internal/config/live.go
new file mode 100644
index 00000000..e887e5dd
--- /dev/null
+++ b/internal/config/live.go
@@ -0,0 +1,44 @@
+package config
+
+import "sync/atomic"
+
+// Live is the one publication point for a runtime config that outlives the
+// goroutine which built it. Holders keep the Live, never the *RuntimeConfig it
+// currently answers, so a save publishes a NEW value instead of writing the
+// fields of an object other goroutines are already reading.
+type Live struct {
+ current atomic.Pointer[RuntimeConfig]
+}
+
+func NewLive(cfg *RuntimeConfig) *Live {
+ live := &Live{}
+ live.Publish(cfg)
+ return live
+}
+
+// Get answers the value in effect. The result is read-only by contract: mutating
+// it puts the process back in the race this type exists to close.
+func (l *Live) Get() *RuntimeConfig {
+ if l == nil {
+ return nil
+ }
+ return l.current.Load()
+}
+
+func (l *Live) Publish(cfg *RuntimeConfig) {
+ if l == nil {
+ return
+ }
+ l.current.Store(cfg)
+}
+
+// NextRuntimeConfig derives the value a save publishes: the file config applied to
+// a COPY of what is in effect, so the object readers hold is never written to.
+func NextRuntimeConfig(base *RuntimeConfig, fc *FileConfig) *RuntimeConfig {
+ next := CloneRuntimeConfig(base)
+ if next == nil {
+ return nil
+ }
+ ApplyFileConfigToRuntime(next, fc)
+ return next
+}
diff --git a/internal/dashboard/auth_api.go b/internal/dashboard/auth_api.go
index f77ca297..bff60533 100644
--- a/internal/dashboard/auth_api.go
+++ b/internal/dashboard/auth_api.go
@@ -16,14 +16,14 @@ import (
)
type AuthAPI struct {
- runtime *config.RuntimeConfig
+ live *config.Live
sessions *browsersession.Manager
loginLimiter *authn.AttemptLimiter
}
-func NewAuthAPI(runtime *config.RuntimeConfig, sessions *browsersession.Manager) *AuthAPI {
+func NewAuthAPI(live *config.Live, sessions *browsersession.Manager) *AuthAPI {
return &AuthAPI{
- runtime: runtime,
+ live: live,
sessions: sessions,
loginLimiter: authn.NewAttemptLimiter(authn.AttemptLimiterConfig{
Window: authn.DefaultLoginRateLimitWindow,
@@ -32,6 +32,25 @@ func NewAuthAPI(runtime *config.RuntimeConfig, sessions *browsersession.Manager)
}
}
+func (a *AuthAPI) cfg() *config.RuntimeConfig {
+ if a == nil {
+ return nil
+ }
+ return a.live.Get()
+}
+
+func (a *AuthAPI) token() string {
+ cfg := a.cfg()
+ if cfg == nil {
+ return ""
+ }
+ return cfg.Token
+}
+
+func cookieTrustsProxy(cfg *config.RuntimeConfig) bool {
+ return cfg != nil && cfg.TrustProxyHeaders
+}
+
func (a *AuthAPI) RegisterHandlers(mux *http.ServeMux) {
mux.HandleFunc("POST /api/auth/login", a.HandleLogin)
mux.HandleFunc("POST /api/auth/elevate", a.HandleElevate)
@@ -39,7 +58,7 @@ func (a *AuthAPI) RegisterHandlers(mux *http.ServeMux) {
}
func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {
- token := strings.TrimSpace(a.runtime.Token)
+ token := strings.TrimSpace(a.token())
if token == "" {
httpx.ErrorCode(w, http.StatusServiceUnavailable, "token_required", "server token is not configured", false, nil)
return
@@ -94,7 +113,7 @@ func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {
if a.loginLimiter != nil {
a.loginLimiter.RecordFailure(clientIP)
}
- authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders, cookieSecureSetting(a.runtime))
+ authn.ClearSessionCookie(w, r, cookieTrustsProxy(a.cfg()), cookieSecureSetting(a.cfg()))
authn.AuditWarn(r, "auth.login_failed", "reason", "bad_token")
httpx.Unauthorized(w, httpx.CodeBadToken, provided)
return
@@ -116,7 +135,7 @@ func (a *AuthAPI) HandleLogin(w http.ResponseWriter, r *http.Request) {
httpx.Error(w, http.StatusInternalServerError, err)
return
}
- authn.SetSessionCookie(w, r, sessionID, a.sessions.MaxLifetime(), a.runtime != nil && a.runtime.TrustProxyHeaders, cookieSecureSetting(a.runtime))
+ authn.SetSessionCookie(w, r, sessionID, a.sessions.MaxLifetime(), cookieTrustsProxy(a.cfg()), cookieSecureSetting(a.cfg()))
authn.AuditLog(r, "auth.session_created",
"sessionIdleSec", int(a.sessions.IdleTimeout().Seconds()),
"sessionMaxLifetimeSec", int(a.sessions.MaxLifetime().Seconds()),
@@ -131,12 +150,12 @@ func (a *AuthAPI) HandleLogout(w http.ResponseWriter, r *http.Request) {
authn.AuditLog(r, "auth.session_revoked", "reason", "logout")
}
}
- authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders, cookieSecureSetting(a.runtime))
+ authn.ClearSessionCookie(w, r, cookieTrustsProxy(a.cfg()), cookieSecureSetting(a.cfg()))
httpx.JSON(w, http.StatusOK, map[string]string{"status": "ok"})
}
func (a *AuthAPI) HandleElevate(w http.ResponseWriter, r *http.Request) {
- token := strings.TrimSpace(a.runtime.Token)
+ token := strings.TrimSpace(a.token())
if token == "" {
httpx.ErrorCode(w, http.StatusServiceUnavailable, "token_required", "server token is not configured", false, nil)
return
@@ -172,7 +191,7 @@ func (a *AuthAPI) HandleElevate(w http.ResponseWriter, r *http.Request) {
return
}
if !a.sessions.Elevate(creds.Value, token) {
- authn.ClearSessionCookie(w, r, a.runtime != nil && a.runtime.TrustProxyHeaders, cookieSecureSetting(a.runtime))
+ authn.ClearSessionCookie(w, r, cookieTrustsProxy(a.cfg()), cookieSecureSetting(a.cfg()))
httpx.Unauthorized(w, httpx.CodeBadToken, "")
return
}
@@ -192,10 +211,11 @@ func cookieSecureSetting(cfg *config.RuntimeConfig) *bool {
}
func (a *AuthAPI) requiresHTTPSForDashboardSession(r *http.Request) bool {
- if a == nil || a.runtime == nil || a.runtime.CookieSecure == nil || !*a.runtime.CookieSecure {
+ cfg := a.cfg()
+ if cfg == nil || cfg.CookieSecure == nil || !*cfg.CookieSecure {
return false
}
- return !authn.RequestIsHTTPS(r, a.runtime.TrustProxyHeaders)
+ return !authn.RequestIsHTTPS(r, cfg.TrustProxyHeaders)
}
func secondsCeil(d time.Duration) int {
diff --git a/internal/dashboard/auth_api_test.go b/internal/dashboard/auth_api_test.go
index d06e87f4..308c46f2 100644
--- a/internal/dashboard/auth_api_test.go
+++ b/internal/dashboard/auth_api_test.go
@@ -14,7 +14,7 @@ import (
func TestAuthAPIHandleLogin(t *testing.T) {
sessions := browsersession.NewManager(browsersession.Config{})
- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, sessions)
req := httptest.NewRequest("POST", "https://pinchtab.example/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))
req.Header.Set("Content-Type", "application/json")
@@ -52,7 +52,7 @@ func TestAuthAPIHandleLogin(t *testing.T) {
func TestAuthAPIHandleLogin_LocalhostHTTPUsesNonSecureCookie(t *testing.T) {
sessions := browsersession.NewManager(browsersession.Config{})
- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, sessions)
req := httptest.NewRequest("POST", "http://localhost:9867/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))
req.Host = "localhost:9867"
@@ -75,7 +75,7 @@ func TestAuthAPIHandleLogin_LocalhostHTTPUsesNonSecureCookie(t *testing.T) {
func TestAuthAPIHandleLogin_LANHTTPUsesNonSecureCookie(t *testing.T) {
sessions := browsersession.NewManager(browsersession.Config{})
- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, sessions)
req := httptest.NewRequest("POST", "http://192.168.1.50:9867/api/auth/login", strings.NewReader(`{"token":"secret-token"}`))
req.Host = "192.168.1.50:9867"
@@ -98,7 +98,7 @@ func TestAuthAPIHandleLogin_LANHTTPUsesNonSecureCookie(t *testing.T) {
func TestAuthAPIHandleLogin_TrustedProxyHTTPSUsesSecureCookie(t *testing.T) {
sessions := browsersession.NewManager(browsersession.Config{})
- api := NewAuthAPI(&config.RuntimeConfig{
+ api := newAuthAPIForTest(&config.RuntimeConfig{
Token: "secret-token",
TrustProxyHeaders: true,
}, sessions)
@@ -127,7 +127,7 @@ func TestAuthAPIHandleLogin_TrustedProxyHTTPSUsesSecureCookie(t *testing.T) {
func TestAuthAPIHandleLogin_CookieSecureFalseOverridesHTTPS(t *testing.T) {
sessions := browsersession.NewManager(browsersession.Config{})
forceInsecure := false
- api := NewAuthAPI(&config.RuntimeConfig{
+ api := newAuthAPIForTest(&config.RuntimeConfig{
Token: "secret-token",
CookieSecure: &forceInsecure,
}, sessions)
@@ -153,7 +153,7 @@ func TestAuthAPIHandleLogin_CookieSecureFalseOverridesHTTPS(t *testing.T) {
func TestAuthAPIHandleLogin_CookieSecureTrueRejectsPlainHTTP(t *testing.T) {
sessions := browsersession.NewManager(browsersession.Config{})
forceSecure := true
- api := NewAuthAPI(&config.RuntimeConfig{
+ api := newAuthAPIForTest(&config.RuntimeConfig{
Token: "secret-token",
CookieSecure: &forceSecure,
}, sessions)
@@ -177,7 +177,7 @@ func TestAuthAPIHandleLogin_CookieSecureTrueRejectsPlainHTTP(t *testing.T) {
}
func TestAuthAPIHandleLoginRejectsBadToken(t *testing.T) {
- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, browsersession.NewManager(browsersession.Config{}))
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, browsersession.NewManager(browsersession.Config{}))
req := httptest.NewRequest("POST", "/api/auth/login", strings.NewReader(`{"token":"wrong"}`))
req.Header.Set("Content-Type", "application/json")
@@ -200,7 +200,7 @@ func TestAuthAPIHandleLogoutClearsCookie(t *testing.T) {
if err != nil {
t.Fatalf("Create() error = %v", err)
}
- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, sessions)
req := httptest.NewRequest("POST", "https://pinchtab.example/api/auth/logout", nil)
req.AddCookie(&http.Cookie{Name: authn.CookieName, Value: sessionID})
@@ -229,7 +229,7 @@ func TestAuthAPIHandleLogout_LocalhostHTTPClearsNonSecureCookie(t *testing.T) {
if err != nil {
t.Fatalf("Create() error = %v", err)
}
- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, sessions)
req := httptest.NewRequest("POST", "http://localhost:9867/api/auth/logout", nil)
req.Host = "localhost:9867"
@@ -256,7 +256,7 @@ func TestAuthAPIHandleLogout_LANHTTPClearsNonSecureCookie(t *testing.T) {
if err != nil {
t.Fatalf("Create() error = %v", err)
}
- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, sessions)
req := httptest.NewRequest("POST", "http://192.168.1.50:9867/api/auth/logout", nil)
req.Host = "192.168.1.50:9867"
@@ -283,7 +283,7 @@ func TestAuthAPIHandleElevateMarksSessionElevated(t *testing.T) {
if err != nil {
t.Fatalf("Create() error = %v", err)
}
- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, sessions)
req := httptest.NewRequest("POST", "/api/auth/elevate", strings.NewReader(`{"token":"secret-token"}`))
req.Header.Set("Content-Type", "application/json")
@@ -306,7 +306,7 @@ func TestAuthAPIHandleElevateRejectsBadToken(t *testing.T) {
if err != nil {
t.Fatalf("Create() error = %v", err)
}
- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, sessions)
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, sessions)
req := httptest.NewRequest("POST", "/api/auth/elevate", strings.NewReader(`{"token":"wrong"}`))
req.Header.Set("Content-Type", "application/json")
@@ -324,7 +324,7 @@ func TestAuthAPIHandleElevateRejectsBadToken(t *testing.T) {
}
func TestAuthAPIHandleLoginRateLimitsRepeatedFailures(t *testing.T) {
- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, browsersession.NewManager(browsersession.Config{}))
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, browsersession.NewManager(browsersession.Config{}))
api.loginLimiter = authn.NewAttemptLimiter(authn.AttemptLimiterConfig{
Window: time.Minute,
MaxAttempts: 1,
@@ -353,7 +353,7 @@ func TestAuthAPIHandleLoginRateLimitsRepeatedFailures(t *testing.T) {
}
func TestAuthAPIHandleLoginRateLimitIgnoresSpoofedForwardedHeaders(t *testing.T) {
- api := NewAuthAPI(&config.RuntimeConfig{Token: "secret-token"}, browsersession.NewManager(browsersession.Config{}))
+ api := newAuthAPIForTest(&config.RuntimeConfig{Token: "secret-token"}, browsersession.NewManager(browsersession.Config{}))
api.loginLimiter = authn.NewAttemptLimiter(authn.AttemptLimiterConfig{
Window: time.Minute,
MaxAttempts: 1,
diff --git a/internal/dashboard/config_api.go b/internal/dashboard/config_api.go
index f8c468cf..4968d1d2 100644
--- a/internal/dashboard/config_api.go
+++ b/internal/dashboard/config_api.go
@@ -30,7 +30,7 @@ type agentCounter interface {
}
type ConfigAPI struct {
- runtime *config.RuntimeConfig
+ live *config.Live
instances InstanceLister
profiles profileLister
applier runtimeConfigApplier
@@ -60,7 +60,7 @@ type configEnvelope struct {
}
func NewConfigAPI(
- runtime *config.RuntimeConfig,
+ live *config.Live,
instances InstanceLister,
profiles profileLister,
applier runtimeConfigApplier,
@@ -75,7 +75,7 @@ func NewConfigAPI(
boot = *fc
}
return &ConfigAPI{
- runtime: runtime,
+ live: live,
instances: instances,
profiles: profiles,
applier: applier,
@@ -86,6 +86,15 @@ func NewConfigAPI(
}
}
+// cfg is the one read of the published runtime config, shared with the
+// orchestrator and the auth API so a save is seen by all three at once.
+func (c *ConfigAPI) cfg() *config.RuntimeConfig {
+ if c == nil {
+ return nil
+ }
+ return c.live.Get()
+}
+
func (c *ConfigAPI) SetSessionManager(sessions *browsersession.Manager) {
if c == nil {
return
@@ -207,12 +216,15 @@ func (c *ConfigAPI) persistAndApply(w http.ResponseWriter, normalized *config.Fi
// writes landing in the same filesystem mtime tick.
c.cfgCacheValid = false
- config.ApplyFileConfigToRuntime(c.runtime, normalized)
+ // A save publishes a NEW value; the object the orchestrator's goroutines are
+ // already reading is never written to.
+ next := config.NextRuntimeConfig(c.cfg(), normalized)
+ c.live.Publish(next)
if c.sessions != nil {
- c.sessions.UpdateConfig(BrowserSessionConfig(c.runtime))
+ c.sessions.UpdateConfig(BrowserSessionConfig(next))
}
if c.applier != nil {
- c.applier.ApplyRuntimeConfig(c.runtime)
+ c.applier.ApplyRuntimeConfig(next)
}
return true
}
@@ -234,14 +246,15 @@ func (c *ConfigAPI) respondConfigUpdated(w http.ResponseWriter, r *http.Request,
}
func (c *ConfigAPI) hasConfigWriteElevation(r *http.Request) bool {
- if c == nil || c.runtime == nil || strings.TrimSpace(c.runtime.Token) == "" {
+ cfg := c.cfg()
+ if cfg == nil || strings.TrimSpace(cfg.Token) == "" {
return true
}
creds := authn.CredentialsFromRequest(r)
if creds.Method != authn.MethodCookie {
return true
}
- return c.sessions != nil && c.sessions.IsElevated(creds.Value, c.runtime.Token)
+ return c.sessions != nil && c.sessions.IsElevated(creds.Value, cfg.Token)
}
func (c *ConfigAPI) currentConfig() (config.FileConfig, string, []string, error) {
diff --git a/internal/dashboard/config_api_test.go b/internal/dashboard/config_api_test.go
index 7e3d42b4..5606dd2f 100644
--- a/internal/dashboard/config_api_test.go
+++ b/internal/dashboard/config_api_test.go
@@ -64,7 +64,7 @@ func TestNewConfigAPISnapshotsBootConfigFromFile(t *testing.T) {
}
runtime := config.Load()
- api := NewConfigAPI(runtime, nil, nil, nil, nil, "test", time.Now())
+ api := newConfigAPIForTest(runtime, nil, nil, nil, nil, "test", time.Now())
if api.boot.MultiInstance.Restart.MaxRestarts != nil {
t.Fatalf("boot restart maxRestarts = %v, want nil from file snapshot", *api.boot.MultiInstance.Restart.MaxRestarts)
@@ -97,7 +97,7 @@ func TestCurrentConfigCachesByMtime(t *testing.T) {
}
origMtime := info.ModTime()
- api := NewConfigAPI(config.Load(), nil, nil, nil, nil, "test", time.Now())
+ api := newConfigAPIForTest(config.Load(), nil, nil, nil, nil, "test", time.Now())
cfg, _, _, err := api.currentConfig()
if err != nil {
@@ -139,7 +139,7 @@ func TestCurrentConfigCachesByMtime(t *testing.T) {
func TestRestartReasonsIncludeStealthLevel(t *testing.T) {
cfg := config.DefaultFileConfig()
- api := NewConfigAPI(config.Load(), nil, nil, nil, nil, "test", time.Now())
+ api := newConfigAPIForTest(config.Load(), nil, nil, nil, nil, "test", time.Now())
api.boot = cfg
next := cfg
@@ -153,7 +153,7 @@ func TestRestartReasonsIncludeStealthLevel(t *testing.T) {
func TestRestartReasonsIncludeSecurityPolicy(t *testing.T) {
cfg := config.DefaultFileConfig()
- api := NewConfigAPI(config.Load(), nil, nil, nil, nil, "test", time.Now())
+ api := newConfigAPIForTest(config.Load(), nil, nil, nil, nil, "test", time.Now())
api.boot = cfg
// Editing the allowlist changes the boot-snapshotted IDPI/security policy, so
@@ -596,7 +596,7 @@ func newConfigAPIOverFile(t *testing.T, data []byte) *ConfigAPI {
t.Fatalf("WriteFile() error = %v", err)
}
- return NewConfigAPI(config.Load(), nil, nil, nil, nil, "test", time.Now())
+ return newConfigAPIForTest(config.Load(), nil, nil, nil, nil, "test", time.Now())
}
func decodeConfigEnvelope(t *testing.T, w *httptest.ResponseRecorder) configEnvelope {
diff --git a/internal/dashboard/config_changes_test.go b/internal/dashboard/config_changes_test.go
index b17985de..532309df 100644
--- a/internal/dashboard/config_changes_test.go
+++ b/internal/dashboard/config_changes_test.go
@@ -50,7 +50,7 @@ func TestSameConfigSectionTreatsUnmarshalableValuesAsChanged(t *testing.T) {
func TestRestartReasonsIgnoreAbsentVersusEmptyContainers(t *testing.T) {
boot := config.DefaultFileConfig()
- api := NewConfigAPI(config.Load(), nil, nil, nil, nil, "test", time.Now())
+ api := newConfigAPIForTest(config.Load(), nil, nil, nil, nil, "test", time.Now())
api.boot = boot
next := boot
diff --git a/internal/dashboard/config_health.go b/internal/dashboard/config_health.go
index d16d1dfa..d435fda4 100644
--- a/internal/dashboard/config_health.go
+++ b/internal/dashboard/config_health.go
@@ -76,12 +76,13 @@ func (c *ConfigAPI) healthInfo(includeSecurity bool) (healthEnvelope, error) {
if c.agents != nil {
agentCount = c.agents.AgentCount()
}
+ cfg := c.cfg()
out := healthEnvelope{
Status: "ok",
Mode: "dashboard",
Version: c.version,
Uptime: int64(time.Since(c.startedAt).Milliseconds()),
- AuthRequired: strings.TrimSpace(c.runtime.Token) != "",
+ AuthRequired: cfg != nil && strings.TrimSpace(cfg.Token) != "",
Profiles: profileCount,
QuarantinedProfiles: quarantinedCount,
Instances: instanceCount,
@@ -91,7 +92,7 @@ func (c *ConfigAPI) healthInfo(includeSecurity bool) (healthEnvelope, error) {
RestartReasons: restartReasons,
}
if includeSecurity {
- security := runtimeSecurityInfo(c.runtime)
+ security := runtimeSecurityInfo(cfg)
out.Security = &security
}
return out, nil
diff --git a/internal/dashboard/config_live_test.go b/internal/dashboard/config_live_test.go
new file mode 100644
index 00000000..e61697b0
--- /dev/null
+++ b/internal/dashboard/config_live_test.go
@@ -0,0 +1,27 @@
+package dashboard
+
+import (
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/browsersession"
+ "github.com/pinchtab/pinchtab/internal/config"
+)
+
+// The APIs hold the shared publication point, not a config pointer. Tests that
+// only care about one config wrap it in a Live of its own here rather than
+// spelling the wrapper at every call.
+func newConfigAPIForTest(
+ runtime *config.RuntimeConfig,
+ instances InstanceLister,
+ profiles profileLister,
+ applier runtimeConfigApplier,
+ agents agentCounter,
+ version string,
+ startedAt time.Time,
+) *ConfigAPI {
+ return NewConfigAPI(config.NewLive(runtime), instances, profiles, applier, agents, version, startedAt)
+}
+
+func newAuthAPIForTest(runtime *config.RuntimeConfig, sessions *browsersession.Manager) *AuthAPI {
+ return NewAuthAPI(config.NewLive(runtime), sessions)
+}
diff --git a/internal/dashboard/config_redaction.go b/internal/dashboard/config_redaction.go
index bae5b313..5500174e 100644
--- a/internal/dashboard/config_redaction.go
+++ b/internal/dashboard/config_redaction.go
@@ -7,7 +7,7 @@ import (
)
func (c *ConfigAPI) tokenConfigured(cfg config.FileConfig) bool {
- if c != nil && c.runtime != nil && strings.TrimSpace(c.runtime.Token) != "" {
+ if runtime := c.cfg(); runtime != nil && strings.TrimSpace(runtime.Token) != "" {
return true
}
return strings.TrimSpace(cfg.Server.Token) != ""
diff --git a/internal/orchestrator/browser_preflight.go b/internal/orchestrator/browser_preflight.go
index 011c28d8..b30c9869 100644
--- a/internal/orchestrator/browser_preflight.go
+++ b/internal/orchestrator/browser_preflight.go
@@ -24,16 +24,17 @@ import (
// bridge/runtime.InitBrowser, including default-target promotion, so it can't
// diverge from what the instance would actually try to launch.
func (o *Orchestrator) BrowserUnavailableReason(r *http.Request) (string, bool) {
- if o == nil || o.runtimeCfg == nil {
+ cfg := o.cfg()
+ if cfg == nil {
return "", false
}
if ExtractRequestedBrowser(r) != "" {
return "", false
}
- if strings.TrimSpace(o.runtimeCfg.CDPAttachURL) != "" {
+ if strings.TrimSpace(cfg.CDPAttachURL) != "" {
return "", false // attaching to an external CDP endpoint; no local binary needed
}
- effective := runtimekit.ResolveEffectiveBrowser(o.runtimeCfg)
+ effective := runtimekit.ResolveEffectiveBrowser(cfg)
provider := effective.ID
if _, ok := browsers.Get(provider); !ok {
return "", false
diff --git a/internal/orchestrator/browser_preflight_test.go b/internal/orchestrator/browser_preflight_test.go
index bd54e219..1d6434c8 100644
--- a/internal/orchestrator/browser_preflight_test.go
+++ b/internal/orchestrator/browser_preflight_test.go
@@ -20,10 +20,10 @@ func TestBrowserUnavailableReason(t *testing.T) {
}
t.Run("missing browser.binary override is reported", func(t *testing.T) {
- o := &Orchestrator{runtimeCfg: &config.RuntimeConfig{
+ o := orchWithConfig(&config.RuntimeConfig{
DefaultBrowser: "chrome",
BrowserBinary: filepath.Join(t.TempDir(), "missing"),
- }}
+ })
reason, unavailable := o.BrowserUnavailableReason(req("/text?url=http://x/"))
if !unavailable {
t.Fatal("expected a missing override to be reported unavailable")
@@ -34,17 +34,17 @@ func TestBrowserUnavailableReason(t *testing.T) {
})
t.Run("existing override is available", func(t *testing.T) {
- o := &Orchestrator{runtimeCfg: &config.RuntimeConfig{
+ o := orchWithConfig(&config.RuntimeConfig{
DefaultBrowser: "chrome",
BrowserBinary: existing,
- }}
+ })
if _, unavailable := o.BrowserUnavailableReason(req("/text?url=http://x/")); unavailable {
t.Error("an existing override binary should be available")
}
})
t.Run("default target binary is available", func(t *testing.T) {
- o := &Orchestrator{runtimeCfg: &config.RuntimeConfig{
+ o := orchWithConfig(&config.RuntimeConfig{
DefaultBrowser: config.BrowserChrome,
Targets: config.BrowserTargetsConfig{
"only": {
@@ -52,17 +52,17 @@ func TestBrowserUnavailableReason(t *testing.T) {
Binary: existing,
},
},
- }}
+ })
if _, unavailable := o.BrowserUnavailableReason(req("/text?url=http://x/")); unavailable {
t.Error("an existing default-target binary should be available")
}
})
t.Run("explicit per-request browser falls through", func(t *testing.T) {
- o := &Orchestrator{runtimeCfg: &config.RuntimeConfig{
+ o := orchWithConfig(&config.RuntimeConfig{
DefaultBrowser: "chrome",
BrowserBinary: filepath.Join(t.TempDir(), "missing"),
- }}
+ })
// An explicit ?browser= override must not be short-circuited here.
if _, unavailable := o.BrowserUnavailableReason(req("/text?browser=chrome&url=http://x/")); unavailable {
t.Error("explicit per-request browser should fall through, not fast-fail")
@@ -70,11 +70,11 @@ func TestBrowserUnavailableReason(t *testing.T) {
})
t.Run("external CDP attach falls through", func(t *testing.T) {
- o := &Orchestrator{runtimeCfg: &config.RuntimeConfig{
+ o := orchWithConfig(&config.RuntimeConfig{
DefaultBrowser: "chrome",
BrowserBinary: filepath.Join(t.TempDir(), "missing"),
CDPAttachURL: "http://127.0.0.1:9222",
- }}
+ })
if _, unavailable := o.BrowserUnavailableReason(req("/text?url=http://x/")); unavailable {
t.Error("CDP attach needs no local binary; should fall through")
}
diff --git a/internal/orchestrator/child_config.go b/internal/orchestrator/child_config.go
index 63246875..d6350c55 100644
--- a/internal/orchestrator/child_config.go
+++ b/internal/orchestrator/child_config.go
@@ -13,8 +13,8 @@ import (
func (o *Orchestrator) childInstanceBaseURL(port string) string {
host := configuredChildInstanceHost("")
- if o != nil && o.runtimeCfg != nil {
- host = configuredChildInstanceHost(o.runtimeCfg.Bind)
+ if cfg := o.cfg(); cfg != nil {
+ host = configuredChildInstanceHost(cfg.Bind)
}
return httpBaseURL(host, port)
}
@@ -33,10 +33,10 @@ func portConflictError(port string, inspection PortInspection) error {
return fmt.Errorf("instance port %s is already in use on this machine", port)
}
-// buildChildFileConfig builds the per-child FileConfig; nil effectiveCfg falls back to o.runtimeCfg.
+// buildChildFileConfig builds the per-child FileConfig; nil effectiveCfg falls back to o.cfg().
func (o *Orchestrator) buildChildFileConfig(effectiveCfg *config.RuntimeConfig, port string, cdpPort int, profilePath, instanceStateDir string, headless bool, extensionPaths []string, securityPolicy *bridge.SecurityPolicy) config.FileConfig {
if effectiveCfg == nil {
- effectiveCfg = o.runtimeCfg
+ effectiveCfg = o.cfg()
}
fc := config.FileConfigFromRuntime(effectiveCfg)
fc.Server.Port = port
@@ -94,7 +94,7 @@ func (o *Orchestrator) writeChildConfig(effectiveCfg *config.RuntimeConfig, port
// writeAttachChildConfig writes a minimal child config for a CDP-attach bridge; RemoteCDPURL is passed via CLI flags.
func (o *Orchestrator) writeAttachChildConfig(port, provider, stateDir string) (string, error) {
- fc := config.FileConfigFromRuntime(o.runtimeCfg)
+ fc := config.FileConfigFromRuntime(o.cfg())
fc.Server.Port = port
fc.Server.StateDir = stateDir
activityEnabled := false
diff --git a/internal/orchestrator/config_publication_test.go b/internal/orchestrator/config_publication_test.go
new file mode 100644
index 00000000..ace47d95
--- /dev/null
+++ b/internal/orchestrator/config_publication_test.go
@@ -0,0 +1,151 @@
+package orchestrator
+
+import (
+ "sync"
+ "testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/srccensus"
+)
+
+// orchWithConfig is the bare-struct orchestrator these tests want, with a config
+// already published. The Live is a value field, so the zero orchestrator is
+// usable and publishing is the only way in — there is no pointer for a test to
+// keep and write through afterwards.
+func orchWithConfig(cfg *config.RuntimeConfig) *Orchestrator {
+ o := &Orchestrator{}
+ o.LiveConfig().Publish(cfg)
+ return o
+}
+
+// republishCfg is how a test changes a setting: it derives a new value and
+// publishes it, the same discipline the dashboard save follows. Writing the
+// fields of the published object instead would be the very race this package's
+// accessors exist to close.
+func republishCfg(o *Orchestrator, mutate func(*config.RuntimeConfig)) {
+ next := config.CloneRuntimeConfig(o.cfg())
+ if next == nil {
+ next = &config.RuntimeConfig{}
+ }
+ mutate(next)
+ o.LiveConfig().Publish(next)
+}
+
+// A publish is a whole-value swap, so one read of the published config is
+// internally coherent: a reader never sees the token from one save and the
+// evaluate policy from the next. The assertion cannot fail while the value is
+// immutable — the test earns its place under -race, which is what reports the
+// swap going back to a field-by-field write.
+func TestOneReadOfThePublishedConfigIsCoherentUnderConcurrentPublishes(t *testing.T) {
+ tokenFor := func(evaluate bool) string {
+ if evaluate {
+ return "evaluating"
+ }
+ return "refusing"
+ }
+ publish := func(evaluate bool) *config.RuntimeConfig {
+ return &config.RuntimeConfig{
+ Token: tokenFor(evaluate),
+ AllowEvaluate: evaluate,
+ InstancePortStart: 9868,
+ InstancePortEnd: 9968,
+ }
+ }
+ o := orchWithConfig(publish(false))
+
+ var wg sync.WaitGroup
+ stop := make(chan struct{})
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ cfg := o.cfg()
+ if cfg.Token != tokenFor(cfg.AllowEvaluate) {
+ t.Errorf("one read saw token %q with allowEvaluate=%v, which no published config carries", cfg.Token, cfg.AllowEvaluate)
+ return
+ }
+ }
+ }()
+
+ for i := 0; i < 500; i++ {
+ o.ApplyRuntimeConfig(publish(i%2 == 0))
+ }
+ close(stop)
+ wg.Wait()
+}
+
+// The token and the evaluate policy are derived from the published config rather
+// than copied into fields, so there is no second copy that can lag behind it.
+func TestTheTokenAndEvaluatePolicyFollowTheAppliedConfig(t *testing.T) {
+ o := orchWithConfig(nil)
+
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{Token: "first", AllowEvaluate: true})
+ if o.cfgToken() != "first" || !o.AllowsEvaluate() {
+ t.Fatalf("token=%q allowEvaluate=%v after the first apply", o.cfgToken(), o.AllowsEvaluate())
+ }
+
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{Token: "second", AllowEvaluate: false})
+ if o.cfgToken() != "second" || o.AllowsEvaluate() {
+ t.Fatalf("token=%q allowEvaluate=%v after the second apply", o.cfgToken(), o.AllowsEvaluate())
+ }
+
+ o.ApplyRuntimeConfig(nil)
+ if o.cfgToken() != "" || o.AllowsEvaluate() {
+ t.Fatalf("token=%q allowEvaluate=%v after clearing the config", o.cfgToken(), o.AllowsEvaluate())
+ }
+}
+
+// The accessors are only worth having if nothing goes around them. A new reader
+// that touches o.live or o.portAllocator directly reads a value nobody
+// synchronised, which is the defect this package was carrying — so the census
+// names the file and line rather than waiting for -race to catch it on a lucky
+// interleaving.
+func TestThePublishedConfigAndThePortAllocatorAreOnlyTouchedByTheirAccessors(t *testing.T) {
+ pkg := srccensus.Load(t, ".", 20)
+
+ // The constructor sets both fields through composite-literal keys, which are not
+ // selectors and so never appear here; the accessors are the whole population.
+ owners := map[string][]string{
+ "live": {"cfg", "ApplyRuntimeConfig", "LiveConfig"},
+ "portAllocator": {"ports", "SetPortRange"},
+ }
+ for field, ownerNames := range owners {
+ spans := make(map[string]srccensus.Func, len(ownerNames))
+ for _, name := range ownerNames {
+ fn, ok := pkg.Func(name)
+ if !ok {
+ t.Fatalf("owner %s of o.%s no longer exists in %s; re-point this census at whatever replaced it", name, field, pkg.Dir())
+ }
+ spans[name] = fn
+ }
+
+ sites := pkg.FieldReferences(field)
+ if len(sites) < len(ownerNames) {
+ t.Fatalf("only %d reference(s) to o.%s for %d accessor(s); the census is matching almost nothing and would pass vacuously", len(sites), field, len(ownerNames))
+ }
+ covered := map[string]bool{}
+ for _, site := range sites {
+ owned := ""
+ for name, span := range spans {
+ if pkg.Contains(span, site) {
+ owned = name
+ break
+ }
+ }
+ covered[owned] = true
+ if owned == "" {
+ t.Errorf("%s touches o.%s outside its accessor; route it through the accessor so the value it reads is the published one", site, field)
+ }
+ }
+ for _, name := range ownerNames {
+ if !covered[name] {
+ t.Errorf("%s no longer touches o.%s, so it has stopped being an accessor for it and this census is guarding one site fewer than it claims", name, field)
+ }
+ }
+ }
+}
diff --git a/internal/orchestrator/handlers_instances.go b/internal/orchestrator/handlers_instances.go
index 37426ec0..e2876e44 100644
--- a/internal/orchestrator/handlers_instances.go
+++ b/internal/orchestrator/handlers_instances.go
@@ -392,8 +392,8 @@ func (o *Orchestrator) handleAttachInstance(w http.ResponseWriter, r *http.Reque
attachBrowser = req.Provider
}
- if attachBrowser != "" && o.runtimeCfg != nil && len(o.runtimeCfg.Targets) > 0 {
- matches := config.TargetsForBrowser(o.runtimeCfg, attachBrowser)
+ if cfg := o.cfg(); attachBrowser != "" && cfg != nil && len(cfg.Targets) > 0 {
+ matches := config.TargetsForBrowser(cfg, attachBrowser)
if len(matches) == 0 {
httpx.Error(w, 400, fmt.Errorf("no browser target configured for browser %q", attachBrowser))
return
@@ -512,11 +512,12 @@ func (o *Orchestrator) probeAttachBridge(baseURL, token string) error {
}
func (o *Orchestrator) validateAttachURL(rawURL string) error {
- if o.runtimeCfg == nil {
+ cfg := o.cfg()
+ if cfg == nil {
return fmt.Errorf("attach not configured")
}
- if !o.runtimeCfg.AttachEnabled {
+ if !cfg.AttachEnabled {
return fmt.Errorf("attach is disabled")
}
@@ -526,14 +527,14 @@ func (o *Orchestrator) validateAttachURL(rawURL string) error {
}
schemeAllowed := false
- for _, allowed := range o.runtimeCfg.AttachAllowSchemes {
+ for _, allowed := range cfg.AttachAllowSchemes {
if parsed.Scheme == allowed {
schemeAllowed = true
break
}
}
if !schemeAllowed {
- return fmt.Errorf("scheme %q not allowed (allowed: %v)", parsed.Scheme, o.runtimeCfg.AttachAllowSchemes)
+ return fmt.Errorf("scheme %q not allowed (allowed: %v)", parsed.Scheme, cfg.AttachAllowSchemes)
}
if parsed.Scheme == "http" || parsed.Scheme == "https" {
@@ -550,8 +551,8 @@ func (o *Orchestrator) validateAttachURL(rawURL string) error {
}
host := parsed.Hostname()
- if !isAllowedAttachHost(host, o.runtimeCfg.AttachAllowHosts) {
- return fmt.Errorf("host %q not allowed (allowed: %v)", host, o.runtimeCfg.AttachAllowHosts)
+ if !isAllowedAttachHost(host, cfg.AttachAllowHosts) {
+ return fmt.Errorf("host %q not allowed (allowed: %v)", host, cfg.AttachAllowHosts)
}
return nil
diff --git a/internal/orchestrator/handlers_instances_test.go b/internal/orchestrator/handlers_instances_test.go
index 93a2aeb0..84e659c5 100644
--- a/internal/orchestrator/handlers_instances_test.go
+++ b/internal/orchestrator/handlers_instances_test.go
@@ -359,7 +359,7 @@ func TestHandleAttachInstanceUsesDefaultBrowserTargetWhenOmitted(t *testing.T) {
stubAttachBridgeHealthy(t)
runner := &mockRunner{portAvail: true}
o := setupAttachTargetsOrchestrator(t, runner)
- o.runtimeCfg.DefaultTarget = "cloak-1"
+ republishCfg(o, func(c *config.RuntimeConfig) { c.DefaultTarget = "cloak-1" })
req := httptest.NewRequest(http.MethodPost, "/instances/attach", strings.NewReader(`{
"name":"attached-cloak",
@@ -497,9 +497,11 @@ func TestHandleAttachBridgeUsesDefaultBrowserTarget(t *testing.T) {
o := setupAttachTargetsOrchestrator(t, &mockRunner{portAvail: true})
o.client = backend.Client()
- o.runtimeCfg.DefaultTarget = "cloak-1"
- o.runtimeCfg.AttachAllowHosts = []string{"*"}
- o.runtimeCfg.AttachAllowSchemes = []string{"http"}
+ republishCfg(o, func(c *config.RuntimeConfig) {
+ c.DefaultTarget = "cloak-1"
+ c.AttachAllowHosts = []string{"*"}
+ c.AttachAllowSchemes = []string{"http"}
+ })
req := httptest.NewRequest(http.MethodPost, "/instances/attach-bridge", strings.NewReader(fmt.Sprintf(`{
"name":"attached-bridge",
diff --git a/internal/orchestrator/health.go b/internal/orchestrator/health.go
index c14455a5..6e720c47 100644
--- a/internal/orchestrator/health.go
+++ b/internal/orchestrator/health.go
@@ -103,7 +103,7 @@ func (o *Orchestrator) probeStartupHealth(inst *InstanceInternal) startupProbe {
break
}
- for _, baseURL := range instanceBaseURLs(configuredChildBind(o.runtimeCfg), probePort) {
+ for _, baseURL := range instanceBaseURLs(configuredChildBind(o.cfg()), probePort) {
targetBaseURL, err := o.validatedHealthProbeBaseURL(baseURL, "", healthProbePolicyLoopback)
if err != nil {
p.lastProbe = fmt.Sprintf("%s -> %s", baseURL, err.Error())
diff --git a/internal/orchestrator/health_probe_url.go b/internal/orchestrator/health_probe_url.go
index 4b81ca4c..f246fa0f 100644
--- a/internal/orchestrator/health_probe_url.go
+++ b/internal/orchestrator/health_probe_url.go
@@ -28,17 +28,18 @@ func (o *Orchestrator) validatedHealthProbeBaseURL(rawURL, port string, policy h
}
host := baseURL.Hostname()
+ cfg := o.cfg()
switch policy {
case healthProbePolicyAttachAllowlist:
- if o.runtimeCfg == nil {
+ if cfg == nil {
return nil, fmt.Errorf("blocked: attach not configured")
}
- if !isAllowedAttachHost(host, o.runtimeCfg.AttachAllowHosts) {
+ if !isAllowedAttachHost(host, cfg.AttachAllowHosts) {
slog.Warn("health probe blocked: host not allowed", "url", rawURL, "host", host)
return nil, fmt.Errorf("blocked: host not allowed")
}
default:
- if !isAllowedChildProbeHost(host, configuredChildBind(o.runtimeCfg)) {
+ if !isAllowedChildProbeHost(host, configuredChildBind(cfg)) {
slog.Warn("health probe blocked: non-loopback host", "url", rawURL, "host", host)
return nil, fmt.Errorf("blocked: non-loopback host")
}
diff --git a/internal/orchestrator/instance_attach.go b/internal/orchestrator/instance_attach.go
index ed6ed59c..ce301820 100644
--- a/internal/orchestrator/instance_attach.go
+++ b/internal/orchestrator/instance_attach.go
@@ -96,14 +96,14 @@ func (o *Orchestrator) AttachWithOptions(name, cdpURL string, opts AttachOptions
return nil, err
}
- bridgePort, err := o.portAllocator.AllocatePort()
+ bridgePort, err := o.ports().AllocatePort()
if err != nil {
return nil, fmt.Errorf("failed to allocate bridge port: %w", err)
}
released := false
defer func() {
if !released {
- o.portAllocator.ReleasePort(bridgePort)
+ o.ports().ReleasePort(bridgePort)
}
}()
portStr := strconv.Itoa(bridgePort)
@@ -331,9 +331,10 @@ func (o *Orchestrator) hasActiveAttachedBridge(name string) bool {
func (o *Orchestrator) resolveAttachOptions(opts AttachOptions, defaultProvider string) (AttachOptions, error) {
requestedProvider := strings.TrimSpace(opts.Browser)
+ cfg := o.cfg()
var configured []string
- if o.runtimeCfg != nil {
- configured = o.runtimeCfg.BrowsersAvailable
+ if cfg != nil {
+ configured = cfg.BrowsersAvailable
}
explicitProvider := requestedProvider != ""
@@ -346,7 +347,7 @@ func (o *Orchestrator) resolveAttachOptions(opts AttachOptions, defaultProvider
parsedProvider = provider
}
- if o.runtimeCfg == nil || len(o.runtimeCfg.Targets) == 0 {
+ if cfg == nil || len(cfg.Targets) == 0 {
if parsedProvider == "" && defaultProvider != "" {
provider, err := config.ParseBrowser(defaultProvider, configured)
if err != nil {
@@ -358,7 +359,7 @@ func (o *Orchestrator) resolveAttachOptions(opts AttachOptions, defaultProvider
}
if parsedProvider == "" {
- resolved, err := config.ResolveDefaultBrowserTarget(o.runtimeCfg)
+ resolved, err := config.ResolveDefaultBrowserTarget(cfg)
if err != nil {
return AttachOptions{}, err
}
diff --git a/internal/orchestrator/instance_launch.go b/internal/orchestrator/instance_launch.go
index c75674b2..aee063a5 100644
--- a/internal/orchestrator/instance_launch.go
+++ b/internal/orchestrator/instance_launch.go
@@ -51,7 +51,7 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
reservedPorts := make([]int, 0, 2)
defer func() {
for _, reserved := range reservedPorts {
- o.portAllocator.ReleasePort(reserved)
+ o.ports().ReleasePort(reserved)
}
}()
@@ -59,7 +59,7 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
if port == "" || port == "0" {
o.mu.Unlock()
- allocatedPort, err := o.portAllocator.AllocatePort()
+ allocatedPort, err := o.ports().AllocatePort()
if err != nil {
return nil, fmt.Errorf("failed to allocate port: %w", err)
}
@@ -73,10 +73,10 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
return nil, err
}
port = strconv.Itoa(portInt)
- if err := o.portAllocator.ReservePort(portInt); err != nil {
+ if err := o.ports().ReservePort(portInt); err != nil {
return nil, fmt.Errorf("failed to reserve port %s: %w", port, err)
}
- if portInt >= o.portAllocator.start && portInt <= o.portAllocator.end {
+ if portInt >= o.ports().start && portInt <= o.ports().end {
reservedPorts = append(reservedPorts, portInt)
}
o.mu.Lock()
@@ -110,7 +110,7 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
o.mu.Unlock()
- cdpPort, err := o.portAllocator.AllocatePort()
+ cdpPort, err := o.ports().AllocatePort()
if err != nil {
return nil, fmt.Errorf("failed to allocate browser debug port: %w", err)
}
@@ -134,14 +134,19 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
}
requestedPolicy := cloneSecurityPolicy(opts.SecurityPolicy)
- effectivePolicy := effectiveSecurityPolicy(o.runtimeCfg, requestedPolicy)
-
- effectiveCfg := o.runtimeCfg
+ // One read of the published config for the whole launch: a save landing
+ // mid-launch must not have the policy come from one value and the target
+ // from the next.
+ cfg := o.cfg()
+ effectivePolicy := effectiveSecurityPolicy(cfg, requestedPolicy)
+
+ effectiveCfg := cfg
+ hasTargets := cfg != nil && len(cfg.Targets) > 0
targetPromoted := false
// A resolved target name is authoritative: re-deriving from the provider
// picks the wrong target when several targets share one provider.
- if targetName := strings.TrimSpace(opts.TargetName); targetName != "" && o.runtimeCfg != nil && len(o.runtimeCfg.Targets) > 0 {
- resolved, err := config.ResolveExplicitBrowserTarget(o.runtimeCfg, targetName)
+ if targetName := strings.TrimSpace(opts.TargetName); targetName != "" && hasTargets {
+ resolved, err := config.ResolveExplicitBrowserTarget(cfg, targetName)
if err == nil {
effectiveCfg = resolved.Config
targetPromoted = true
@@ -149,12 +154,12 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
slog.Warn("launch: resolved target name no longer resolves; falling back to provider-derived config", "target", targetName, "err", err)
}
}
- if browser := strings.TrimSpace(opts.Browser); !targetPromoted && browser != "" && o.runtimeCfg != nil && len(o.runtimeCfg.Targets) > 0 {
+ if browser := strings.TrimSpace(opts.Browser); !targetPromoted && browser != "" && hasTargets {
// Lenient: only promote a target when the provider maps to an unambiguous
// winner (single match, or the configured default among several); an
// ambiguous/zero match leaves the provider-derived config in place.
- if target, _ := config.MatchBrowserToTarget(o.runtimeCfg, browser); target != "" {
- if resolved, err := config.ResolveExplicitBrowserTarget(o.runtimeCfg, target); err == nil {
+ if target, _ := config.MatchBrowserToTarget(cfg, browser); target != "" {
+ if resolved, err := config.ResolveExplicitBrowserTarget(cfg, target); err == nil {
effectiveCfg = resolved.Config
}
}
@@ -176,8 +181,8 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
if opts.Browser != "" {
var configured []string
- if o.runtimeCfg != nil {
- configured = o.runtimeCfg.BrowsersAvailable
+ if cfg != nil {
+ configured = cfg.BrowsersAvailable
}
if _, err := config.ParseBrowser(opts.Browser, configured); err != nil {
return nil, fmt.Errorf("invalid browser %q: %w", opts.Browser, err)
@@ -194,8 +199,8 @@ func (o *Orchestrator) LaunchWithOptions(name, port string, headless bool, opts
}
browser := opts.Browser
- if browser == "" && o.runtimeCfg != nil {
- browser = config.NormalizeBrowser(o.runtimeCfg.DefaultBrowser)
+ if browser == "" && cfg != nil {
+ browser = config.NormalizeBrowser(cfg.DefaultBrowser)
}
inst := &InstanceInternal{
diff --git a/internal/orchestrator/instance_query.go b/internal/orchestrator/instance_query.go
index 93811834..475f2ee9 100644
--- a/internal/orchestrator/instance_query.go
+++ b/internal/orchestrator/instance_query.go
@@ -122,7 +122,7 @@ func (o *Orchestrator) firstRunningURL(match func(*InstanceInternal) bool) strin
func (o *Orchestrator) FirstRunningURLForRequest(r *http.Request) (string, int, error) {
requested := ExtractRequestedBrowser(r)
if requested == "" {
- resolved, err := config.ResolveDefaultBrowserTarget(o.runtimeCfg)
+ resolved, err := config.ResolveDefaultBrowserTarget(o.cfg())
if err != nil {
return "", http.StatusBadRequest, err
}
@@ -140,8 +140,8 @@ func (o *Orchestrator) FirstRunningURLForRequest(r *http.Request) (string, int,
}
normalized := config.NormalizeBrowser(requested)
- if o.runtimeCfg != nil && len(o.runtimeCfg.Targets) > 0 {
- matches := config.TargetsForBrowser(o.runtimeCfg, requested)
+ if cfg := o.cfg(); cfg != nil && len(cfg.Targets) > 0 {
+ matches := config.TargetsForBrowser(cfg, requested)
if len(matches) == 0 {
return "", http.StatusBadRequest, fmt.Errorf("no browser target configured for browser %q", requested)
}
diff --git a/internal/orchestrator/instance_stop.go b/internal/orchestrator/instance_stop.go
index ea59f987..b96cbc05 100644
--- a/internal/orchestrator/instance_stop.go
+++ b/internal/orchestrator/instance_stop.go
@@ -215,16 +215,16 @@ func (o *Orchestrator) markStopped(id string) {
}
func (o *Orchestrator) releaseInstancePorts(id string, inst *InstanceInternal) {
- if o == nil || o.portAllocator == nil || inst == nil {
+ if o == nil || o.ports() == nil || inst == nil {
return
}
portStr := inst.Port
if portInt, err := strconv.Atoi(portStr); err == nil {
- o.portAllocator.ReleasePort(portInt)
+ o.ports().ReleasePort(portInt)
slog.Debug("released port", "id", id, "port", portStr)
}
if inst.cdpPort > 0 {
- o.portAllocator.ReleasePort(inst.cdpPort)
+ o.ports().ReleasePort(inst.cdpPort)
slog.Debug("released browser debug port", "id", id, "port", inst.cdpPort)
}
}
@@ -238,8 +238,8 @@ func (o *Orchestrator) removeInstanceFromManager(id string) {
func (o *Orchestrator) cleanupStoppedProfile(profileName, browser string) {
profilePath := filepath.Join(o.baseDir, profileName)
- if browser == "" && o.runtimeCfg != nil {
- browser = config.NormalizeBrowser(o.runtimeCfg.DefaultBrowser)
+ if cfg := o.cfg(); browser == "" && cfg != nil {
+ browser = config.NormalizeBrowser(cfg.DefaultBrowser)
}
if browser == "" {
// Every provider's cleanup hook is the same chrome-process sweep;
diff --git a/internal/orchestrator/launch_target_config_test.go b/internal/orchestrator/launch_target_config_test.go
index a8872f41..5f3a0461 100644
--- a/internal/orchestrator/launch_target_config_test.go
+++ b/internal/orchestrator/launch_target_config_test.go
@@ -11,7 +11,7 @@ import (
// fakeOrch avoids the binary-install side effects of NewOrchestrator.
func fakeOrch(cfg *config.RuntimeConfig) *Orchestrator {
- return &Orchestrator{runtimeCfg: cfg}
+ return orchWithConfig(cfg)
}
func runtimeCfgWithTargets() *config.RuntimeConfig {
@@ -103,7 +103,7 @@ func TestBuildChildFileConfig_LegacyConfigByteStable(t *testing.T) {
}
o := fakeOrch(cfg)
- prev := o.buildChildFileConfig(o.runtimeCfg, "9999", 12345, "/tmp/profile", "/tmp/state", true, nil, nil)
+ prev := o.buildChildFileConfig(o.cfg(), "9999", 12345, "/tmp/profile", "/tmp/state", true, nil, nil)
prevBytes, err := json.MarshalIndent(prev, "", " ")
if err != nil {
t.Fatalf("marshal prev: %v", err)
diff --git a/internal/orchestrator/launch_target_selection.go b/internal/orchestrator/launch_target_selection.go
index e9363fc2..9b22fa23 100644
--- a/internal/orchestrator/launch_target_selection.go
+++ b/internal/orchestrator/launch_target_selection.go
@@ -13,9 +13,11 @@ import (
// config and wraps failures for HTTP handlers.
func (o *Orchestrator) ResolveRequestedBrowser(requested string) (targetName, provider string, err error) {
requested = strings.TrimSpace(requested)
+ cfg := o.cfg()
+ hasTargets := cfg != nil && len(cfg.Targets) > 0
if requested == "" {
var resolved *config.ResolvedBrowserTarget
- resolved, err = config.ResolveDefaultBrowserTarget(o.runtimeCfg)
+ resolved, err = config.ResolveDefaultBrowserTarget(cfg)
if err != nil {
return "", "", &UnknownBrowserError{Target: requested, Err: err}
}
@@ -25,18 +27,18 @@ func (o *Orchestrator) ResolveRequestedBrowser(requested string) (targetName, pr
return resolved.Name, resolved.Provider, nil
}
- if o.runtimeCfg != nil && len(o.runtimeCfg.Targets) > 0 {
- resolved, explicitErr := config.ResolveExplicitBrowserTarget(o.runtimeCfg, requested)
+ if hasTargets {
+ resolved, explicitErr := config.ResolveExplicitBrowserTarget(cfg, requested)
if explicitErr == nil && resolved != nil && !resolved.Legacy {
return resolved.Name, resolved.Provider, nil
}
}
- if o.runtimeCfg != nil && len(o.runtimeCfg.Targets) > 0 {
- target, matches := config.MatchBrowserToTarget(o.runtimeCfg, requested)
+ if hasTargets {
+ target, matches := config.MatchBrowserToTarget(cfg, requested)
switch {
case target != "":
- resolved, resolveErr := config.ResolveExplicitBrowserTarget(o.runtimeCfg, target)
+ resolved, resolveErr := config.ResolveExplicitBrowserTarget(cfg, target)
if resolveErr == nil && resolved != nil {
return resolved.Name, resolved.Provider, nil
}
@@ -52,8 +54,8 @@ func (o *Orchestrator) ResolveRequestedBrowser(requested string) (targetName, pr
// Legacy (no-targets) fallthrough: an explicit unknown browser must fail
// here, not silently launch chrome via NormalizeBrowser coercion later.
var available []string
- if o.runtimeCfg != nil {
- available = o.runtimeCfg.BrowsersAvailable
+ if cfg != nil {
+ available = cfg.BrowsersAvailable
}
parsed, err := config.ParseBrowser(requested, available)
if err != nil {
@@ -87,11 +89,12 @@ func (o *Orchestrator) LaunchWithTargetSelection(
// (e.g. "cloak") or target names (e.g. "cloak-1"); each is resolved through
// the same two-step logic as the primary request, so a provider-name
// fallback no longer 400s and aborts the chain.
+ cfg := o.cfg()
var fallbacks []string
if len(fallbackTargets) > 0 {
fallbacks = fallbackTargets
- } else if strings.TrimSpace(requestedTarget) == "" && resolvedTarget != "" && o.runtimeCfg != nil {
- fallbacks = o.runtimeCfg.FallbackOrder
+ } else if strings.TrimSpace(requestedTarget) == "" && resolvedTarget != "" && cfg != nil {
+ fallbacks = cfg.FallbackOrder
}
if resolvedTarget == "" || len(fallbacks) == 0 {
@@ -107,10 +110,10 @@ func (o *Orchestrator) LaunchWithTargetSelection(
// Reject a fallback that is neither a configured target nor a known
// provider before resolving: the two-step resolver's NormalizeBrowser
// default would otherwise silently coerce a typo'd name to chrome.
- if o.runtimeCfg == nil || o.runtimeCfg.Targets[fb].Provider == "" {
+ if cfg == nil || cfg.Targets[fb].Provider == "" {
var available []string
- if o.runtimeCfg != nil {
- available = o.runtimeCfg.BrowsersAvailable
+ if cfg != nil {
+ available = cfg.BrowsersAvailable
}
if _, perr := config.ParseBrowser(fb, available); perr != nil {
return nil, &UnknownBrowserError{Target: fb, Err: perr}
diff --git a/internal/orchestrator/launch_with_fallback.go b/internal/orchestrator/launch_with_fallback.go
index d0d7a52a..92d6c9fb 100644
--- a/internal/orchestrator/launch_with_fallback.go
+++ b/internal/orchestrator/launch_with_fallback.go
@@ -234,7 +234,7 @@ type orchestratorFallbackLauncher struct {
}
func (l orchestratorFallbackLauncher) ResolveTarget(candidate string) (ResolvedLaunchTarget, error) {
- resolved, err := config.ResolveExplicitBrowserTarget(l.orch.runtimeCfg, candidate)
+ resolved, err := config.ResolveExplicitBrowserTarget(l.orch.cfg(), candidate)
if err != nil {
return ResolvedLaunchTarget{}, err
}
diff --git a/internal/orchestrator/launch_with_fallback_test.go b/internal/orchestrator/launch_with_fallback_test.go
index 1c4d29ec..2f64674c 100644
--- a/internal/orchestrator/launch_with_fallback_test.go
+++ b/internal/orchestrator/launch_with_fallback_test.go
@@ -163,19 +163,20 @@ func fastPolling(t *testing.T) {
func newFallbackTestOrch(t *testing.T) *Orchestrator {
t.Helper()
- return &Orchestrator{
+ o := &Orchestrator{
instances: make(map[string]*InstanceInternal),
portAllocator: NewPortAllocator(9000, 9100),
- runtimeCfg: &config.RuntimeConfig{
- DefaultBrowser: config.BrowserChrome,
- Targets: config.BrowserTargetsConfig{
- "chrome": config.BrowserTargetConfig{Provider: config.BrowserChrome},
- "cloak": config.BrowserTargetConfig{Provider: config.BrowserCloak},
- "backup": config.BrowserTargetConfig{Provider: config.BrowserChrome},
- },
- DefaultTarget: "chrome",
- },
}
+ o.LiveConfig().Publish(&config.RuntimeConfig{
+ DefaultBrowser: config.BrowserChrome,
+ Targets: config.BrowserTargetsConfig{
+ "chrome": config.BrowserTargetConfig{Provider: config.BrowserChrome},
+ "cloak": config.BrowserTargetConfig{Provider: config.BrowserCloak},
+ "backup": config.BrowserTargetConfig{Provider: config.BrowserChrome},
+ },
+ DefaultTarget: "chrome",
+ })
+ return o
}
func TestLaunchWithFallback_FirstCandidateSucceeds(t *testing.T) {
@@ -260,7 +261,7 @@ func TestLaunchWithFallback_StoresFallbackMetadataOnCanonicalInstance(t *testing
func TestLaunchUsesConfiguredFallbackOrder(t *testing.T) {
fastPolling(t)
o := newFallbackTestOrch(t)
- o.runtimeCfg.FallbackOrder = []string{"cloak"}
+ republishCfg(o, func(c *config.RuntimeConfig) { c.FallbackOrder = []string{"cloak"} })
fl := fakeLauncherForOrch(t, o, []scriptedOutcome{
{target: "chrome", failReason: ReasonBinaryMissing},
{target: "cloak", succeed: true},
@@ -410,11 +411,13 @@ func TestLaunchWithFallback_NonRecoverableWaitErrorAborts(t *testing.T) {
func TestLaunchWithTargetSelection_ResolvesProviderNameFallback(t *testing.T) {
fastPolling(t)
o := newFallbackTestOrch(t)
- o.runtimeCfg.Targets = config.BrowserTargetsConfig{
- "chrome": config.BrowserTargetConfig{Provider: config.BrowserChrome},
- "cloak-primary": config.BrowserTargetConfig{Provider: config.BrowserCloak},
- }
- o.runtimeCfg.DefaultTarget = "chrome"
+ republishCfg(o, func(c *config.RuntimeConfig) {
+ c.Targets = config.BrowserTargetsConfig{
+ "chrome": config.BrowserTargetConfig{Provider: config.BrowserChrome},
+ "cloak-primary": config.BrowserTargetConfig{Provider: config.BrowserCloak},
+ }
+ c.DefaultTarget = "chrome"
+ })
fl := fakeLauncherForOrch(t, o, []scriptedOutcome{
{target: "chrome", failReason: ReasonBinaryMissing},
{target: "cloak-primary", succeed: true},
diff --git a/internal/orchestrator/orchestrator.go b/internal/orchestrator/orchestrator.go
index 9181911f..cabe6aaf 100644
--- a/internal/orchestrator/orchestrator.go
+++ b/internal/orchestrator/orchestrator.go
@@ -25,17 +25,15 @@ type InstanceEvent struct {
type EventHandler func(InstanceEvent)
type Orchestrator struct {
- instances map[string]*InstanceInternal
- baseDir string
- binary string
- profiles *profiles.ProfileManager
- runner HostRunner
- mu sync.RWMutex
- client *http.Client
- childAuthToken string
- allowEvaluate bool
- internalToken string
- bindings *Bindings
+ instances map[string]*InstanceInternal
+ baseDir string
+ binary string
+ profiles *profiles.ProfileManager
+ runner HostRunner
+ mu sync.RWMutex
+ client *http.Client
+ internalToken string
+ bindings *Bindings
// detachedStops tracks async failed-attempt teardowns so tests (and
// shutdown paths) can wait for them instead of leaking goroutines that
// race with stubbed package vars.
@@ -72,7 +70,7 @@ type Orchestrator struct {
idMgr *ids.Manager
eventHandlers []EventHandler
instanceMgr *instance.Manager
- runtimeCfg *config.RuntimeConfig
+ live config.Live
fallbackLauncher Launcher
// attachHealthCheckTimeout overrides the default health-check timeout in tests.
@@ -160,19 +158,17 @@ func NewOrchestrator(baseDir string) *Orchestrator {
func NewOrchestratorWithRunner(baseDir string, runner HostRunner) *Orchestrator {
orch := &Orchestrator{
- instances: make(map[string]*InstanceInternal),
- baseDir: baseDir,
- binary: resolveStableBinary(baseDir),
- runner: runner,
- client: &http.Client{Timeout: httpx.MaxNavigationHTTPDuration},
- childAuthToken: "",
- allowEvaluate: false,
- internalToken: generateInternalToken(),
- bindings: NewBindings(nil),
- tabsCache: NewTabsCache(0, nil),
- portAllocator: NewPortAllocator(9868, 9968),
- idMgr: ids.NewManager(),
- shutdownCh: make(chan struct{}),
+ instances: make(map[string]*InstanceInternal),
+ baseDir: baseDir,
+ binary: resolveStableBinary(baseDir),
+ runner: runner,
+ client: &http.Client{Timeout: httpx.MaxNavigationHTTPDuration},
+ internalToken: generateInternalToken(),
+ bindings: NewBindings(nil),
+ tabsCache: NewTabsCache(0, nil),
+ portAllocator: NewPortAllocator(9868, 9968),
+ idMgr: ids.NewManager(),
+ shutdownCh: make(chan struct{}),
}
orch.registerInstanceCleanupHook()
@@ -292,15 +288,14 @@ func (o *Orchestrator) SetProfileManager(pm *profiles.ProfileManager) {
o.profiles = pm
}
+// ApplyRuntimeConfig publishes the value every reader will see from here on. The
+// config is never written in place, so publication is a single pointer store and
+// only the derived state that lives outside it needs the lock.
func (o *Orchestrator) ApplyRuntimeConfig(cfg *config.RuntimeConfig) {
- o.runtimeCfg = cfg
+ o.live.Publish(cfg)
if cfg == nil {
- o.childAuthToken = ""
- o.allowEvaluate = false
return
}
- o.childAuthToken = cfg.Token
- o.allowEvaluate = cfg.AllowEvaluate
o.SetPortRange(cfg.InstancePortStart, cfg.InstancePortEnd)
if cfg.AllocationPolicy != "" {
if err := o.SetAllocationPolicy(cfg.AllocationPolicy); err != nil {
@@ -309,38 +304,92 @@ func (o *Orchestrator) ApplyRuntimeConfig(cfg *config.RuntimeConfig) {
}
}
+// LiveConfig hands out the publication point so every other holder of the runtime
+// config in this process reads and writes the same one. A save through the
+// dashboard is then visible to the orchestrator's goroutines by construction,
+// rather than by two holders agreeing to mutate one shared object.
+func (o *Orchestrator) LiveConfig() *config.Live {
+ if o == nil {
+ return nil
+ }
+ return &o.live
+}
+
+// cfg is the ONE accessor for the published runtime config. Nothing reads a bare
+// field: a nil Live (a bare struct literal in a test) answers nil, which every
+// caller already handles.
+func (o *Orchestrator) cfg() *config.RuntimeConfig {
+ if o == nil {
+ return nil
+ }
+ return o.live.Get()
+}
+
+// ports is the same discipline for the allocator, which is a swap rather than a
+// publication: SetPortRange replaces it while launches are reading it.
+func (o *Orchestrator) ports() *PortAllocator {
+ if o == nil {
+ return nil
+ }
+ o.mu.RLock()
+ defer o.mu.RUnlock()
+ return o.portAllocator
+}
+
+// cfgToken is the child auth token: derived from the published config on every
+// read rather than copied into a field, so a reader cannot observe a token that
+// disagrees with the config in effect.
+func (o *Orchestrator) cfgToken() string {
+ cfg := o.cfg()
+ if cfg == nil {
+ return ""
+ }
+ return cfg.Token
+}
+
func (o *Orchestrator) AllowsEvaluate() bool {
- return o != nil && o.allowEvaluate
+ cfg := o.cfg()
+ return cfg != nil && cfg.AllowEvaluate
}
func (o *Orchestrator) AllowsMacro() bool {
- return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowMacro
+ cfg := o.cfg()
+ return cfg != nil && cfg.AllowMacro
}
func (o *Orchestrator) AllowsScreencast() bool {
- return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowScreencast
+ cfg := o.cfg()
+ return cfg != nil && cfg.AllowScreencast
}
func (o *Orchestrator) AllowsDownload() bool {
- return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowDownload
+ cfg := o.cfg()
+ return cfg != nil && cfg.AllowDownload
}
func (o *Orchestrator) AllowsCookies() bool {
- return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowCookies
+ cfg := o.cfg()
+ return cfg != nil && cfg.AllowCookies
}
func (o *Orchestrator) AllowsUpload() bool {
- return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowUpload
+ cfg := o.cfg()
+ return cfg != nil && cfg.AllowUpload
}
func (o *Orchestrator) AllowsStateExport() bool {
- return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowStateExport
+ cfg := o.cfg()
+ return cfg != nil && cfg.AllowStateExport
}
func (o *Orchestrator) AllowsNetworkIntercept() bool {
- return o != nil && o.runtimeCfg != nil && o.runtimeCfg.AllowNetworkIntercept
+ cfg := o.cfg()
+ return cfg != nil && cfg.AllowNetworkIntercept
}
func (o *Orchestrator) SetPortRange(start, end int) {
- o.portAllocator = NewPortAllocator(start, end)
+ allocator := NewPortAllocator(start, end)
+ o.mu.Lock()
+ defer o.mu.Unlock()
+ o.portAllocator = allocator
}
diff --git a/internal/orchestrator/proxy.go b/internal/orchestrator/proxy.go
index 14cf373d..0f077125 100644
--- a/internal/orchestrator/proxy.go
+++ b/internal/orchestrator/proxy.go
@@ -228,7 +228,7 @@ func (o *Orchestrator) handleProxyScreencast(w http.ResponseWriter, r *http.Requ
iproxy.SetProxyWSBackendAuthorization(req.Header, "")
if token := inst.authToken; token != "" {
iproxy.SetProxyWSBackendAuthorization(req.Header, "Bearer "+token)
- } else if token := o.childAuthToken; token != "" {
+ } else if token := o.cfgToken(); token != "" {
iproxy.SetProxyWSBackendAuthorization(req.Header, "Bearer "+token)
}
@@ -324,7 +324,7 @@ func (o *Orchestrator) applyInstanceAuth(req *http.Request, inst *InstanceIntern
iproxy.SetProxyWSBackendAuthorization(req.Header, "")
token := inst.authToken
if token == "" {
- token = o.childAuthToken
+ token = o.cfgToken()
}
if token != "" {
bearer := "Bearer " + token
diff --git a/internal/orchestrator/proxy_test.go b/internal/orchestrator/proxy_test.go
index c196eb5a..12d77981 100644
--- a/internal/orchestrator/proxy_test.go
+++ b/internal/orchestrator/proxy_test.go
@@ -11,6 +11,8 @@ import (
"sync/atomic"
"testing"
+ "github.com/pinchtab/pinchtab/internal/config"
+
"github.com/pinchtab/pinchtab/internal/activity"
"github.com/pinchtab/pinchtab/internal/bridge"
"github.com/pinchtab/pinchtab/internal/session"
@@ -133,7 +135,7 @@ func TestRegisterHandlers_TabCloseUsesGenericProxyAndInvalidatesCache(t *testing
o := NewOrchestrator(t.TempDir())
o.client = backend.Client()
- o.childAuthToken = "child-token"
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{Token: "child-token"})
inst := bridge.Instance{ID: "inst_1", Status: "running", URL: backend.URL}
o.instances["inst_1"] = &InstanceInternal{
Instance: inst,
@@ -290,7 +292,7 @@ func TestProxyToTarget_InjectsChildAuthAndStripsCookie(t *testing.T) {
o := NewOrchestrator(t.TempDir())
o.client = backend.Client()
- o.childAuthToken = "child-token"
+ o.ApplyRuntimeConfig(&config.RuntimeConfig{Token: "child-token"})
o.instances["inst_1"] = &InstanceInternal{
Instance: bridge.Instance{ID: "inst_1", Status: "running"},
URL: backend.URL,
diff --git a/internal/orchestrator/proxy_ws_auth_test.go b/internal/orchestrator/proxy_ws_auth_test.go
index b32560c4..218534bd 100644
--- a/internal/orchestrator/proxy_ws_auth_test.go
+++ b/internal/orchestrator/proxy_ws_auth_test.go
@@ -3,6 +3,8 @@ package orchestrator
import (
"net/http"
"testing"
+
+ "github.com/pinchtab/pinchtab/internal/config"
)
// The WebSocket header filter in internal/proxy promotes
@@ -27,7 +29,7 @@ func TestApplyInstanceAuthDropsClientSuppliedWSAuthorization(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- o := &Orchestrator{childAuthToken: tt.childToken}
+ o := orchWithConfig(&config.RuntimeConfig{Token: tt.childToken})
inst := &InstanceInternal{authToken: tt.instanceToken}
req, err := http.NewRequest(http.MethodGet, "http://instance/screencast", nil)
diff --git a/internal/orchestrator/route.go b/internal/orchestrator/route.go
index bacf894b..0f71e8f0 100644
--- a/internal/orchestrator/route.go
+++ b/internal/orchestrator/route.go
@@ -44,8 +44,8 @@ func (o *Orchestrator) RouteForRequest(r *http.Request) (string, int, error) {
requestedBrowser := ExtractRequestedBrowser(r)
if requestedBrowser != "" {
var available []string
- if o.runtimeCfg != nil {
- available = o.runtimeCfg.BrowsersAvailable
+ if cfg := o.cfg(); cfg != nil {
+ available = cfg.BrowsersAvailable
}
if _, err := config.ParseBrowser(requestedBrowser, available); err != nil {
return "", http.StatusBadRequest, fmt.Errorf("unknown browser %q: %w", requestedBrowser, err)
diff --git a/internal/server/config_race_test.go b/internal/server/config_race_test.go
new file mode 100644
index 00000000..b7a2ec59
--- /dev/null
+++ b/internal/server/config_race_test.go
@@ -0,0 +1,76 @@
+package server
+
+import (
+ "bytes"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "os"
+ "path/filepath"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/pinchtab/pinchtab/internal/config"
+ "github.com/pinchtab/pinchtab/internal/dashboard"
+ "github.com/pinchtab/pinchtab/internal/orchestrator"
+)
+
+// The wiring under test is RunDashboard's: one publication point reaches the
+// orchestrator and the config API, and a dashboard save must not write the value
+// the orchestrator's goroutines are reading. The reader runs for the whole of
+// every save rather than being sampled once, so -race has a write and a read to
+// pair up on every iteration instead of on a lucky one.
+func TestADashboardSaveDoesNotRaceAnOrchestratorReader(t *testing.T) {
+ configPath := filepath.Join(t.TempDir(), "config.json")
+ t.Setenv("PINCHTAB_CONFIG", configPath)
+ data, err := json.MarshalIndent(config.DefaultFileConfig(), "", " ")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(configPath, data, 0o600); err != nil {
+ t.Fatal(err)
+ }
+
+ orch := orchestrator.NewOrchestrator(t.TempDir())
+ orch.ApplyRuntimeConfig(config.Load())
+ api := dashboard.NewConfigAPI(orch.LiveConfig(), nil, nil, orch, nil, "test", time.Now())
+
+ stop := make(chan struct{})
+ var readers sync.WaitGroup
+ readers.Add(1)
+ go func() {
+ defer readers.Done()
+ for {
+ select {
+ case <-stop:
+ return
+ default:
+ }
+ // The same reads the off-request goroutines make: the security
+ // policy and the child bind address the startup probe follows.
+ _ = orch.AllowsEvaluate()
+ _ = orch.AllowsMacro()
+ _ = orch.AllowsDownload()
+ }
+ }()
+
+ for i := 0; i < 25; i++ {
+ payload := config.DefaultFileConfig()
+ macro, download := i%2 == 0, i%2 == 1
+ payload.Security.AllowMacro = &macro
+ payload.Security.AllowDownload = &download
+ body, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ w := httptest.NewRecorder()
+ api.HandlePutConfig(w, httptest.NewRequest(http.MethodPut, "/api/config", bytes.NewReader(body)))
+ if w.Code != http.StatusOK {
+ t.Fatalf("save %d returned %d: %s", i, w.Code, w.Body.String())
+ }
+ }
+
+ close(stop)
+ readers.Wait()
+}
diff --git a/internal/server/server.go b/internal/server/server.go
index 45bccc69..9c95fcfb 100644
--- a/internal/server/server.go
+++ b/internal/server/server.go
@@ -86,10 +86,11 @@ func RunDashboard(cfg *config.RuntimeConfig, version string) {
RateBucketHosts: MetricInt(snapshot["rateBucketHosts"]),
}
})
- configAPI := dashboard.NewConfigAPI(cfg, orch, profMgr, orch, dash, version, startedAt)
+ live := orch.LiveConfig()
+ configAPI := dashboard.NewConfigAPI(live, orch, profMgr, orch, dash, version, startedAt)
sessions := browsersession.NewManager(dashboard.BrowserSessionConfig(cfg))
configAPI.SetSessionManager(sessions)
- authAPI := dashboard.NewAuthAPI(cfg, sessions)
+ authAPI := dashboard.NewAuthAPI(live, sessions)
sessionStore := session.NewStore(session.Config{
Enabled: cfg.Sessions.Agent.Enabled,
diff --git a/internal/srccensus/srccensus.go b/internal/srccensus/srccensus.go
index ee19d891..7665f00c 100644
--- a/internal/srccensus/srccensus.go
+++ b/internal/srccensus/srccensus.go
@@ -286,6 +286,25 @@ func (p *Package) FieldAssignments(field string) []Site {
return sites
}
+// FieldReferences returns every selector naming field — a read or a write, o.live and
+// l.orch.live alike — so a guard can say "this field is only touched inside its
+// accessor". FieldAssignments is the narrower sibling: it sees writes only, which is
+// not enough when an unsynchronised READ is the defect.
+func (p *Package) FieldReferences(field string) []Site {
+ var sites []Site
+ p.each(func(name string, file *ast.File) {
+ ast.Inspect(file, func(node ast.Node) bool {
+ sel, ok := node.(*ast.SelectorExpr)
+ if !ok || sel.Sel.Name != field {
+ return true
+ }
+ sites = append(sites, p.site(name, file, sel, "."+field))
+ return true
+ })
+ })
+ return sites
+}
+
// Func is a declaration found in the package, carrying the span a scope check needs.
type Func struct {
Name string