Compare commits

..
2 Commits
Author SHA1 Message Date
Cédric Verstraeten 774df33c4d Merge pull request #371 from kerberos-io/feat/env-managed-config
Tell the Hub which settings come from environment variables
2026-11-27 15:38:13 +01:00
Cédric VerstraetenandClaude Opus 5.5 a37c5b1623 Tell the Hub which settings come from environment variables
The agent applies AGENT_* (and, in ConfigMap mode, GLOBAL_AGENT_*)
environment variables again on every start. A remote-config change the Hub
saves to such a setting is written to config.json and then undone at the
next restart; in ConfigMap mode config.json is ignored entirely.

receive-config now carries "env_managed": {"all": bool, "paths": [...]}:
"all" in ConfigMap mode, and the JSON paths of the settings set by
environment variables (e.g. "capture.ipcamera.rtsp"), so the Hub can show
them read-only. It is omitted when no setting comes from the environment.

envConfigFields maps each AGENT_* variable to the Config field it sets;
tests keep it in step with applyAgentEnvVars.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-27 14:19:34 +00:00
3 changed files with 364 additions and 0 deletions
+180
View File
@@ -0,0 +1,180 @@
package config
import (
"os"
"reflect"
"sort"
"strings"
"github.com/kerberos-io/agent/machinery/src/models"
)
// envConfigFields maps every AGENT_* environment variable that
// applyAgentEnvVars reads to the Config field it sets, as a Go field path.
// TestEnvConfigFieldsCoverEveryEnvVar keeps this table in step with the
// switch in applyAgentEnvVars.
var envConfigFields = map[string]string{
"AGENT_KEY": "Key",
"AGENT_NAME": "FriendlyName",
"AGENT_TIMEZONE": "Timezone",
"AGENT_OFFLINE": "Offline",
"AGENT_AUTO_CLEAN": "AutoClean",
"AGENT_AUTO_CLEAN_MAX_SIZE": "MaxDirectorySize",
"AGENT_AUTO_CLEAN_MIN_FREE_SPACE": "MinFreeSpace",
"AGENT_CAPTURE_IPCAMERA_RTSP": "Capture.IPCamera.RTSP",
"AGENT_CAPTURE_IPCAMERA_RTSP_TRANSPORT": "Capture.IPCamera.RTSPTransport",
"AGENT_CAPTURE_IPCAMERA_SUB_RTSP": "Capture.IPCamera.SubRTSP",
"AGENT_CAPTURE_IPCAMERA_BASE_WIDTH": "Capture.IPCamera.BaseWidth",
"AGENT_CAPTURE_IPCAMERA_BASE_HEIGHT": "Capture.IPCamera.BaseHeight",
"AGENT_CAPTURE_IPCAMERA_ONVIF": "Capture.IPCamera.ONVIF",
"AGENT_CAPTURE_IPCAMERA_ONVIF_XADDR": "Capture.IPCamera.ONVIFXAddr",
"AGENT_CAPTURE_IPCAMERA_ONVIF_USERNAME": "Capture.IPCamera.ONVIFUsername",
"AGENT_CAPTURE_IPCAMERA_ONVIF_PASSWORD": "Capture.IPCamera.ONVIFPassword",
"AGENT_CAPTURE_IPCAMERA_ONVIF_CHANNEL": "Capture.IPCamera.ONVIFChannel",
"AGENT_CAPTURE_RECORDING": "Capture.Recording",
"AGENT_CAPTURE_CONTINUOUS": "Capture.Continuous",
"AGENT_CAPTURE_LIVEVIEW": "Capture.Liveview",
"AGENT_CAPTURE_MOTION": "Capture.Motion",
"AGENT_CAPTURE_ONVIF_MOTION": "Capture.ONVIFMotion",
"AGENT_CAPTURE_SNAPSHOTS": "Capture.Snapshots",
"AGENT_CAPTURE_PRERECORDING": "Capture.PreRecording",
"AGENT_CAPTURE_POSTRECORDING": "Capture.PostRecording",
"AGENT_CAPTURE_MAXLENGTH": "Capture.MaxLengthRecording",
"AGENT_CAPTURE_PIXEL_CHANGE": "Capture.PixelChangeThreshold",
"AGENT_CAPTURE_FRAGMENTED": "Capture.Fragmented",
"AGENT_CAPTURE_FRAGMENTED_DURATION": "Capture.FragmentedDuration",
"AGENT_CAPTURE_LIVEVIEW_CHUNKING": "Capture.LiveviewChunking",
"AGENT_TIME": "Time",
"AGENT_TIMETABLE": "Timetable",
"AGENT_REGION_POLYGON": "Region.Polygon",
"AGENT_MQTT_URI": "MQTTURI",
"AGENT_MQTT_USERNAME": "MQTTUsername",
"AGENT_MQTT_PASSWORD": "MQTTPassword",
"AGENT_REALTIME_PROCESSING": "RealtimeProcessing",
"AGENT_REALTIME_PROCESSING_TOPIC": "RealtimeProcessingTopic",
"AGENT_STUN_URI": "STUNURI",
"AGENT_FORCE_TURN": "ForceTurn",
"AGENT_TURN_URI": "TURNURI",
"AGENT_TURN_USERNAME": "TURNUsername",
"AGENT_TURN_PASSWORD": "TURNPassword",
"AGENT_CLOUD": "Cloud",
"AGENT_REMOVE_AFTER_UPLOAD": "RemoveAfterUpload",
"AGENT_HUB_ENCRYPTION": "HubEncryption",
"AGENT_HUB_URI": "HubURI",
"AGENT_HUB_KEY": "HubKey",
"AGENT_HUB_PRIVATE_KEY": "HubPrivateKey",
"AGENT_HUB_SITE": "HubSite",
"AGENT_HUB_REGION": "S3.Region",
"AGENT_KERBEROSVAULT_URI": "KStorage.URI",
"AGENT_KERBEROSVAULT_ACCESS_KEY": "KStorage.AccessKey",
"AGENT_KERBEROSVAULT_SECRET_KEY": "KStorage.SecretAccessKey",
"AGENT_KERBEROSVAULT_PROVIDER": "KStorage.Provider",
"AGENT_KERBEROSVAULT_DIRECTORY": "KStorage.Directory",
"AGENT_KERBEROSVAULT_CUSTOM_HEADERS": "KStorage.CustomHeaders",
"AGENT_KERBEROSVAULT_MAX_RETRIES": "KStorage.MaxRetries",
"AGENT_KERBEROSVAULT_TIMEOUT": "KStorage.Timeout",
"AGENT_KERBEROSVAULT_SECONDARY_URI": "KStorageSecondary.URI",
"AGENT_KERBEROSVAULT_SECONDARY_ACCESS_KEY": "KStorageSecondary.AccessKey",
"AGENT_KERBEROSVAULT_SECONDARY_SECRET_KEY": "KStorageSecondary.SecretAccessKey",
"AGENT_KERBEROSVAULT_SECONDARY_PROVIDER": "KStorageSecondary.Provider",
"AGENT_KERBEROSVAULT_SECONDARY_DIRECTORY": "KStorageSecondary.Directory",
"AGENT_KERBEROSVAULT_SECONDARY_CUSTOM_HEADERS": "KStorageSecondary.CustomHeaders",
"AGENT_DROPBOX_ACCESS_TOKEN": "Dropbox.AccessToken",
"AGENT_DROPBOX_DIRECTORY": "Dropbox.Directory",
"AGENT_ENCRYPTION": "Encryption.Enabled",
"AGENT_ENCRYPTION_RECORDINGS": "Encryption.Recordings",
"AGENT_ENCRYPTION_FINGERPRINT": "Encryption.Fingerprint",
"AGENT_ENCRYPTION_PRIVATE_KEY": "Encryption.PrivateKey",
"AGENT_ENCRYPTION_SYMMETRIC_KEY": "Encryption.SymmetricKey",
"AGENT_SIGNING": "Signing.Enabled",
"AGENT_SIGNING_PRIVATE_KEY": "Signing.PrivateKey",
}
// EnvManaged tells a remote editor (the Hub) which settings come from
// environment variables. The agent applies those again on every start, so a
// change saved to them through the Hub is undone at the next restart.
//
// All is true in ConfigMap mode: the configuration is then built only from
// GLOBAL_AGENT_* and AGENT_* variables and the saved config.json is ignored,
// so no remote change survives a restart. Paths lists the JSON paths of the
// configuration fields set by environment variables, e.g.
// "capture.ipcamera.rtsp".
type EnvManaged struct {
All bool `json:"all"`
Paths []string `json:"paths"`
}
// IsEmpty reports whether no setting is managed by environment variables.
func (e EnvManaged) IsEmpty() bool {
return !e.All && len(e.Paths) == 0
}
// EnvManagedConfig reports which settings the current environment variables
// manage, following the same rules as OverrideWithEnvironmentVariables.
func EnvManagedConfig() EnvManaged {
standalone := os.Getenv("DEPLOYMENT") == "" || os.Getenv("DEPLOYMENT") == "agent"
seen := map[string]bool{}
add := func(goPath string) {
if path, ok := configJSONPath(goPath); ok {
seen[path] = true
}
}
if os.Getenv("DEPLOYMENT_NAME") != "" {
add("Name")
}
for _, env := range os.Environ() {
fullKey := strings.SplitN(env, "=", 2)[0]
key := fullKey
if strings.HasPrefix(fullKey, "GLOBAL_AGENT_") {
// GLOBAL_AGENT_* variables are only applied in standalone and
// ConfigMap mode, not in Factory/MongoDB mode.
if !standalone {
continue
}
key = strings.TrimPrefix(fullKey, "GLOBAL_")
}
if goPath, ok := envConfigFields[key]; ok {
add(goPath)
}
}
paths := make([]string, 0, len(seen))
for path := range seen {
paths = append(paths, path)
}
sort.Strings(paths)
return EnvManaged{
All: standalone && isConfigMapMode(),
Paths: paths,
}
}
// configJSONPath converts a Go field path of models.Config (e.g.
// "Capture.IPCamera.RTSP") into its JSON path (e.g. "capture.ipcamera.rtsp").
func configJSONPath(goPath string) (string, bool) {
t := reflect.TypeOf(models.Config{})
segments := strings.Split(goPath, ".")
jsonSegments := make([]string, 0, len(segments))
for _, segment := range segments {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
if t.Kind() != reflect.Struct {
return "", false
}
field, ok := t.FieldByName(segment)
if !ok {
return "", false
}
name := strings.Split(field.Tag.Get("json"), ",")[0]
if name == "" || name == "-" {
name = field.Name
}
jsonSegments = append(jsonSegments, name)
t = field.Type
}
return strings.Join(jsonSegments, "."), true
}
+177
View File
@@ -0,0 +1,177 @@
package config
import (
"os"
"reflect"
"regexp"
"strings"
"testing"
"github.com/kerberos-io/agent/machinery/src/models"
)
// Every AGENT_* variable handled by applyAgentEnvVars needs an entry in
// envConfigFields, and the table must not list variables that are not handled.
func TestEnvConfigFieldsCoverEveryEnvVar(t *testing.T) {
source, err := os.ReadFile("main.go")
if err != nil {
t.Fatal(err)
}
start := strings.Index(string(source), "func applyAgentEnvVars(")
if start < 0 {
t.Fatal("applyAgentEnvVars not found in main.go")
}
handled := map[string]bool{}
for _, match := range regexp.MustCompile(`case "(AGENT_[A-Z0-9_]+)":`).FindAllStringSubmatch(string(source[start:]), -1) {
handled[match[1]] = true
}
if len(handled) == 0 {
t.Fatal("no AGENT_* cases found")
}
for key := range handled {
if _, ok := envConfigFields[key]; !ok {
t.Errorf("%s is handled by applyAgentEnvVars but missing from envConfigFields", key)
}
}
for key := range envConfigFields {
if !handled[key] {
t.Errorf("%s is in envConfigFields but not handled by applyAgentEnvVars", key)
}
}
}
func TestEnvConfigFieldsResolveToJSONPaths(t *testing.T) {
for key, goPath := range envConfigFields {
if _, ok := configJSONPath(goPath); !ok {
t.Errorf("%s: %q is not a field path of models.Config", key, goPath)
}
}
want := map[string]string{
"AGENT_CAPTURE_IPCAMERA_RTSP": "capture.ipcamera.rtsp",
"AGENT_CAPTURE_PIXEL_CHANGE": "capture.pixelChangeThreshold",
"AGENT_REGION_POLYGON": "region.polygon",
"AGENT_KERBEROSVAULT_SECONDARY_URI": "kstorage_secondary.uri",
"AGENT_NAME": "friendly_name",
"AGENT_HUB_REGION": "s3.region",
}
for key, path := range want {
got, _ := configJSONPath(envConfigFields[key])
if got != path {
t.Errorf("%s: path = %q, want %q", key, got, path)
}
}
}
// Setting a variable on its own must change the field the table names.
func TestEnvConfigFieldsMatchApplyAgentEnvVars(t *testing.T) {
samples := map[string]string{
"AGENT_TIMETABLE": "0,43199,43200,86400",
"AGENT_REGION_POLYGON": "0,0;10,0;10,10",
}
for key, goPath := range envConfigFields {
t.Run(key, func(t *testing.T) {
configuration := &models.Configuration{}
initConfigPointers(&configuration.Config)
field := configField(reflect.ValueOf(&configuration.Config).Elem(), goPath)
if !field.IsValid() {
t.Fatalf("%q not found", goPath)
}
sample, ok := samples[key]
if !ok {
switch underlying(field.Type()).Kind() {
case reflect.String:
sample = "sample"
default:
sample = "7"
}
}
t.Setenv(key, sample)
applyAgentEnvVars(configuration, "", false)
field = configField(reflect.ValueOf(&configuration.Config).Elem(), goPath)
if !field.IsValid() || field.IsZero() {
t.Fatalf("%s=%q did not set %s", key, sample, goPath)
}
})
}
}
func TestEnvManagedConfig(t *testing.T) {
clearAgentEnv(t)
t.Run("nothing set", func(t *testing.T) {
if got := EnvManagedConfig(); !got.IsEmpty() {
t.Fatalf("got %+v, want empty", got)
}
})
t.Run("standalone with AGENT_* variables", func(t *testing.T) {
t.Setenv("AGENT_CAPTURE_IPCAMERA_RTSP", "rtsp://camera/stream")
t.Setenv("AGENT_REGION_POLYGON", "0,0;10,0;10,10")
t.Setenv("DEPLOYMENT_NAME", "agent-front-door")
got := EnvManagedConfig()
want := EnvManaged{All: false, Paths: []string{"capture.ipcamera.rtsp", "name", "region.polygon"}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %+v, want %+v", got, want)
}
})
t.Run("ConfigMap mode manages everything", func(t *testing.T) {
t.Setenv("GLOBAL_AGENT_TIMEZONE", "Europe/Brussels")
t.Setenv("AGENT_CAPTURE_IPCAMERA_RTSP", "rtsp://camera/stream")
got := EnvManagedConfig()
want := EnvManaged{All: true, Paths: []string{"capture.ipcamera.rtsp", "timezone"}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %+v, want %+v", got, want)
}
})
t.Run("Factory mode ignores GLOBAL_AGENT_* variables", func(t *testing.T) {
t.Setenv("DEPLOYMENT", "factory")
t.Setenv("GLOBAL_AGENT_TIMEZONE", "Europe/Brussels")
t.Setenv("AGENT_CAPTURE_IPCAMERA_RTSP", "rtsp://camera/stream")
got := EnvManagedConfig()
want := EnvManaged{All: false, Paths: []string{"capture.ipcamera.rtsp"}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %+v, want %+v", got, want)
}
})
}
// clearAgentEnv unsets variables that would leak into these tests from the
// environment running them; t.Setenv restores them afterwards.
func clearAgentEnv(t *testing.T) {
for _, env := range os.Environ() {
key := strings.SplitN(env, "=", 2)[0]
if strings.HasPrefix(key, "AGENT_") || strings.HasPrefix(key, "GLOBAL_AGENT_") ||
key == "DEPLOYMENT" || key == "DEPLOYMENT_NAME" {
t.Setenv(key, "")
os.Unsetenv(key)
}
}
}
func underlying(t reflect.Type) reflect.Type {
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
return t
}
// configField follows a Go field path through (pointer) structs.
func configField(v reflect.Value, goPath string) reflect.Value {
for _, segment := range strings.Split(goPath, ".") {
for v.Kind() == reflect.Ptr {
if v.IsNil() {
return reflect.Value{}
}
v = v.Elem()
}
v = v.FieldByName(segment)
if !v.IsValid() {
return v
}
}
return v
}
+7
View File
@@ -848,6 +848,13 @@ func HandleRequestConfig(mqttClient mqtt.Client, hubKey string, payload models.P
// Unset encryption part.
delete(configMap, "encryption")
// Tell the Hub which settings come from environment variables:
// those are applied again on every start, so the Hub shows them
// as read-only instead of saving changes that would be undone.
if envManaged := configService.EnvManagedConfig(); !envManaged.IsEmpty() && configMap != nil {
configMap["env_managed"] = envManaged
}
message := models.Message{
Payload: models.Payload{
Action: "receive-config",