Add docstrings to mdm_integration

This commit is contained in:
riccardom
2026-06-09 10:49:57 +00:00
parent d7f00b3beb
commit bd9fed41ad
13 changed files with 129 additions and 31 deletions

View File

@@ -109,7 +109,9 @@ var debugConfigCmd = &cobra.Command{
// debugConfigDump requests the daemon for the resolved effective configuration and prints it as indented JSON.
// It resolves the active profile and current OS user, calls DaemonService.GetConfig with those values, and
// marshals the response using protojson with default/zero-valued fields included.
// Returns an error if profile or user lookup fails, the gRPC call fails, or the response cannot be marshaled.
// debugConfigDump prints the daemon's effective configuration for the active profile and current OS user as indented JSON.
// It requests the configuration from the daemon and writes the protobuf response with default fields emitted to stdout.
// Returns an error if active profile or user lookup fails, the daemon RPC fails, or the response cannot be marshaled.
func debugConfigDump(cmd *cobra.Command, _ []string) error {
pm := profilemanager.NewProfileManager()
activeProf, err := pm.GetActiveProfile()
@@ -155,7 +157,10 @@ func debugConfigDump(cmd *cobra.Command, _ []string) error {
// local file path and, if uploaded, the uploaded file key.
// It uses the package flags (anonymize, system info, log file count, CLI version and
// optional upload URL) to configure the bundle request. Returns an error if the RPC
// fails or if the daemon reports an upload failure reason.
// debugBundle requests creation of a debug bundle from the daemon and prints
// the local bundle file path and, if uploading was enabled, the uploaded file key.
// It returns an error if the RPC fails, if the daemon reports an upload failure
// reason, or if establishing the connection fails.
func debugBundle(cmd *cobra.Command, _ []string) error {
conn, err := getClient(cmd)
if err != nil {

View File

@@ -95,7 +95,9 @@ var (
}
)
// Execute executes the root command.
// Execute runs the appropriate Cobra command for the CLI.
// If the process is the update binary it delegates to updateCmd; otherwise it runs the root command.
// It returns any error produced during command execution.
func Execute() error {
if isUpdateBinary() {
return updateCmd.Execute()
@@ -108,7 +110,15 @@ func Execute() error {
// registers persistent flags (daemon address, management/admin URLs, logging, setup key, preshared key,
// hostname, anonymize, config path), attaches top-level and nested subcommands to the root command,
// and configures `up` command specific flags (external IP maps, DNS resolver address, Rosenpass options,
// auto-connect disabling, and lazy connection).
// init initializes package-level defaults and configures the root Cobra command.
//
// It sets default configuration and log directory paths (including legacy Wiretrustee
// locations) based on the runtime OS, builds default config/log file paths, and selects
// a platform-appropriate default daemon address. It registers persistent CLI flags
// (including mutually exclusive setup-key and setup-key-file), attaches top-level
// commands and subcommands to the root command, and registers `up`-specific persistent
// flags for external IP mapping, custom DNS resolver address, Rosenpass options,
// auto-connect disabling, and lazy connection.
func init() {
defaultConfigPathDir = "/etc/netbird/"
defaultLogFileDir = "/var/log/netbird/"

View File

@@ -719,7 +719,7 @@ func (config *Config) applyMDMPolicy(policy *mdm.Policy) {
// parseURL parses and validates the URL for the named service.
// It requires the URL to use the http or https scheme and, if no port is present,
// appends ":443" for https or ":80" for http. On success it returns the parsed
// *url.URL; on failure it returns a non-nil error.
// ":80" is appended. The `serviceName` is used to contextualize error messages.
func parseURL(serviceName, serviceURL string) (*url.URL, error) {
parsedMgmtURL, err := url.ParseRequestURI(serviceURL)
if err != nil {

View File

@@ -85,7 +85,9 @@ type Policy struct {
// NewPolicy constructs a Policy from a key→value map. Pass nil or an empty
// NewPolicy constructs a Policy backed by the provided key→value map.
// If values is nil it is replaced with an empty map so the returned *Policy
// is always non-nil and represents no active MDM enforcement when empty.
// NewPolicy constructs a non-nil *Policy that wraps the provided key/value map.
// If values is nil it is replaced with an empty map so the returned Policy always
// represents "no MDM enforcement" when its values are empty.
func NewPolicy(values map[string]any) *Policy {
if values == nil {
values = map[string]any{}
@@ -102,7 +104,11 @@ func NewPolicy(values map[string]any) *Policy {
// - source present, zero keys: info "MDM enrolled (no managed keys)"
// LoadPolicy loads MDM-managed configuration from the platform and returns a Policy representing the managed settings.
// If the platform loader fails or returns nil, LoadPolicy returns a non-nil empty Policy.
// When the loaded map contains zero keys it logs that MDM is enrolled with no managed keys; when it contains keys it logs the count and a stable, sorted list of key names.
// LoadPolicy loads platform-managed MDM key/value pairs and returns a non-nil Policy.
// If the platform loader returns an error or a nil map, an empty Policy is returned.
// On loader error a trace-level message is emitted. When a map is returned, an
// informational message is logged either indicating enrollment with no managed keys
// or the count and a stable, sorted list of managed key names.
func LoadPolicy() *Policy {
values, err := loadPlatformPolicy()
if err != nil {
@@ -260,7 +266,8 @@ func (p *Policy) GetStringSlice(key string) ([]string, bool) {
// sortedKeys returns the keys of m as a deterministic, lexicographically
// sorted slice. Used internally by Policy.ManagedKeys and LoadPolicy's
// diagnostic log line so callers see a stable key order across runs
// It produces a deterministic ordering for a map regardless of Go's randomized iteration.
// sortedKeys returns the keys of m as a lexicographically sorted slice.
// The sorted order provides a deterministic key ordering for diagnostics and enumeration.
func sortedKeys(m map[string]any) []string {
out := make([]string, 0, len(m))
for k := range m {

View File

@@ -41,7 +41,13 @@ const policyPlistPath = "/Library/Managed Preferences/io.netbird.client.plist"
//
// If the plist file does not exist, it returns (nil, nil). It returns a wrapped error on open/stat/decode failures.
// The function refuses to read a world-writable plist and returns an error in that case.
// Top-level plist keys are canonicalized (case-insensitive) to the internal MDM key names; unknown keys are logged and skipped.
// loadPlatformPolicy reads the device-level managed-preferences plist and returns its recognized keys.
//
// It looks for the plist at policyPlistPath and, if present, decodes it into a map[string]any.
// Top-level plist keys are canonicalized case-insensitively to the package's internal MDM key names;
// unknown keys are logged and ignored. If the plist file does not exist, it returns (nil, nil).
// The function refuses to read the file if it is world-writable and returns a wrapped error for
// failures to open, stat, or decode the plist.
func loadPlatformPolicy() (map[string]any, error) {
f, err := os.Open(policyPlistPath)
if err != nil {

View File

@@ -9,7 +9,9 @@ package mdm
// builds and returns (nil, nil) — the platform-absent sentinel that
// LoadPolicy in policy.go treats as "no MDM source present".
//
//nolint:nilnil // (nil, nil) is the documented platform-absent sentinel; see LoadPolicy.
// loadPlatformPolicy reports the absence of a platform-managed configuration on mobile builds.
// It returns a nil policy map and a nil error as a sentinel value; the real managed-config
// dictionary is read by the native iOS/Android layer and injected into the Go process.
func loadPlatformPolicy() (map[string]any, error) {
return nil, nil
}

View File

@@ -9,7 +9,8 @@ package mdm
// source present"; an error here would just translate to the same
// outcome with an extra log line.
//
//nolint:nilnil // (nil, nil) is the documented platform-absent sentinel; see LoadPolicy.
// loadPlatformPolicy indicates that no platform MDM policy is available on this build target.
// It intentionally returns (nil, nil) as the documented platform-absent sentinel so callers treat MDM as not present.
func loadPlatformPolicy() (map[string]any, error) {
return nil, nil
}

View File

@@ -35,7 +35,9 @@ const policyRegistryPath = `Software\Policies\NetBird`
// If the registry key does not exist it returns (nil, nil).
// It returns a map whose keys are canonical policy names and whose values are coerced from registry types:
// REG_SZ/REG_EXPAND_SZ -> string, REG_DWORD/REG_QWORD -> int64, REG_MULTI_SZ -> []string.
// Unknown value names, unsupported value types, and per-value read errors are skipped and logged; failures opening the key or enumerating values are returned as errors.
// readRegistryValue reads the registry value named by name from key k and, when the value is successfully read and its type is supported, stores the coerced Go value in out[canonical].
//
// REG_SZ and REG_EXPAND_SZ are stored as string, REG_DWORD and REG_QWORD are stored as int64, and REG_MULTI_SZ is stored as []string; unknown value names, unsupported value types, and per-value read errors are logged and skipped.
func readRegistryValue(k registry.Key, name, canonical string, out map[string]any) {
_, valType, err := k.GetValue(name, nil)
if err != nil {
@@ -69,6 +71,16 @@ func readRegistryValue(k registry.Key, name, canonical string, out map[string]an
}
}
// loadPlatformPolicy loads MDM-managed NetBird policy values from the Windows
// registry at HKLM\Software\Policies\NetBird.
//
// It returns a map that maps canonical policy names to coerced Go values:
// string for REG_SZ/REG_EXPAND_SZ, int64 for REG_DWORD/REG_QWORD, and []string
// for REG_MULTI_SZ. If the policy registry key does not exist, it returns
// (nil, nil). It returns an error when opening or enumerating the registry
// key fails. Individual values that are unknown, of unsupported types, or that
// fail to read are skipped and produce logged warnings; registry close failures
// are also logged.
func loadPlatformPolicy() (map[string]any, error) {
k, err := registry.OpenKey(registry.LOCAL_MACHINE, policyRegistryPath, registry.QUERY_VALUE)
if err != nil {

View File

@@ -26,7 +26,8 @@ const testReloadInterval = 1 * time.Second
// reloadInterval returns the production cadence, or the accelerated test
// cadence when running under `go test`. Centralising the choice here keeps
// reloadInterval selects the polling interval used to re-read the OS-native MDM policy.
// It returns testReloadInterval when tests are running (testing.Testing() == true) and defaultReloadInterval otherwise.
// reloadInterval selects the polling interval used for policy reloads.
// It returns testReloadInterval when running under `go test` (testing.Testing() == true), and defaultReloadInterval otherwise.
func reloadInterval() time.Duration {
if testing.Testing() {
return testReloadInterval
@@ -55,7 +56,11 @@ type Ticker struct {
// reloadInterval (production default, accelerated under `go test`); callers
// NewTicker creates a Ticker that polls the OS-native MDM policy at the package reload interval and invokes onChange when a policy change is detected.
// If onChange is nil the ticker will only log detected changes.
// The ticker's initial snapshot is populated by loading the current policy.
// NewTicker creates a Ticker that polls for policy changes and invokes onChange when a difference is detected.
//
// The provided onChange callback, if non-nil, is called with the previous and current Policy snapshots when a
// change is observed. The returned Ticker's polling interval is set via reloadInterval and its initial snapshot
// is populated by calling policyLoader.
func NewTicker(onChange func(prev, curr *Policy)) *Ticker {
return &Ticker{
interval: reloadInterval(),
@@ -94,7 +99,10 @@ func (t *Ticker) Run(ctx context.Context) {
}
// PoliciesEqual reports whether two Policy instances carry the same managed
// value maps for deep equality.
// PoliciesEqual reports whether two Policy instances represent the same policy.
// It returns true when both policies are empty, returns false if one pointer is nil
// while the other is not, and otherwise compares the policies' underlying value
// maps for deep equality.
func PoliciesEqual(a, b *Policy) bool {
if a.IsEmpty() && b.IsEmpty() {
return true
@@ -110,7 +118,7 @@ func PoliciesEqual(a, b *Policy) bool {
// The returned slices contain keys present only in `curr` (added), only in `prev` (removed),
// and present in both but whose values differ (changed). Each slice is sorted
// lexicographically for stable logging output; value differences are determined
// using deep equality.
// associated values differ by deep equality.
func diffPolicies(prev, curr *Policy) (added, removed, changed []string) {
prevKeys := mapOf(prev)
currKeys := mapOf(curr)
@@ -136,6 +144,8 @@ func diffPolicies(prev, curr *Policy) (added, removed, changed []string) {
// map of a Policy so callers outside this package can compare across the
// mapOf returns a non-nil copy of the given Policy's key/value map.
// If p is nil, mapOf returns an empty map; otherwise it returns a newly
// mapOf returns a non-nil copy of a Policy's values map.
// If p is nil it returns an empty map; otherwise it returns a newly
// allocated map containing the same key/value pairs as p.values.
func mapOf(p *Policy) map[string]any {
if p == nil {

View File

@@ -174,7 +174,9 @@ type conflictCheck struct {
// conflictBool builds a conflictCheck for a boolean MDM key.
// If p is nil the returned check treats the field as matching; otherwise the
// check returns true only when the policy contains the key and its boolean
// value equals *p.
// conflictBool constructs a conflictCheck that verifies a boolean MDM policy key matches a desired value.
// If p is nil the produced check treats the field as matching by definition. Otherwise the check returns
// true only if the policy has the key and its boolean value equals *p.
func conflictBool(key string, p *bool) conflictCheck {
return conflictCheck{
key: key,
@@ -191,7 +193,9 @@ func conflictBool(key string, p *bool) conflictCheck {
// conflictString builds a check for a string field. Empty string ("")
// conflictString returns a conflictCheck for the MDM string key identified by `key`.
// If `got` is empty the field is treated as unset and will not be considered a conflict.
// Otherwise the check succeeds only when the policy contains `key` and its value equals `got`.
// conflictString constructs a conflictCheck for a string policy key.
// The check treats an empty requested value as matching. Otherwise it
// succeeds only when the policy contains the key and its value equals got.
func conflictString(key, got string) conflictCheck {
return conflictCheck{
key: key,
@@ -206,7 +210,8 @@ func conflictString(key, got string) conflictCheck {
}
// conflictInt64 builds a conflictCheck that verifies an *int64 field against the MDM policy key.
// If p is nil the check always matches; otherwise the check requires the policy to contain the key and its integer value to equal *p.
// conflictInt64 builds a conflictCheck that validates an int64 MDM policy key.
// If p is nil, the check always matches; otherwise the policy must contain the key and its integer value must equal *p.
func conflictInt64(key string, p *int64) conflictCheck {
return conflictCheck{
key: key,
@@ -226,7 +231,9 @@ func conflictInt64(key string, p *int64) conflictCheck {
// skipped silently (the gate fires only for keys the admin has actually
// resolveConflicts identifies MDM-managed policy keys whose values differ from the provided checks.
// If the policy is empty, it returns nil. Only keys present in the policy are considered; for each
// check whose predicate returns false the corresponding key is included in the returned slice.
// resolveConflicts evaluates each conflictCheck against the provided MDM policy and returns
// a slice of policy keys whose checks report a mismatch. If the policy is empty, it returns nil.
// Checks whose key is not present in the policy are skipped.
func resolveConflicts(policy *mdm.Policy, checks []conflictCheck) []string {
if policy.IsEmpty() {
return nil
@@ -258,7 +265,11 @@ func resolveConflicts(policy *mdm.Policy, checks []conflictCheck) []string {
// If msg is nil, it returns nil. The function treats the PSK redaction sentinel
// ("**********") as an intentional no-op (equivalent to field not set). Only keys
// present in the supplied policy are considered; returned slice contains the policy
// key names that conflict with the values in msg.
// mdmManagedFieldConflicts reports MDM-managed policy keys that would conflict with a SetConfigRequest.
//
// If msg is nil, it returns nil. The pre-shared key redaction sentinel ("**********") is treated as unset
// so it does not produce a false conflict. The returned slice contains policy key names whose values in
// the request differ from the active policy; an empty or nil slice indicates no conflicts.
func mdmManagedFieldConflicts(msg *proto.SetConfigRequest, policy *mdm.Policy) []string {
if msg == nil {
return nil
@@ -297,7 +308,10 @@ func mdmManagedFieldConflicts(msg *proto.SetConfigRequest, policy *mdm.Policy) [
// field is present (for example: management/admin URLs, pre-shared key, DNS/NAT lists and
// cleaning flags, interface/port/MTU settings, auto-connect and routing toggles, DNS/firewall/IPv6
// controls, SSH-related flags, notification/lazy-connection options, or other persistent config
// toggles).
// setConfigRequestHasConfigOverrides reports whether msg contains any fields that would modify persisted daemon configuration.
// It returns false for a nil message. The check includes management/admin URLs, pre-shared key, DNS/NAT lists and cleanup flags,
// interface and WireGuard settings, MTU, auto-connect, routing, DNS/firewall/IPv6 controls, SSH-related flags, notification and
// lazy-connection options, and other persistent network/security fields.
func setConfigRequestHasConfigOverrides(msg *proto.SetConfigRequest) bool {
if msg == nil {
return false
@@ -343,7 +357,8 @@ func setConfigRequestHasConfigOverrides(msg *proto.SetConfigRequest) bool {
// loginRequestHasConfigOverrides reports whether a LoginRequest includes any fields that would change persisted daemon configuration.
// It returns true when the request carries any configuration-related values (for example: management/admin URLs, pre-shared key,
// DNS or NAT lists/cleanup flags, interface or WireGuard port, connection and policy toggles, route/DNS/firewall/notification flags,
// Rosenpass settings, lazy-connection or block-inbound), and false when the request is nil or contains only authentication/identity fields.
// loginRequestHasConfigOverrides reports whether the given LoginRequest contains any fields that would modify the daemon's persisted configuration.
// It returns true when the request sets any configuration-related fields (management/admin URLs, pre-shared key, DNS/NAT settings, Rosenpass options, interface/WireGuard settings, auto-connect, routing/SSH/firewall/DNS controls, notifications, lazy-connection, block-inbound, or similar persistent toggles); it returns false if msg is nil or contains only authentication/identity fields.
func loginRequestHasConfigOverrides(msg *proto.LoginRequest) bool {
if msg == nil {
return false
@@ -385,7 +400,13 @@ func loginRequestHasConfigOverrides(msg *proto.LoginRequest) bool {
// It returns a slice of policy keys that are managed by the given policy and whose values in the request
// differ from the policy. If msg is nil or the policy has no managed keys, it returns nil. The function
// prefers OptionalPreSharedKey over the legacy PreSharedKey when both are present and treats the redaction
// sentinel "**********" as an absent pre-shared key.
// loginRequestMDMConflicts reports MDM-managed configuration keys that would
// conflict between a LoginRequest and the active MDM policy.
//
// It returns a slice of policy key names whose requested values differ from the
// policy. If msg is nil it returns nil. For pre-shared keys, OptionalPreSharedKey
// takes precedence over the deprecated PreSharedKey; a value equal to
// preSharedKeyRedactedSentinel ("**********") is treated as unset.
func loginRequestMDMConflicts(msg *proto.LoginRequest, policy *mdm.Policy) []string {
if msg == nil {
return nil
@@ -427,7 +448,19 @@ func loginRequestMDMConflicts(msg *proto.LoginRequest, policy *mdm.Policy) []str
// rejectMDMManagedFieldConflicts returns a gRPC FailedPrecondition error when any MDM-managed fields conflict.
// If `conflicts` is empty this function returns nil. When conflicts exist it produces a FailedPrecondition status
// whose message lists the conflicting fields and attempts to attach a `proto.MDMManagedFieldsViolation` detail;
// if attaching details fails the base status error is returned. A warning is logged listing the rejected keys.
// rejectMDMManagedFieldConflicts rejects requests that attempt to modify fields managed by MDM.
// If `conflicts` is empty, it does nothing. Otherwise it logs a warning and returns a gRPC
// FailedPrecondition error whose message lists the conflicting keys and which carries a
// `proto.MDMManagedFieldsViolation` detail with the `Fields` set to `conflicts`. If attaching
// the detail fails, the base FailedPrecondition status is returned.
//
// Parameters:
// - policy: the active MDM policy (unused here, present for call-site symmetry).
// - conflicts: list of MDM-managed keys that the request attempted to modify.
//
// Returns:
// - a gRPC error indicating the request was rejected due to MDM-managed fields, or nil when
// there are no conflicts.
func rejectMDMManagedFieldConflicts(policy *mdm.Policy, conflicts []string) error {
if len(conflicts) == 0 {
return nil

View File

@@ -363,7 +363,16 @@ func (s *Server) SetConfig(callerCtx context.Context, msg *proto.SetConfigReques
// fields (DNS labels, NAT external IPs). Extracted from SetConfig to
// keep the handler's cognitive complexity below the SonarCube
// threshold; the body of this function is intentionally linear and
// branchy because each proto field is its own optional case.
// setConfigInputFromRequest builds a profilemanager.ConfigInput from a SetConfigRequest proto.
//
// It translates each provided proto field into the corresponding ConfigInput field,
// preserving the request's semantics for "clean" vs explicit-empty slices/bytes and
// converting optional numeric fields into typed pointers where applicable.
//
// msg: the incoming SetConfigRequest whose fields are mapped into the returned ConfigInput.
//
// Returns the constructed ConfigInput and a non-nil error if the active profile file path
// cannot be determined.
func setConfigInputFromRequest(msg *proto.SetConfigRequest) (profilemanager.ConfigInput, error) {
var config profilemanager.ConfigInput

View File

@@ -70,7 +70,9 @@ const (
// It parses CLI flags, initializes logging, creates the Fyne application and tray icons,
// and constructs the service client (which may open a requested UI window). If a window-mode
// flag is set the Fyne event loop runs and main returns; otherwise it ensures only one
// instance is running, sets up signal handling and fonts, and starts the system tray loop.
// main is the program entry point that initializes logging and the Fyne UI, enforces single-instance behavior, creates the service client, and starts the system tray.
//
// It parses CLI flags, configures logging, constructs the Fyne application and service client (optionally showing a requested UI window), monitors theme/settings changes, ensures only a single instance runs (signaling an existing instance to show its window when present), sets up signal handling and default fonts, and finally runs the system tray loop.
func main() {
flags := parseFlags()
@@ -1698,7 +1700,8 @@ func (s *serviceClient) applyMDMLocks(managed []string) {
// Entry's placeholder slot. The placeholder is the only signal the user
// gets that a PSK is configured, because the entry's Text is forced to
// empty to keep the password reveal toggle from leaking the
// It returns an empty string if no pre-shared key is present; returns "MDM-managed" if the pre-shared key is enforced by MDM; otherwise returns "configured".
// preSharedKeyPlaceholder returns the placeholder text for the pre-shared key entry based on the daemon config.
// It returns an empty string if no pre-shared key is present, `MDM-managed` if the key is enforced by MDM, and `configured` otherwise.
func preSharedKeyPlaceholder(cfg *proto.GetConfigResponse) string {
if cfg == nil || cfg.PreSharedKey == "" {
return ""

View File

@@ -75,7 +75,7 @@ readonly PLIST_DIR='/Library/Managed Preferences'
readonly PLIST_PATH="$PLIST_DIR/io.netbird.client.plist"
readonly LOG_TAG='netbird-mdm'
# log sends a message to the system logger with the configured tag and echoes the message to stdout prefixed by an ISO 8601 UTC timestamp and the tag.
# log sends a message to the system logger using the configured tag and echoes the message to stdout prefixed by an ISO 8601 UTC timestamp and the tag.
log() {
/usr/bin/logger -t "$LOG_TAG" "$*"
printf '%s [%s] %s\n' "$(date -u '+%Y-%m-%dT%H:%M:%SZ')" "$LOG_TAG" "$*"
@@ -105,7 +105,7 @@ end_plist() {
EOF
}
# emit_string appends a plist `<key>/<string>` entry for a given key and value to "$PLIST_PATH.tmp", XML-escaping `&`, `<`, and `>` and logging the assignment; if the key is "preSharedKey" the logged value is masked.
# emit_string appends a plist `<key>`/`<string>` entry for the given key and value to "$PLIST_PATH.tmp", XML-escaping `&`, `<`, and `>`, and logs the assignment (masking the logged value as `********** (secret)` when the key is `preSharedKey`).
emit_string() {
local key="$1" value="$2" log_value="$2"
# Escape XML entities in the value
@@ -119,7 +119,7 @@ emit_string() {
}
# emit_bool writes a boolean plist entry for a given key into the temporary plist file.
# emit_bool accepts `true/True/TRUE/1/yes` as true and `false/False/FALSE/0/no` as false; on invalid input it logs an error and skips emitting the key.
# emit_bool writes a boolean plist entry for a key when the provided value matches an accepted boolean token; logs an error and skips the key on invalid input.
emit_bool() {
local key="$1" value="$2"
local xml_bool