diff --git a/charts/iron-proxy/README.md b/charts/iron-proxy/README.md index eb14a0a..fb3719f 100644 --- a/charts/iron-proxy/README.md +++ b/charts/iron-proxy/README.md @@ -123,6 +123,7 @@ managed: existingTokenSecret: iron-proxy-token # Secret with a "token" key # tokenSecretKey: token # controlPlaneURL: https://api.iron.sh # override if self-hosting + # pollInterval: 10s # -> IRON_CONTROL_PLANE_POLL_INTERVAL proxyIP: "203.0.113.10" # REQUIRED -> IRON_DNS_PROXY_IP # tlsMode: "sni-only" # -> IRON_TLS_MODE (set when ca.mode=none) # logLevel: "info" # -> IRON_LOG_LEVEL @@ -192,6 +193,7 @@ credentials with: | `managed.existingTokenSecret` | `""` | Existing Secret holding the token. | | `managed.tokenSecretKey` | `token` | Key within that Secret. | | `managed.controlPlaneURL` | `""` | Override `IRON_CONTROL_PLANE_URL`. | +| `managed.pollInterval` | `""` | Override `IRON_CONTROL_PLANE_POLL_INTERVAL`; binary default is `10s`. | | `managed.proxyIP` | `""` | `IRON_DNS_PROXY_IP`. Required in managed mode. | | `managed.tlsMode` | `""` | `IRON_TLS_MODE` (`mitm`/`sni-only`). | | `managed.logLevel` | `""` | `IRON_LOG_LEVEL`. | diff --git a/charts/iron-proxy/templates/_helpers.tpl b/charts/iron-proxy/templates/_helpers.tpl index a4fa920..1c8e32a 100644 --- a/charts/iron-proxy/templates/_helpers.tpl +++ b/charts/iron-proxy/templates/_helpers.tpl @@ -144,6 +144,10 @@ from the CA mount. The control-plane token is emitted separately by the Deployme - name: IRON_CONTROL_PLANE_URL value: {{ . | quote }} {{- end }} +{{- with .Values.managed.pollInterval }} +- name: IRON_CONTROL_PLANE_POLL_INTERVAL + value: {{ . | quote }} +{{- end }} {{- with .Values.managed.proxyIP }} - name: IRON_DNS_PROXY_IP value: {{ . | quote }} diff --git a/charts/iron-proxy/values.yaml b/charts/iron-proxy/values.yaml index ff6c0e8..0e48134 100644 --- a/charts/iron-proxy/values.yaml +++ b/charts/iron-proxy/values.yaml @@ -81,6 +81,9 @@ managed: # -- Override the control plane URL (sets IRON_CONTROL_PLANE_URL). Empty uses # the binary default (https://api.iron.sh). controlPlaneURL: "" + # -- Control-plane poll interval (sets IRON_CONTROL_PLANE_POLL_INTERVAL). + # Empty uses the binary default (10s). + pollInterval: "" # -- REQUIRED in managed mode: IP returned for intercepted DNS queries # (IRON_DNS_PROXY_IP). Same meaning as config.dns.proxy_ip in standalone mode. proxyIP: "" diff --git a/cmd/iron-proxy/main.go b/cmd/iron-proxy/main.go index c8c756f..687948b 100644 --- a/cmd/iron-proxy/main.go +++ b/cmd/iron-proxy/main.go @@ -400,7 +400,7 @@ func initManaged(ctx context.Context, cfg *config.Config, bodyLimits transform.B } // Start config poller. - poller := controlplane.NewPoller(client, configHash, func(u controlplane.SyncUpdate) error { + poller := controlplane.NewPollerWithInterval(client, configHash, func(u controlplane.SyncUpdate) error { if u.Rules != nil || u.Secrets != nil || u.Transforms != nil { if err := applyPipelineSync(holder, bodyLimits, logger, u.Rules, u.Secrets, u.Transforms); err != nil { return err @@ -417,7 +417,7 @@ func initManaged(ctx context.Context, cfg *config.Config, bodyLimits transform.B } } return nil - }, logger) + }, logger, time.Duration(cfg.ControlPlane.PollInterval)) // Seed the poller's status from the startup sync so /v1/status (and the // fail-closed gate) reflect it before the polling loop's first pass. diff --git a/internal/config/config.go b/internal/config/config.go index 5ed8e11..56b06bd 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -12,9 +12,15 @@ import ( "github.com/ironsh/iron-proxy/internal/dnsguard" ) -// DefaultUpstreamResponseHeaderTimeout is the default cap on how long the -// proxy waits for upstream response headers before returning 502. -const DefaultUpstreamResponseHeaderTimeout = 30 * time.Second +const ( + // DefaultUpstreamResponseHeaderTimeout is the default cap on how long the + // proxy waits for upstream response headers before returning 502. + DefaultUpstreamResponseHeaderTimeout = 30 * time.Second + + // DefaultControlPlanePollInterval is the default base interval between + // control-plane sync calls. The poller applies jitter around this value. + DefaultControlPlanePollInterval = 10 * time.Second +) // Duration is a time.Duration that decodes YAML strings using // time.ParseDuration ("30s", "5m", "2h"). The zero value indicates "unset" @@ -46,15 +52,16 @@ func (d *Duration) UnmarshalYAML(value *yaml.Node) error { // package stays decoupled from the consumer's typed schema, and validation // errors surface where the value is actually used. type Config struct { - DNS DNS `yaml:"dns"` - Proxy Proxy `yaml:"proxy"` - TLS TLS `yaml:"tls"` - Transforms []Transform `yaml:"transforms"` - MCP yaml.Node `yaml:"mcp"` - Postgres yaml.Node `yaml:"postgres"` - Metrics Metrics `yaml:"metrics"` - Management Management `yaml:"management"` - Log Log `yaml:"log"` + DNS DNS `yaml:"dns"` + Proxy Proxy `yaml:"proxy"` + TLS TLS `yaml:"tls"` + Transforms []Transform `yaml:"transforms"` + MCP yaml.Node `yaml:"mcp"` + Postgres yaml.Node `yaml:"postgres"` + Metrics Metrics `yaml:"metrics"` + Management Management `yaml:"management"` + ControlPlane ControlPlane `yaml:"control_plane"` + Log Log `yaml:"log"` } // DNS configures the built-in DNS server. @@ -166,6 +173,14 @@ type Management struct { APIKeyEnv string `yaml:"api_key_env"` } +// ControlPlane configures managed-mode control-plane behavior. +type ControlPlane struct { + // PollInterval is the base interval between control-plane sync calls. + // Accepts Go duration syntax: "10s" (default), "1m", "500ms". + // The poller applies jitter around this value. + PollInterval Duration `yaml:"poll_interval"` +} + // Log configures structured logging. type Log struct { Level string `yaml:"level"` @@ -257,6 +272,9 @@ func applyDefaults(cfg *Config) { if cfg.Management.Listen != "" && cfg.Management.APIKeyEnv == "" { cfg.Management.APIKeyEnv = "IRON_MANAGEMENT_API_KEY" } + if cfg.ControlPlane.PollInterval == 0 { + cfg.ControlPlane.PollInterval = Duration(DefaultControlPlanePollInterval) + } if cfg.Log.Level == "" { cfg.Log.Level = "info" } @@ -289,6 +307,9 @@ func Validate(cfg *Config) error { if cfg.Proxy.UpstreamResponseHeaderTimeout <= 0 { return fmt.Errorf("proxy.upstream_response_header_timeout must be positive; got %s", time.Duration(cfg.Proxy.UpstreamResponseHeaderTimeout)) } + if cfg.ControlPlane.PollInterval <= 0 { + return fmt.Errorf("control_plane.poll_interval must be positive; got %s", time.Duration(cfg.ControlPlane.PollInterval)) + } if err := dnsguard.ValidateCIDRs(cfg.Proxy.UpstreamDenyCIDRs.Values); err != nil { return fmt.Errorf("proxy.upstream_deny_cidrs: %w", err) diff --git a/internal/config/config_test.go b/internal/config/config_test.go index 0b537dd..b7c4910 100644 --- a/internal/config/config_test.go +++ b/internal/config/config_test.go @@ -538,3 +538,63 @@ tls: require.Contains(t, err.Error(), "must be positive") }) } + +func TestLoad_ControlPlanePollInterval(t *testing.T) { + t.Run("default applied when unset", func(t *testing.T) { + yaml := ` +dns: + proxy_ip: "10.0.0.1" +tls: + ca_cert: "/tmp/ca.crt" + ca_key: "/tmp/ca.key" +` + cfg, err := Load(strings.NewReader(yaml)) + require.NoError(t, err) + require.Equal(t, 10*time.Second, time.Duration(cfg.ControlPlane.PollInterval)) + }) + + t.Run("valid duration accepted", func(t *testing.T) { + yaml := ` +dns: + proxy_ip: "10.0.0.1" +control_plane: + poll_interval: "30s" +tls: + ca_cert: "/tmp/ca.crt" + ca_key: "/tmp/ca.key" +` + cfg, err := Load(strings.NewReader(yaml)) + require.NoError(t, err) + require.Equal(t, 30*time.Second, time.Duration(cfg.ControlPlane.PollInterval)) + }) + + t.Run("invalid duration rejected at parse", func(t *testing.T) { + yaml := ` +dns: + proxy_ip: "10.0.0.1" +control_plane: + poll_interval: "not-a-duration" +tls: + ca_cert: "/tmp/ca.crt" + ca_key: "/tmp/ca.key" +` + _, err := Load(strings.NewReader(yaml)) + require.Error(t, err) + require.Contains(t, err.Error(), "invalid duration") + }) + + t.Run("negative duration rejected at validate", func(t *testing.T) { + yaml := ` +dns: + proxy_ip: "10.0.0.1" +control_plane: + poll_interval: "-5s" +tls: + ca_cert: "/tmp/ca.crt" + ca_key: "/tmp/ca.key" +` + _, err := Load(strings.NewReader(yaml)) + require.Error(t, err) + require.Contains(t, err.Error(), "control_plane.poll_interval must be positive") + }) +} diff --git a/internal/config/env.go b/internal/config/env.go index 8458f80..70ee9a2 100644 --- a/internal/config/env.go +++ b/internal/config/env.go @@ -94,5 +94,13 @@ func applyEnvOverrides(cfg *Config) error { cfg.Proxy.UpstreamResponseHeaderTimeout = Duration(d) } + if v := os.Getenv("IRON_CONTROL_PLANE_POLL_INTERVAL"); v != "" { + d, err := time.ParseDuration(v) + if err != nil { + return fmt.Errorf("IRON_CONTROL_PLANE_POLL_INTERVAL: %w", err) + } + cfg.ControlPlane.PollInterval = Duration(d) + } + return nil } diff --git a/internal/config/env_test.go b/internal/config/env_test.go index d377abc..61f8632 100644 --- a/internal/config/env_test.go +++ b/internal/config/env_test.go @@ -264,6 +264,39 @@ func TestApplyEnvOverrides_UpstreamResponseHeaderTimeout(t *testing.T) { }) } +func TestApplyEnvOverrides_ControlPlanePollInterval(t *testing.T) { + t.Run("env override applied", func(t *testing.T) { + setEnvs(t, map[string]string{ + "IRON_CONTROL_PLANE_POLL_INTERVAL": "15s", + }) + + var cfg Config + require.NoError(t, applyEnvOverrides(&cfg)) + require.Equal(t, 15*time.Second, time.Duration(cfg.ControlPlane.PollInterval)) + }) + + t.Run("env override beats yaml value", func(t *testing.T) { + setEnvs(t, map[string]string{ + "IRON_CONTROL_PLANE_POLL_INTERVAL": "20s", + }) + + cfg := Config{ControlPlane: ControlPlane{PollInterval: Duration(time.Minute)}} + require.NoError(t, applyEnvOverrides(&cfg)) + require.Equal(t, 20*time.Second, time.Duration(cfg.ControlPlane.PollInterval)) + }) + + t.Run("invalid duration rejected", func(t *testing.T) { + setEnvs(t, map[string]string{ + "IRON_CONTROL_PLANE_POLL_INTERVAL": "not-a-duration", + }) + + var cfg Config + err := applyEnvOverrides(&cfg) + require.Error(t, err) + require.Contains(t, err.Error(), "IRON_CONTROL_PLANE_POLL_INTERVAL") + }) +} + func TestApplyEnvOverrides_DNSEnabled(t *testing.T) { t.Run("false disables dns", func(t *testing.T) { setEnvs(t, map[string]string{"IRON_DNS_ENABLED": "false"}) diff --git a/internal/controlplane/poller.go b/internal/controlplane/poller.go index dc0a476..af3e284 100644 --- a/internal/controlplane/poller.go +++ b/internal/controlplane/poller.go @@ -10,8 +10,8 @@ import ( "time" ) -// PollInterval is the base interval between sync calls. -const PollInterval = 5 * time.Second +// DefaultPollInterval is the default base interval between sync calls. +const DefaultPollInterval = 10 * time.Second // SyncUpdate is the slice of a SyncResponse passed to the poller's update // callback. Fields are nil or JSON null when the control plane did not include @@ -42,6 +42,7 @@ type Poller struct { configHash string onUpdate func(SyncUpdate) error logger *slog.Logger + interval time.Duration mu sync.RWMutex status Status @@ -50,11 +51,20 @@ type Poller struct { // NewPoller creates a new sync poller. func NewPoller(client *Client, initialConfigHash string, onUpdate func(SyncUpdate) error, logger *slog.Logger) *Poller { + return NewPollerWithInterval(client, initialConfigHash, onUpdate, logger, DefaultPollInterval) +} + +// NewPollerWithInterval creates a new sync poller with a custom base interval. +func NewPollerWithInterval(client *Client, initialConfigHash string, onUpdate func(SyncUpdate) error, logger *slog.Logger, interval time.Duration) *Poller { + if interval <= 0 { + interval = DefaultPollInterval + } return &Poller{ client: client, configHash: initialConfigHash, onUpdate: onUpdate, logger: logger, + interval: interval, poke: make(chan struct{}, 1), } } @@ -103,7 +113,7 @@ func (p *Poller) recordSync(resp *SyncResponse) { } // Run starts the polling loop. It performs an initial sync immediately, then -// polls on PollInterval with ±10% jitter; a Poke wakes it early. Returns when +// polls on the configured interval with ±10% jitter; a Poke wakes it early. Returns when // ctx is canceled or a revocation error is received. func (p *Poller) Run(ctx context.Context) error { if err := p.sync(ctx); err != nil { @@ -114,7 +124,7 @@ func (p *Poller) Run(ctx context.Context) error { } for { - delay := jitteredInterval(PollInterval, 0.1) + delay := jitteredInterval(p.interval, 0.1) timer := time.NewTimer(delay) select { diff --git a/internal/controlplane/poller_test.go b/internal/controlplane/poller_test.go index ca982c3..c7c6410 100644 --- a/internal/controlplane/poller_test.go +++ b/internal/controlplane/poller_test.go @@ -169,7 +169,7 @@ func TestPollerContinuesOnTransientError(t *testing.T) { poller := NewPoller(client, "", nil, slog.New(slog.NewTextHandler(io.Discard, nil))) - // Run briefly -- the 30s interval means we won't get past the initial sync in 200ms, + // Run briefly. The 10s interval means we won't get past the initial sync in 200ms, // but the initial sync error should be handled gracefully. ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() @@ -241,7 +241,7 @@ func TestPollerPokeTriggersImmediateSync(t *testing.T) { }, 2*time.Second, 10*time.Millisecond) require.Equal(t, "sha256:one", poller.Status().ConfigHash) - // A poke must trigger the second sync long before the 5s poll interval. + // A poke must trigger the second sync long before the 10s poll interval. poller.Poke() require.Eventually(t, func() bool { return poller.Status().ConfigHash == "sha256:two" @@ -257,6 +257,35 @@ func TestPollerPokeTriggersImmediateSync(t *testing.T) { require.NoError(t, <-done) } +func TestPollerCustomIntervalTriggersSync(t *testing.T) { + var syncCalls atomic.Int32 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + syncCalls.Add(1) + w.WriteHeader(http.StatusOK) + _ = json.NewEncoder(w).Encode(SyncResponse{ConfigHash: "sha256:ok"}) + })) + defer server.Close() + + client := NewClient(server.URL, "irpt_test", testLogger()) + poller := NewPollerWithInterval(client, "", nil, testLogger(), 20*time.Millisecond) + + ctx, cancel := context.WithTimeout(context.Background(), 150*time.Millisecond) + defer cancel() + + err := poller.Run(ctx) + require.NoError(t, err) + require.GreaterOrEqual(t, syncCalls.Load(), int32(2)) +} + +func TestJitteredIntervalRange(t *testing.T) { + base := time.Second + for range 100 { + got := jitteredInterval(base, 0.1) + require.GreaterOrEqual(t, got, 900*time.Millisecond) + require.LessOrEqual(t, got, 1100*time.Millisecond) + } +} + func TestPollerStatusRetainsPrincipalOnHashMatch(t *testing.T) { var syncCalls atomic.Int32 server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { diff --git a/iron-proxy.example.yaml b/iron-proxy.example.yaml index 3f42e25..1bc3a1c 100644 --- a/iron-proxy.example.yaml +++ b/iron-proxy.example.yaml @@ -734,6 +734,11 @@ transforms: # # Env var that holds the bearer token. Defaults to IRON_MANAGEMENT_API_KEY. # api_key_env: "IRON_MANAGEMENT_API_KEY" +# Optional managed-mode control-plane settings. +# control_plane: +# # Base interval between sync polls. The poller adds jitter between polls. +# poll_interval: "10s" + # Logging log: level: "info" # debug, info, warn, error