A policy that enforces a management URL refuses any SetConfig or Login whose
URL differs from it. The comparison normalized only the default port, so
three ways of writing the very endpoint the policy names were reported as
conflicts:
policy https://mgmt.example.com vs https://mgmt.example.com/ refused
https://MGMT.example.com refused
https://mgmt.example.com:0443 refused
For an MDM-managed deployment whose stored or command-line URL is spelled
differently from the policy's value, that means every settings update is
refused with an MDMManagedFieldsViolation naming a field the caller did not
change. `netbird up --management-url https://MGMT.example.com` reproduces it.
The rules now live in util.SameServiceURL, and ConflictURL delegates: scheme
and host compared case-insensitively, the effective port normalized
numerically, a trailing slash ignored, and a path otherwise still part of the
identity so /other remains a divergence. Unparseable input falls back to
string equality.
util rather than either caller, because comparing two service URLs is
neither device management nor profile storage, and more than one place does
it: an MDM-enforced management URL against a requested one here, a stored
profile URL against a command-line one in profilemanager and the SSH gate.
Every copy of these rules that drifts turns an equivalent URL into a refused
request, which is how this one arose.
CanonicalURL is left alone: besides comparison it is the canonical value
handed to mdm.Restrictions and to the Android and iOS Preferences getters,
and normalizing what those return is a separate decision.
encoding/json decodes every JSON number into float64, so the policy
values the mobile loaders produce never contain int or int64. GetBool
accepted both of those but not float64, so a managed boolean pushed as
1 or 0 — how some MDM consoles normalise flags — was reported as
unreadable while the key still counted as managed: the policy was not
applied, and the conflict gate rejected both values the user could pick
for that field.
The rejected-float assertion predates the JSON channel. It came with the
registry and plist loaders, where a real number for a flag is a
configuration mistake; on the JSON channel an integer is the only shape
a number can take. GetInt already accepts float64.
* MDM Android mobile wiring
* Removes dead code
* Removes static vars
* Now we need to apply MDM in the GetConfig
* You now need to explicitly call these around
* Adds iOS wiring
* Resolve merge conflicts from main
- login.go: keep both new imports (mdm + nbnet + server)
- ios/NetBirdSDK/client.go: additive struct-field merge (mdmLoader + stateMu/connectClient/config)
- setconfig_mdm_test.go: adopt new withMDMPolicy(t, s, policy) signature; fix stray old-signature call in TestSetConfig_MDMAllow_ManagementURLPortNormalized
* Convey MDM overlay config to Debug Bundle output
Aligns to other clients OSes behavior
* Solved conflict in client.go
* Fixup helper withMDMPolicy -> configWithMDM
* Fixup after merge
* Resolve merge conflicts
* [client] Move MDM enforcement logic into a shared Go layer (#7319)
The mobile bridges only carried the policy fetcher, leaving every
enforcement decision to the native apps: the desktop derived its UI
restrictions in the Wails service layer, the daemon kept the conflict
machinery in the server package, and both mobile bridges duplicated the
JSON fetch adapter. Anything the native side had to reimplement was a
place for iOS and Android to drift apart.
Enforcement now lives in client/mdm and is consumed identically by all
three platforms:
- conflicts.go holds the value-aware conflict checks lifted out of the
daemon, so the same normalization (canonical URLs, PSK sentinel echo)
applies wherever a config change is validated.
- restrictions.go derives the UI enforcement snapshot from a policy and
renders it in the JSON shape the desktop frontend already consumes.
The service-layer types become aliases, keeping one source of truth.
- jsonloader.go replaces the adapter that was copy-pasted into both
bridges.
- changedetector.go moves change detection off the native side: the
caller forwards the OS notification and asks whether the managed
configuration actually changed, instead of diffing dictionaries
itself.
The mobile bridges gain the enforcement the daemon already had. The
Preferences getters resolve managed keys from the policy, so a naive UI
shows the enforced value; Commit rejects a staged change that diverges
from a managed key; NewAuth resolves the managed management URL before
persisting the config and overlays the policy on it, so a login can no
longer run against a URL the policy forbids. Android's profile
mutations fail closed when disableProfiles is set.
NewAuth takes the fetcher as a required argument rather than keeping a
policy-blind overload: the apps consume this code as a submodule, so a
compile error at the bump is the point. The mobile PSK getter is
replaced by a presence check — the key has no reason to cross the
bridge, and not returning it means the native side needs no redaction
sentinel of its own.
* [client] Resolve the main merge conflicts in the MDM integration
The merge commit was recorded with the conflict markers still in the
tree. Resolve them so the branch builds again:
- client/ios/NetBirdSDK: keep both the mdm and mobile imports, and keep
the mdmLoader/mdmDetector fields next to main's stateMu documentation.
- client/server/mdm.go: drop the conflict helpers main added locally,
they already live in the client/mdm package on this branch, and keep
the new checks main introduced (allowRemoteJobs, enableLocalMetrics,
localMetricsAddress) as calls into the package-level helpers.
- client/mdm/conflicts.go: add ConflictStringPtr, the presence-aware
string check main needs for the optional localMetricsAddress field.
- Port the two tests main added over the per-Server loader helper and the
configWithMDM helper, both of which replaced the package-level policy
injection this branch removed.
* [client] Reject explicit empty PSK when MDM enforces a pre-shared key
The SetConfig, Login and mobile Commit conflict checks collapsed the PSK
to a plain string, so an explicit empty value was indistinguishable from
an unset field and slipped past the MDM gate, clearing the persisted key.
Carry the optional field as a pointer through ConflictStringPtr, treating
only the redaction sentinel as a no-op echo. ConflictString had no other
callers and is removed.
* [client] Apply MDM overlay on the preloaded iOS config in Run
Run only overlaid the MDM policy when the config was loaded from file,
so the tvOS path fed by SetConfigFromJSON started with unmanaged
settings. Apply the overlay after the config source is selected, as the
other resolution sites already do.
* [client] Gate non-active profile logout behind the MDM profiles switch
The mobile ProfileManager let LogoutProfile clear credentials of any
profile even when disableProfiles was enforced. Follow the daemon's
validateProfileLogout semantics: logging out of the active profile is a
plain logout and stays allowed, logging out of any other profile is
profile management and is rejected under the policy.
* [client] Resolve the managed management URL through the MDM overlay on mobile
NewAuth on Android and iOS replaced the caller URL with the raw policy
value before persisting, so a malformed managed URL failed config
validation and blocked the login instead of being skipped with a warning
like the overlay does. Preferences.GetManagementURL likewise echoed the
raw policy string to the native UI even when the overlay had rejected it.
Follow the daemon: persist the caller URL, overlay the policy on the
resolved config, and report the overlaid ManagementURL as the effective
value.
* [client] Clean up MDM review leftovers
Drop the unused ChangeDetector.Current, point the stale LoadPolicy
comment references at Loader.Load, and move the profileEmail godoc back
above its function.
* [client] Check remote jobs and local metrics keys in the mobile MDM conflict gate
MDMConflicts skipped allowRemoteJobs, enableLocalMetrics and
localMetricsAddress even though the overlay applies all three and the
daemon gate already checks them, so a mobile Commit could persist values
diverging from the enforced policy. Align the list with the daemon.
* [client] Silence the deprecated PreSharedKey lint in the login conflict test
The legacy LoginRequest.PreSharedKey field is deliberately exercised by
the test, matching the nolint already carried by the production path.
* [client] Publish the mobile MDM loader and detector atomically
SetMDMPolicyFetcher wrote the loader and change detector as two plain
fields that Run, the OS-change callback and the restrictions getter read
from other threads without synchronization. Hold both behind a single
atomic pointer so a registration is published as one unit and readers
always observe a matching loader and detector pair; Preferences gets the
same treatment for its loader. Exported signatures are unchanged.
* [client] Report the MDM-overlaid remote jobs value from mobile Preferences
GetRemoteJobsAllowed returned the staged or persisted value even when
the policy manages allowRemoteJobs, so the native settings UI could show
a value the Commit gate would reject. Resolve it through the overlay like
GetManagementURL does.
* [client] Stop persisting the MDM-overlaid config after mobile logins
NewAuth already writes the config through UpdateOrCreateConfig before
the MDM policy is overlaid, and the login itself never mutates the
Config. The post-login WriteOutConfig calls therefore only rewrote the
same file with the enforced ManagementURL and PreSharedKey in it, so a
removed or changed policy kept acting through the persisted values.
* [client] Document that the MDM overlay on Config is not reversible
ApplyMDMPolicy promised that an empty Policy clears a prior overlay, but
applyMDMPolicy only resets the enforcement metadata and the runtime-only
upload URL; the enforced ManagementURL, PreSharedKey and flags stay. Every
lifecycle owner resolves the base Config again before applying, so state
that contract instead of the reversibility that was never implemented.
* [client] Re-resolve the tvOS preloaded config before every MDM overlay
The iOS Client kept the config parsed from SetConfigFromJSON and applied
the MDM overlay onto that same instance on every Run, IsLoginRequired
and DebugBundle, so a key removed from the policy stayed enforced. Store
the JSON instead and parse it per load through one loadConfig path.
Auth serialized the overlaid config from GetConfigJSON, which tvOS then
persisted to UserDefaults and fed back as the preload. Keep the resolved
config as the base, run the login on a JSON round-trip copy with the
overlay, and return the base from GetConfigJSON.
* [client] Serve the MDM-managed management URL without touching the config file on mobile
Preferences.GetManagementURL resolved a managed URL by reading and
overlaying the persisted config, so a corrupt file or the tvOS sandbox
turned an enforced URL into a read error. Return the canonical managed
value directly, the same string BuildRestrictions already hands to the
UI, and only fall back to the staged or persisted value when MDM does
not manage the key.
NewAuth validated the caller-supplied management URL before the overlay
ran, so a malformed or echoed value blocked or persisted under an MDM
policy that already dictates the URL. Ignore the caller value while the
key is managed; the login runs against the overlay either way.
* [client] Align the MDM loader docs with the fetcher precedence and make disableAdvancedView a tristate
NewLoader, PolicyFetcher and the darwin/windows loadPlatform docs claimed
the fetcher is unused on desktop, while every loader returns its values
when one is injected. That precedence is the seam the server tests rely
on across platforms, so the docs now describe it; production desktop
callers still pass nil and keep the registry / plist authoritative.
Fields.DisableAdvancedView collapsed "managed and false" into the same
JSON as "not managed", unlike AllowServerSSH and the daemon's optional
proto field. Carry it as a *bool so the UIs can tell the two apart; the
desktop reflect loop skips pointer fields already, and the mobile
decoders treat null as not managed.
* [client] Clean up MDM review nits
- ResolveConflicts treats a managed key whose ConflictCheck has no Check
as a conflict instead of dereferencing nil.
- Ticker.Run and ChangeDetector.Changed share policyChanged so the diff
semantics and the log line cannot drift apart.
- TestLoader_NilFetcherReturnsEmpty skips on windows/darwin, where a nil
fetcher reads the real registry / plist.
- The profilemanager test loader checks GetInt before GetBool so integer
keys survive the round trip, and the PSK tests use the exported
redaction sentinel.
* [client] Fix int policy values coercing to bool in the MDM test helper
withMDMPolicy rebuilt the policy map by trying GetString, then GetBool,
then GetInt. Policy.GetBool accepts native ints (non-zero means true), so
an int-valued key such as wireguardPort round-tripped through the helper as
the bool true and GetInt was never reached. Try GetInt before GetBool, as
the profilemanager helper already does; GetInt does not coerce bools, so
booleans still fall through to GetBool.
No test sets an int key today, so this was latent: the first test to
exercise the wireguardPort conflict gate would have seen ConflictInt64
report a conflict for every value, including a matching one.
---------
Co-authored-by: Zoltan Papp <zoltan.pmail@gmail.com>
* [client] Return the context error when the SSH handshake fails on a context deadline
The handshake mapped the context deadline onto the socket but returned the
raw socket error. Which error surfaces depends on a race between the x/crypto
ssh readLoop and kexLoop goroutines: the kexLoop write fails with i/o timeout
and closes the conn, and the readLoop then reports use of closed network
connection. Callers checking errors.Is(err, context.DeadlineExceeded) never
matched, and TestSSHClient_ContextCancellation flaked on the FreeBSD job.
Handshake now wraps the context error when the context is done or its
deadline has passed. The deadline comparison is needed because the socket
deadline and the context timer fire independently, so ctx.Err() can still be
nil when the deadline-triggered socket error arrives.
* [client] Close the silent test server conn without racing t.Cleanup
The accept goroutine registered the conn close via t.Cleanup, which can run
after the test's cleanup list has already been drained, leaving the accepted
connection open. The goroutine now holds the conn until a cleanup-closed
channel signals the end of the test and closes it on the way out.
* [client] Bind the SSH handshake to the context instead of a socket deadline
Mapping only the context deadline onto the socket left context cancellation
unobserved: an in-flight handshake kept running until the deadline, and the
error classification had to guess whether a raw socket error was caused by
the deadline. Closing the conn from context.AfterFunc covers both deadline
and cancellation, and ctx.Err() is already set by the time the close-induced
error surfaces, so the time-based DeadlineExceeded attribution is no longer
needed. The stop() result guards the window between a successful handshake
and the AfterFunc firing so a closed conn is never handed back as a client.
Defines the cloud-side managed gateway provisioning surface
(POST/GET /api/integrations/agent-network/managed-proxy) and its
response objects so clients consume generated types instead of
hand-written ones. POST is idempotent: 202 when the call starts (or
restarts) provisioning, 200 when a deployment already exists; 409
names an already-assigned endpoint the managed flow does not own and
503 signals temporarily exhausted endpoint allocation.
Android 16+ local network protection derives the blocked prefixes from the interface address prefix. A /16 address turns the whole overlay into a local network, so apps without ACCESS_LOCAL_NETWORK cannot reach any peer. Pass the address as /32 and /128 and add the overlay networks to the route list that the Android side turns into VPN routes, on both the initial create and the renew path.
* Gather fresh system info on every management sync stream connect
The engine collected the peer meta once at start and reused the same
Info for every Sync stream reconnect, so a mobile network switch that
redials management kept reporting the old local network addresses.
The peer network range posture check was then evaluated against stale
data until the client restarted.
Sync now takes a gatherer that runs at each stream connect. The
gatherer is cheap: GetInfo plus the cached posture check file results,
kept in the new system.InfoSource, which the engine refreshes whenever
the checks list changes. No process enumeration runs on the reconnect
path.
Also fix the management mock server calling itself instead of SyncFunc.
* Evaluate the login response posture checks before the first sync connect
The engine starts with the checks the login response carried, and the
first sync stream request used to send their evaluated file results.
After moving the gather into InfoSource, the stream opened with an empty
cache and the first sync response did not refill it, because its checks
equal the ones the engine already holds. Desktop peers therefore never
reported process or file posture results.
Seed the cache once before the first connect, where the old gather ran,
so a timed out evaluation still falls through to the address-only info.
* Harden the sync info source against nil callbacks and shared slices
A nil getInfo opens the stream without metadata, as a nil sysInfo did
before. The cached posture results are a copy, so the Info returned by
Refresh cannot alias the snapshot later Current calls report. The
exclusion test asserts the remaining address count so it cannot pass
vacuously on a single-address host.
* Retry a posture check refresh that timed out or failed to sync
The checks list was recorded before the gather ran, so once the gather
timed out or SyncMeta failed, the next sync response carrying the same
list matched the recorded one and nothing retried. The peer kept
reporting the previous posture results until the list changed again.
Record the checks only after the meta reached management, so a failed
cycle is repeated on the next sync response.
* Log the skipped posture refresh, let the mock Sync return errors and deflake the reconnect test
* Drop the nil guard around the sync info callback
* Send the refreshed info on the first sync connect instead of gathering it twice
The SQLite network-map query expanded a router's groups with from network_routers, json_each(peer_groups). That comma is an inner join, so a router row survives only when json_each returns at least one row. A router targeting an individual peer carries no groups — the write path stores NULL for a nil slice and '[]' for an empty one — and json_each yields nothing for either, so the join erased the router before it could be keyed by its peer. Postgres reads the same rows through a correlated subquery and was never affected.
The fix expands the groups with a left join, so the router survives with a NULL group_peers.peer_id and the existing scan loop keys it by router.Peer. Group routers still fan out one row per member.
A push that creates a branch sends the all-zero SHA as `before`, and
bufbuild/buf-action unconditionally builds its default baseline from
it:(src/inputs.ts:86), so `buf breaking` failed cloning a ref that does
not exist. This broke the first run on every new release-* branch, most
recently release-0.78.
Gate `breaking` on github.event.created instead. Nothing is lost: every
commit on a freshly cut release branch already passed the check on main,
and pushes with a real `before` -- plus pull requests, which compare
against their own base -- keep the action's own default baseline, so
stacked PRs are unaffected.
Also drop `build: false`, which is not an input this action accepts and
only produced a warning.
Remote jobs (debug bundle requests from management) are gated behind
Config.RemoteJobsAllowed, which defaults to false and could only be
enabled through the CLI flag or an MDM policy. The mobile SDKs had no
way to set it, so the mobile clients always refused the job.
Add GetRemoteJobsAllowed/SetRemoteJobsAllowed to both mobile
Preferences types, following the existing ServerSSHAllowed accessors,
so the apps can offer a settings toggle for it.