9fdbb8aab0
Implements the Linux half of AGENT_LOCAL_DISCOVERY_SPEC.md: when a local theta-gateway/theta-proxy announces itself via mDNS as fronting this agent's ServerURL host, skip the relay/WAN path and talk to it directly. Off by default (config.PreferLocalDirectory / prefer_local_directory) since it changes host name resolution. - local_discovery.go: polls for _theta-suite._tcp every 30s via hashicorp/mdns, matches the TXT "hosts" field against the agent's own target host, applies/clears a hosts-file override on change. Presence/ absence of the mDNS announcement IS the "on this LAN or not" signal -- no separate network detection needed, since multicast doesn't cross routers/VLANs. - hosts_override.go: writes a single marked, idempotent block into /etc/hosts (never touches anything else in the file); clearing removes the block entirely rather than leaving empty markers. - HARD RULE preserved: this only ever changes DNS resolution, never TLS trust -- nothing here touches certificate validation, so a spoofed rogue mDNS announcement produces a TLS failure against the real hostname's cert, not a silent MITM. Verified end-to-end with real containers (Node mDNS announcer + this actual Go binary, not mocked), which caught two real bugs neither showed up in code review: 1. mdns.Lookup()'s DefaultParams() requests both IPv4 and IPv6. The underlying client sends the v4 query (which got a real, valid response per a packet capture), then sends the v6 query, and if THAT send fails (no IPv6 route -- common on plain v4 hosts/containers) the whole Query() returns that error synchronously, before ever entering the response-listening loop. The v4 response was silently discarded. Fixed by building QueryParam manually with DisableIPv6: true instead of using the Lookup() convenience wrapper. 2. The original hosts-file writer used write-tmp-then-rename for atomicity. /etc/hosts is frequently a bind mount (every container runtime does this) -- rename() onto a bind-mounted file fails with EBUSY, since you can't atomically replace a mountpoint. Switched to truncate-and-rewrite in place; the process-local mutex already serializes writers, so the lost atomicity is a small, acceptable tradeoff against a confirmed hard failure. Full cycle verified: announcer starts -> agent discovers it -> hosts override applied -> announcer stops -> override cleanly reverts, no stale entry, no discovery trace left. Windows/macOS remain unbuilt -- need platform-native testing this environment can't do (see AGENT_LOCAL_DISCOVERY_SPEC.md §3's open question: hosts-file edits vs. a local stub resolver, per-OS elevation and DNS-cache behavior).
283 lines
8.9 KiB
Go
283 lines
8.9 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"os"
|
|
"regexp"
|
|
"strings"
|
|
"sync"
|
|
|
|
"gopkg.in/yaml.v3"
|
|
)
|
|
|
|
type Capabilities struct {
|
|
Telemetry bool `yaml:"telemetry"`
|
|
ConfigureLDAP bool `yaml:"configure_ldap"`
|
|
Reboot bool `yaml:"reboot"`
|
|
ServiceControl []string `yaml:"service_control"`
|
|
ArbitraryBash bool `yaml:"arbitrary_bash"`
|
|
LdapTunnel bool `yaml:"ldap_tunnel"`
|
|
Secrets bool `yaml:"secrets"`
|
|
IAM bool `yaml:"iam"`
|
|
WireGuard bool `yaml:"wireguard"`
|
|
}
|
|
|
|
// SecretTarget maps a local template to a rendered target file and an optional
|
|
// post-render reload command (DESIGN.md §5).
|
|
type SecretTarget struct {
|
|
Template string `yaml:"template"`
|
|
Target string `yaml:"target"`
|
|
Reload string `yaml:"reload"`
|
|
}
|
|
|
|
// WireGuardConfig holds the mesh client settings (DESIGN-WINDOWS.md §5).
|
|
type WireGuardConfig struct {
|
|
// TunnelName is the WireGuard interface (Linux) / service name (Windows).
|
|
TunnelName string `yaml:"tunnel_name"`
|
|
// Conf is where the pushed peer config is persisted on disk.
|
|
Conf string `yaml:"conf"`
|
|
// Executable is the wireguard.exe path (Windows); "" = PATH or default
|
|
// install location.
|
|
Executable string `yaml:"executable"`
|
|
}
|
|
|
|
type Config struct {
|
|
ServerURL string `yaml:"server_url"`
|
|
AuthToken string `yaml:"auth_token"`
|
|
// A join key is the one credential an operator hands out. On first connect
|
|
// the server exchanges it for a per-agent AuthToken (written back to this
|
|
// file), so it is a bootstrap value, not a long-term credential. Used only
|
|
// when AuthToken is empty.
|
|
JoinKey string `yaml:"join_key"`
|
|
Location string `yaml:"location"`
|
|
PublicKey string `yaml:"public_key"` // Ed25519 public key for signed commands
|
|
LdapSocket string `yaml:"ldap_socket"` // local LDAP tunnel socket (DESIGN.md §4)
|
|
Secrets []SecretTarget `yaml:"secrets"` // secret templates to render (DESIGN.md §5)
|
|
Capabilities Capabilities `yaml:"capabilities"`
|
|
|
|
// Windows-specific (DESIGN-WINDOWS.md §11).
|
|
ServiceName string `yaml:"service_name"` // Windows service name
|
|
DesktopHelper string `yaml:"desktop_helper"` // theta-agent-helper.exe path
|
|
PublicIPDetect *bool `yaml:"public_ip_detect"` // false disables external lookups (air-gap)
|
|
AutoVPN bool `yaml:"auto_vpn"` // auto-connect WireGuard when away
|
|
WireGuard WireGuardConfig `yaml:"wireguard"`
|
|
|
|
// PreferLocalDirectory opts into mDNS local-discovery (MULTI_SITE_SPEC.md
|
|
// Appendix B): when a theta-gateway/theta-proxy on the local network
|
|
// segment announces itself as fronting this agent's ServerURL host, skip
|
|
// the WAN/relay path and talk to it directly. Off by default -- it
|
|
// changes name resolution behavior on the host, so it's opt-in, not
|
|
// automatic. Linux only for now (see local_discovery.go); Windows/macOS
|
|
// need their own platform-native investigation before this flag does
|
|
// anything there.
|
|
PreferLocalDirectory bool `yaml:"prefer_local_directory"`
|
|
}
|
|
|
|
// DetectPublicIP reports whether the agent may perform external public-IP
|
|
// lookups. Defaults to true; an air-gapped host sets public_ip_detect: false so
|
|
// the agent never tries to reach ipify/icanhazip/etc.
|
|
func (c *Config) DetectPublicIP() bool {
|
|
if c.PublicIPDetect == nil {
|
|
return true
|
|
}
|
|
return *c.PublicIPDetect
|
|
}
|
|
|
|
// ServiceNameOrDefault returns the Windows service name, defaulting to
|
|
// theta-agent when unset.
|
|
func (c *Config) ServiceNameOrDefault() string {
|
|
if c.ServiceName != "" {
|
|
return c.ServiceName
|
|
}
|
|
return "theta-agent"
|
|
}
|
|
|
|
// Credential returns the value to present when connecting: our own token once
|
|
// enrolled, otherwise the join key.
|
|
func (c *Config) Credential() string {
|
|
if c.AuthToken != "" {
|
|
return c.AuthToken
|
|
}
|
|
return c.JoinKey
|
|
}
|
|
|
|
// ConfigManager handles thread-safe access and reloading of the agent configuration.
|
|
type ConfigManager struct {
|
|
mu sync.RWMutex
|
|
current *Config
|
|
configPath string
|
|
}
|
|
|
|
func NewConfigManager(path string) (*ConfigManager, error) {
|
|
cfg, err := LoadConfig(path)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return &ConfigManager{
|
|
current: cfg,
|
|
configPath: path,
|
|
}, nil
|
|
}
|
|
|
|
// Get returns a copy of the current configuration.
|
|
func (cm *ConfigManager) Get() *Config {
|
|
cm.mu.RLock()
|
|
defer cm.mu.RUnlock()
|
|
return cm.current
|
|
}
|
|
|
|
// Reload re-reads the configuration from disk and updates the active config.
|
|
func (cm *ConfigManager) Reload() error {
|
|
cfg, err := LoadConfig(cm.configPath)
|
|
if err != nil {
|
|
return fmt.Errorf("reload failed: %w", err)
|
|
}
|
|
cm.mu.Lock()
|
|
cm.current = cfg
|
|
cm.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
// PersistEnrollment writes the credentials the server issued during join-key
|
|
// enrollment back into agent.yml, then reloads. Only the auth_token and
|
|
// public_key lines are rewritten (added if absent); every other line, including
|
|
// operator comments and the capability matrix, is preserved -- this file is
|
|
// hand-edited, so a naive marshal-and-write would destroy it.
|
|
//
|
|
// The join key is blanked once we hold our own token: leaving a fleet-wide
|
|
// credential on every host after it has stopped being needed is exactly the
|
|
// blast radius the per-agent token exists to avoid.
|
|
func (cm *ConfigManager) PersistEnrollment(token, publicKey string) error {
|
|
if token == "" {
|
|
return fmt.Errorf("server reported enrollment but sent no token")
|
|
}
|
|
|
|
cm.mu.Lock()
|
|
defer cm.mu.Unlock()
|
|
|
|
raw, err := os.ReadFile(cm.configPath)
|
|
if err != nil {
|
|
return fmt.Errorf("read %s: %w", cm.configPath, err)
|
|
}
|
|
|
|
out := setYamlScalar(string(raw), "auth_token", token)
|
|
if publicKey != "" {
|
|
out = setYamlScalar(out, "public_key", publicKey)
|
|
}
|
|
out = setYamlScalar(out, "join_key", "")
|
|
|
|
// Same permissions the installer sets: this file now holds a credential.
|
|
if err := os.WriteFile(cm.configPath, []byte(out), 0600); err != nil {
|
|
return fmt.Errorf("write %s: %w", cm.configPath, err)
|
|
}
|
|
|
|
cfg, err := LoadConfig(cm.configPath)
|
|
if err != nil {
|
|
return fmt.Errorf("reload after enrollment: %w", err)
|
|
}
|
|
cm.current = cfg
|
|
return nil
|
|
}
|
|
|
|
// PersistAutoVPN writes the tray's auto-VPN preference back into agent.yml so
|
|
// it survives a restart. Same line-preserving edit as PersistEnrollment.
|
|
func (cm *ConfigManager) PersistAutoVPN(value bool) error {
|
|
cm.mu.Lock()
|
|
defer cm.mu.Unlock()
|
|
|
|
raw, err := os.ReadFile(cm.configPath)
|
|
if err != nil {
|
|
return fmt.Errorf("read %s: %w", cm.configPath, err)
|
|
}
|
|
out := setYamlScalarValue(string(raw), "auto_vpn", fmt.Sprintf("%t", value), false)
|
|
if err := os.WriteFile(cm.configPath, []byte(out), 0600); err != nil {
|
|
return fmt.Errorf("write %s: %w", cm.configPath, err)
|
|
}
|
|
|
|
cfg, err := LoadConfig(cm.configPath)
|
|
if err != nil {
|
|
return fmt.Errorf("reload after auto_vpn: %w", err)
|
|
}
|
|
cm.current = cfg
|
|
return nil
|
|
}
|
|
|
|
// ClearEnrollment blanks the auth_token and public_key so the agent re-enrolls
|
|
// with whatever join_key is configured. Triggered by the tray's "re-enroll".
|
|
func (cm *ConfigManager) ClearEnrollment() error {
|
|
cm.mu.Lock()
|
|
defer cm.mu.Unlock()
|
|
|
|
raw, err := os.ReadFile(cm.configPath)
|
|
if err != nil {
|
|
return fmt.Errorf("read %s: %w", cm.configPath, err)
|
|
}
|
|
out := setYamlScalar(string(raw), "auth_token", "")
|
|
out = setYamlScalar(out, "public_key", "")
|
|
if err := os.WriteFile(cm.configPath, []byte(out), 0600); err != nil {
|
|
return fmt.Errorf("write %s: %w", cm.configPath, err)
|
|
}
|
|
|
|
cfg, err := LoadConfig(cm.configPath)
|
|
if err != nil {
|
|
return fmt.Errorf("reload after enrollment clear: %w", err)
|
|
}
|
|
cm.current = cfg
|
|
return nil
|
|
}
|
|
|
|
// setYamlScalar replaces the value of a top-level `key: "..."` line, or appends
|
|
// the key when it is absent. Deliberately line-based rather than a YAML
|
|
// round-trip so comments and formatting survive.
|
|
func setYamlScalar(doc, key, value string) string {
|
|
return setYamlScalarValue(doc, key, value, true)
|
|
}
|
|
|
|
// setYamlScalarValue is setYamlScalar with control over quoting. Numeric/bool
|
|
// scalars (e.g. auto_vpn: true) must stay unquoted or YAML decodes them as
|
|
// strings.
|
|
func setYamlScalarValue(doc, key, value string, quote bool) string {
|
|
line := fmt.Sprintf("%s: %s", key, value)
|
|
if quote {
|
|
line = fmt.Sprintf("%s: %q", key, value)
|
|
}
|
|
re := regexp.MustCompile(`(?m)^[ \t]*` + regexp.QuoteMeta(key) + `[ \t]*:.*$`)
|
|
if re.MatchString(doc) {
|
|
return re.ReplaceAllString(doc, line)
|
|
}
|
|
if !strings.HasSuffix(doc, "\n") {
|
|
doc += "\n"
|
|
}
|
|
return doc + line + "\n"
|
|
}
|
|
|
|
func LoadConfig(path string) (*Config, error) {
|
|
file, err := os.Open(path)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("failed to open config file: %w", err)
|
|
}
|
|
defer file.Close()
|
|
|
|
var cfg Config
|
|
decoder := yaml.NewDecoder(file)
|
|
if err := decoder.Decode(&cfg); err != nil {
|
|
return nil, fmt.Errorf("failed to decode YAML config: %w", err)
|
|
}
|
|
|
|
if cfg.Capabilities.ConfigureLDAP {
|
|
cfg.Capabilities.LdapTunnel = true
|
|
}
|
|
|
|
return &cfg, nil
|
|
}
|
|
|
|
// CanManageService checks if a specific service is permitted to be restarted/stopped
|
|
func (c *Capabilities) CanManageService(serviceName string) bool {
|
|
for _, allowed := range c.ServiceControl {
|
|
if allowed == serviceName {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|