Commit Graph
2050 Commits
Author SHA1 Message Date
Kabir Sikand 78e1e4a4e9 ipn/ipnlocal: move BlueprintConfig copy out of peerStatusFromNode
peerStatusFromNode is shared by both the Self-status path and the
peer iteration in populatePeerStatusLocked, so the BlueprintConfig
copy added in the prior commit was leaking onto peer PeerStatus
entries whenever the server included BlueprintConfig in a peer's
Node record. The ipnstate.PeerStatus.BlueprintConfig docstring and
the v2 design both promise nil on peer entries.

Move the copy into MutateSelfStatus, alongside the other Self-only
fields. BlueprintID stays in the shared helper since both Self and
peers legitimately surface it (the status subcommand filters peers
by it).

Adds TestPeerStatusFromNodeDoesNotCopyBlueprintConfig to lock in
the invariant.

Updates #cleanup

Signed-off-by: Kabir Sikand <[email protected]>
2026-05-27 20:20:29 +00:00
Kabir Sikand f2b02df99e cmd/tailscale/cli, ipn/ipnstate: add blueprint projection wait helper
Adds a pure waitForBlueprintProjection helper that polls a Status
fetcher until the daemon reports a matching projection or a deadline
elapses. Extracted from runJoin so the wait-loop behavior can be unit
tested without a fake LocalClient.

Also threads PeerStatus.BlueprintConfig (populated only on Self, from
tailcfg.Node.BlueprintConfig) so the helper's success condition can
be expressed in terms of the public Status surface. Peer entries
never read this field; the helper checks only Status.Self.

Updates #cleanup

Signed-off-by: Kabir Sikand <[email protected]>
2026-05-27 19:54:07 +00:00
Kabir Sikand 42600800a1 ipn/ipnlocal: copy Node.BlueprintID into PeerStatus.BlueprintID
peerStatusFromNode is the centralized helper that copies fields from
tailcfg.NodeView into ipnstate.PeerStatus for both the local node
(via MutateSelfStatus) and every peer (via populatePeerStatusLocked).
A one-line copy populates the new PeerStatus.BlueprintID field added
in the previous commit, making blueprint bindings visible everywhere
the status surface is read.

Updates #cleanup

Signed-off-by: Kabir Sikand <[email protected]>
2026-05-27 19:45:22 +00:00
Kabir Sikand 846765cb85 ipn/ipnstate: add PeerStatus.BlueprintID
Adds a BlueprintID field to PeerStatus and extends StatusBuilder.AddPeer
to merge it using the same "non-empty wins" pattern as every other
string field on the struct. The field is populated upstream (see the
peerStatusFromNode helper in ipn/ipnlocal/local.go) from
tailcfg.Node.BlueprintID, which is already on the wire as of capver
139, and is consumed by the `tailscale join status` subcommand to
filter peers by their blueprint binding.

Updates #cleanup

Signed-off-by: Kabir Sikand <[email protected]>
2026-05-27 19:41:55 +00:00
Kabir Sikand 4cd8636d63 tailcfg, ipn/ipnlocal: wire blueprint serves.apps + serves.services
Closes the corp-side dangling wire fields (corp v2.1 ships
ServeApps/ServeServices in BlueprintConfig but the OSS client
never read them). Adds the missing OSS-side type field plus a
reconciler that maps the resolved blueprint's app + service list
onto local daemon state.

tailcfg.BlueprintConfig gains ServeServices []string (companion
to the existing ServeApps + ServeIPSets). Equal() updated; clone
+ view hand-edits follow the existing pattern (prior agent noted
the corp pin makes go generate awkward, so the cloner/viewer
files are hand-extended with regen sentinels updated).

ipn/ipnlocal/local.go: two new reconcile functions, called from
the tail of setNetMapLocked alongside the existing routes / prefs
reconciles:

  - reconcileBlueprintAppConnectorLocked: flips
    Prefs.AppConnector.Advertise to match presence of any "app:"
    identifier in BlueprintConfig.ServeApps. Silence-equals-OFF
    consistent with the other blueprint prefs. Per-app routing
    rules (which domains/CIDRs each connector handles) remain
    owned by the existing app-connector machinery; the blueprint
    only toggles the node-level advertise bit.

  - reconcileBlueprintServicesLocked: surfaces the projected
    ServeServices list via the daemon log so operators can see
    what services the blueprint expects this node to advertise.
    Full reconcile into the daemon's services machinery is a
    follow-up — translating "svc:<name>" identifiers into actual
    ServeConfig entries depends on the services backend exposing
    a reconcile API, which is out of scope for this commit.

Operationally: after this commit, a blueprint that lists
"serves.apps": ["app:github"] auto-enables the bound node as an
app connector (no need for the operator to also run
`tailscale set --advertise-connector` and have it rejected by the
blueprint-lock); the per-app routing rules still come from the
operator's app-connector configuration in the admin panel.

Updates #cleanup

Signed-off-by: Kabir Sikand <[email protected]>
2026-05-19 22:38:42 +00:00
Kabir Sikand a86a228350 ipn/ipnlocal: drop shields-up + webclient from blueprint prefs allowlist
Brings the client-side blueprint pref projection to spec v2. The v1
table had five entries (accept-dns, accept-routes, ssh, shields-up,
webclient); the latest spec (§6 in-scope #10, §13) lists four
(accept-dns, accept-routes, ssh, funnel). The v1.1-era shields-up and
webclient were retracted; pref:funnel is added in concept but has no
ipn.Prefs boolean to project onto — funnel eligibility today flows
through tailcfg.NodeAttrFunnel via the existing nodecap path, not
through ipn.Prefs.

For the client reconciler that means three rows:

  pref:accept-dns    -> Prefs.CorpDNS
  pref:accept-routes -> Prefs.RouteAll
  pref:ssh           -> Prefs.RunSSH

pref:funnel falls through as an "unknown pref" on the projection side;
the compile-time allowlist in corp still accepts it. The gap is
documented in BLUEPRINTS-FOLLOWUPS.md so a future change adding a
first-class Prefs.FunnelEligible bool can plug the table cleanly.

Tests:

  - TestReconcileBlueprintPrefs_PresenceIsOnAbsenceIsOff loses its
    ShieldsUp/RunWebClient columns and gains funnel + v1-legacy
    coverage rows.
  - New TestReconcileBlueprintPrefs_LegacyPrefsLeaveLocalFieldsAlone
    pins the distinguishing behavior: pref:shields-up and
    pref:webclient must not flip the corresponding bool either way
    (no silence-forces-OFF, no presence-forces-ON), even if a
    blueprint still lists them. That catches a regression where
    someone re-adds the v1 setters by accident.

Updates #cleanup

Signed-off-by: Kabir Sikand <[email protected]>
2026-05-19 15:34:07 +00:00
Kabir Sikand c3721ba263 tailcfg, ipn/ipnlocal, cmd/tailscale/cli: drive node prefs from blueprint
Paired OSS side for the corp v1.1 "blueprint prefs" work. Three
changes:

  1. tailcfg.BlueprintConfig grows a Prefs []string field. The wire
     format intentionally uses strings rather than a typed bool
     struct so the control plane can add new supported prefs
     without a capver bump on the client; unrecognized entries are
     ignored by older clients. Clone, view, and Equal hand-edited
     to keep the regen sentinels green (corp pin makes go generate
     awkward; follows the prior commits' pattern).

  2. ipn/ipnlocal grows reconcileBlueprintPrefsLocked, called from
     setNetMapLocked right after the existing routes reconcile.
     For each entry in a small per-pref table (id, getter, setter,
     metric) the loop forces the matching ipn.Prefs bool to true
     when the pref appears in BlueprintConfig.Prefs and to false
     when it does not. Silence equals OFF: the blueprint is the
     source of truth and overrides any pre-existing local setting
     on every netmap apply. Persists only when something actually
     flipped. One clientmetric counter per pref bumps each time
     the reconcile turns the field ON.

     Supported prefs in this revision:

       pref:accept-dns    -> Prefs.CorpDNS
       pref:accept-routes -> Prefs.RouteAll
       pref:ssh           -> Prefs.RunSSH
       pref:shields-up    -> Prefs.ShieldsUp
       pref:webclient     -> Prefs.RunWebClient

     Unknown pref ids in the projection are ignored silently
     (forward-compat: a newer control plane may reference a pref
     this client does not yet implement).

  3. cmd/tailscale/cli/blueprint_lock.go extends the locked-field
     list to reject `tailscale set --accept-routes`,
     `--shields-up`, and `--webclient` on blueprint-bound nodes
     with the same v1 error template. --accept-dns and --ssh were
     already locked.

Tests added:

  - ipn/ipnlocal/blueprint_prefs_test.go exercises the reconcile
    function across the matrix of all-on, partial, silence-equals-off
    (overrides prior local), unknown-pref-ignored, and the no-op
    paths for unbound nodes and nil netmaps.
  - cmd/tailscale/cli/blueprint_lock_test.go gains rows for each
    new locked field.

Updates #cleanup

Signed-off-by: Kabir Sikand <[email protected]>
2026-05-19 00:10:42 +00:00
Kabir Sikand 6d016c0c33 ipn/ipnlocal: reconcile blueprint routes into AdvertiseRoutes
When the netmap's SelfNode carries a BlueprintConfig with non-empty
Routes, treat those routes as the source of truth for the local
Prefs.AdvertiseRoutes. tailscale set --advertise-routes is already
rejected for blueprint-bound nodes (see
cmd/tailscale/cli/blueprint_lock.go) so the prefs slot is
effectively under the blueprint's control; rewriting it from the
netmap is the right thing to do.

Reconciliation runs at the tail of setNetMapLocked. When it spots
a delta, it persists the new prefs via b.pm.SetPrefs, refreshes
b.hostinfo through the existing applyPrefsToHostinfoLocked path,
and pushes the new Hostinfo to controlclient via
doSetHostinfoFilterServices. The result is that the admin
Machines page sees the freshly-advertised subnets within one
map-poll of an ACL save touching the blueprint's serves.ipsets --
no leave/rejoin required.

Updates #cleanup

Signed-off-by: Kabir Sikand <[email protected]>
2026-05-18 18:03:17 +00:00
Kabir Sikand 3223269303 ipn,cmd/tailscale/cli: add tailscale join/leave and blueprint locking
Three pieces, intentionally landed together because the join->set lock
contract is what makes blueprint-bound nodes safe:

  - ipn.Prefs grows a BlueprintID field plus a MaskedPrefs.BlueprintIDSet
    mask bit. A node brought up via "tailscale join" carries BlueprintID
    for the lifetime of the binding; "tailscale leave" clears it.
    Prefs.IsBlueprintBound is a one-line read for callers that just
    need the bit.

  - cmd/tailscale/cli adds the "join" and "leave" subcommands. join
    accepts --blueprint=bp:<id> and --auth-key=<oauth-secret>; under
    the hood it reuses the existing HookResolveAuthKey exchange path
    (OAuth client secret -> auth key) and then calls Start with a
    Prefs whose BlueprintID is set. leave clears BlueprintID and
    logs the node out, matching the spec's "ephemeral when bound"
    semantics.

  - cmd/tailscale/cli/blueprint_lock.go enforces the spec's
    locked-field rejection on "tailscale set" for any blueprint-bound
    node. The error message is the verbatim spec text, varying only
    by which field was touched (Routes, Advertised tags, SSH, etc).
    Inserted in runSet right after curPrefs is fetched so it fires
    before any local validation work.

Client metrics (clientmetric) cover the v1 join/leave/set-rejected
counters and the blueprint_bound gauge so we can answer "is anyone
using this" without server-side correlation.

Updates #cleanup

Signed-off-by: Kabir Sikand <[email protected]>
2026-05-15 19:43:19 +00:00
Alex Chan 0cb432ed84 all: update more references to Tailnet/Network Lock
Updates tailscale/corp#37904

Change-Id: I09e73b3248b9ddf86dafe33dfb621bd560f6596d
Signed-off-by: Alex Chan <[email protected]>
2026-05-15 16:23:50 +01:00
Adriano Sela Aviles 41286c2b56 ipn/ipnlocal,tsd: add NoiseRoundTripper to tsd.Sys
Adds a new NoiseRoundTripper field to tsd.Sys
to expose an http.RoundTripper to make requests
over the control plane Noise connection.

This will be used in PAM use cases soon.

Updates tailscale/corp#41800

Signed-off-by: Adriano Sela Aviles <[email protected]>
2026-05-13 14:56:28 -07:00
Simon Law 6467f0d067 ipn/ipnlocal: fix minor typo in shouldUseOneCGNATRoute (#19719)
This fixes a log message where ipn/ipnlocal.shouldUseOneCGNATRoute
would claim that an android machines was actually macOS.

Updates #cleanup
Updates #19652

Signed-off-by: Simon Law <[email protected]>
2026-05-12 21:55:29 -07:00
Adriano Sela Aviles 72578de033 ipn/{ipnlocal,localapi},client/local: add per-dst cap resolution for services
Adds two new cap resolution methods alongside the existing PeerCaps:

PeerCapsForService(src netip.Addr, svcName tailcfg.ServiceName) resolves
the service name to its VIP addresses via the node's service IP mappings
and returns caps scoped to that service. Exposed on /v0/whois via the
svc_name query parameter and on client/local.Client as WhoIsForService.

PeerCapsForIP(src, dst netip.Addr) resolves caps against an arbitrary
destination IP. Exposed on /v0/whois via the svc_addr query parameter
and on client/local.Client as WhoIsForIP.

svc_name takes priority over svc_addr when both are present. Invalid
values for either return 400. The existing PeerCaps/WhoIs path is
unchanged: without a service parameter, WhoIs returns only host-level
caps.

Updates tailscale/corp#41632

Signed-off-by: Adriano Sela Aviles <[email protected]>
2026-05-12 15:50:39 -07:00
M. J. Fromberger 9f48567bf1 ipn/ipnlocal,wgengine/magicsock: add basic counters for cached peer connectivity (#19699)
Add new clientmetric counters for establishing contact with peers while using
cached network map data. To do this, instrument the magicsock.Conn with a bit
to indicate whether its peer data came from a cached netmap. If so, there are
two conditions we will count as establishing connectivity to a peer:

  - Receipt of a CallMeMaybe from a peer via disco.
  - Establishing a valid endpoint address for a peer.

In vmtest, add Env.ClientMetrics to scrape metrics from the specified node.
Use this to check that counters were updated in caching tests.

Updates https://github.com/tailscale/projects/issues/13
Updates #12639

Change-Id: Ie8cf3244ac8af4f5bcfe4d0d944078da2ba08990
Signed-off-by: M. J. Fromberger <[email protected]>
2026-05-12 12:01:05 -07:00
Alex Chan d6ffc0d986 tka,ipn: reduce boilerplate in Tailnet Lock tests
The `CreateStateForTest` helper reduces boilerplate in cases where the test
only cares about the trusted keys and not the disablement values (and makes
it more obvious where the disablement values are meaningful).

The `setupChonkStorage` helper reduces the boilerplate when creating on-disk
TKA storage in tests.

The `fakeLocalBackend` helper reduces the boilerplate when setting up a
`LocalBackend` instance in the IPN tests.

Updates #cleanup

Change-Id: Iacfba1be5f7fab208eec11e4369d63c7d7519da5
Signed-off-by: Alex Chan <[email protected]>
2026-05-07 21:49:27 +01:00
kari-ts c721189cef ipn/ipnlocal: prefer one CGNAT route on Android (#19652)
Android rebuilds its VpnService interface when the VPN route
configuration changes, which tears down long lived TCP connections
through the tunnel. Use the same automatic OneCGNATRoute behavior as
macOS on Android, and prefer the single CGNAT route when no other
interface is using the CGNAT, falling back to fine grained peer routes
otherwise.

Updates tailscale/tailscale#19591

Signed-off-by: kari <[email protected]>
2026-05-05 19:11:17 -07:00
Brad Fitzpatrick 89a78dc9b7 client/local, ipn/localapi, ipn/ipnlocal: add PeerByID
Add a narrow LocalAPI accessor and matching client/LocalBackend method
to look up a single peer's current full [tailcfg.Node] by NodeID, in
O(1) time on the daemon side, without fetching the entire netmap.

Useful for callers that need the latest state of a single peer (e.g.
in response to a peer-mutation event on the IPN bus) without paying
for a full netmap fetch.

Updates #12542

Change-Id: I1cb2d350e6ad846a5dabc1f5368dfc8121387f7c
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-05-01 06:20:46 -07:00
Alex Chan cac94f51cc ipn/ipnlocal: don't compact TKA state on startup
Compacting on startup means nodes may compact at a different cadence
based on whether they're long-running or restarting frequently.

We already compact after every sync, which only occurs when the TKA
state has changed. Waiting for TKA changes to trigger compaction on
nodes means compaction will occur more consistently across a tailnet.

Updates tailscale/corp#33537

Change-Id: Ia0aa6d9e5e362e9ab08450fde69772841790d5b5
Signed-off-by: Alex Chan <[email protected]>
2026-05-01 13:27:12 +01:00
Brad Fitzpatrick a6c5d23742 ipn, ipn/ipnlocal: add Notify.SelfChange
Add a new bus signal that lets reactive consumers (containerboot, kube
agents, sniproxy, tsconsensus, etc.) react to self-node updates without
having to subscribe to the full netmap. Today those consumers either
watch Notify.NetMap (which on large tailnets is expensive to encode and
ship per watcher) or poll. SelfChange is a cheap, narrow alternative:
addresses, name, key expiry, capabilities, etc.

Consumers that need additional state can react to SelfChange and then
fetch the relevant bits on demand via existing LocalClient methods.

Producer-side, every netmap-bearing setControlClientStatus call now
also publishes SelfChange. Future changes will migrate individual
in-tree consumers off Notify.NetMap to this signal, and eventually
gate the legacy NetMap emission to platforms whose host GUIs still
require it.

Updates #12542

Change-Id: I4441650b0e085d663eb6bf26a03748b7d961ca49
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-30 14:47:03 -07:00
Brad Fitzpatrick 9f343fdc0c client/local, ipn/localapi, all: add CertDomains and DNSConfig accessors
Add two narrow LocalAPI accessors so callers don't have to subscribe to
the IPN bus and pull a full *netmap.NetworkMap just to read DNS-shaped
fields:

  - GET /localapi/v0/cert-domains returns DNS.CertDomains.
  - GET /localapi/v0/dns-config returns the full tailcfg.DNSConfig.

Migrate in-tree callers off the netmap-on-the-bus pattern:

  - kube/certs.waitForCertDomain still wakes on the IPN bus but now
    queries CertDomains via LocalClient.CertDomains rather than
    reading n.NetMap.DNS.CertDomains. The kube LocalClient interface
    and FakeLocalClient gain a CertDomains method.
  - cmd/tailscale dns status calls LocalClient.DNSConfig directly
    instead of opening a NotifyInitialNetMap watcher.
  - cmd/tailscale configure kubeconfig switches from a netmap watcher
    + serviceDNSRecordFromNetMap to LocalClient.DNSConfig +
    serviceDNSRecordFromDNSConfig.

This is part of a series moving callers away from depending on the
netmap traveling on the IPN bus, so the bus payload can shrink in a
later change.

Updates #12542

Change-Id: Ie10204e141d085fbac183b4cfe497226b670ad6c
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-30 13:50:46 -07:00
Brad Fitzpatrick 159cf8707a ipn/ipnlocal, all: split LocalBackend.NetMap into NetMapNoPeers / NetMapWithPeers
Add two narrower accessors alongside the existing
[LocalBackend.NetMap], with docs that distinguish their semantics:

  - NetMapNoPeers: cheap (returns the cached *netmap.NetworkMap with
    a possibly-stale Peers slice). For callers that only read non-Peers
    fields like SelfNode, DNS, PacketFilter, capabilities.
  - NetMapWithPeers: documented as returning an up-to-date Peers slice.
    For callers that genuinely need to iterate Peers or call
    PeerByXxx.

Mark the existing NetMap deprecated and point readers at the two new
accessors. NetMap, NetMapNoPeers, and NetMapWithPeers all currently
return the same value (b.currentNode().NetMap()): this commit is a
no-op behaviorally, just a renaming and migration of in-tree callers.
A subsequent change in the same series will switch
NetMapWithPeers to actually rebuild the Peers slice from the live
per-node-backend peers map (O(N) per call), at which point the
distinction between the two new accessors becomes load-bearing.

Migrate in-tree callers to the appropriate accessor based on what
fields they read:

  - NetMapNoPeers (most common): localapi handlers, peerapi accept,
    GetCertPEMWithValidity, web client noise request, doctor DNS
    resolver check, tsnet CertDomains/TailscaleIPs, ssh/tailssh
    SSH-policy/cap reads, several LocalBackend internals
    (isLocalIP, allowExitNodeDNSProxyToServeName, pauseForNetwork
    nil-check, serve config).
  - NetMapWithPeers: writeNetmapToDiskLocked (persist full netmap to
    disk for fast restart), PeerByTailscaleIP lookup.

Tests still call the legacy NetMap; they'll see the deprecation
warning but otherwise behave identically.

Also add two pieces of plumbing the next change in this series will
need, but which are already useful on their own:

  - [client/local.GetDebugResultJSON]: a generic [Client.DebugResultJSON]
    that decodes directly into a target type T, avoiding the
    marshal/unmarshal roundtrip callers otherwise need.
  - localapi "current-netmap" debug action: returns the current
    netmap (with peers) as JSON. Documented as debug-only — the
    netmap.NetworkMap shape is internal and may change without notice.

This commit is part of a series breaking up a larger change for
review; on its own it is a no-op refactor.

Updates #12542

Change-Id: Idbb30707414f8da3149c44ca0273262708375b02
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-30 11:14:06 -07:00
Brad Fitzpatrick f343b496c3 wgengine, all: remove LazyWG, use wireguard-go callback API for on-demand peers
Replace the UAPI text protocol-based wireguard configuration with
wireguard-go's new direct callback API (SetPeerLookupFunc,
SetPeerByIPPacketFunc, RemoveMatchingPeers, SetPrivateKey).

Instead of computing a trimmed wireguard config ahead of time upon
control plane updates and pushing it via UAPI, install callbacks so
wireguard-go creates peers on demand when packets arrive. This removes
all the LazyWG trimming machinery: idle peer tracking, activity maps,
noteRecvActivity callbacks, the KeepFullWGConfig control knob, and the
ts_omit_lazywg build tag.

For incoming packets, PeerLookupFunc answers wireguard-go's questions
about unknown public keys by looking up the peer in the full config.
For outgoing packets, PeerByIPPacketFunc (installed from
LocalBackend.lookupPeerByIP) maps destination IPs to node public keys
using the existing nodeByAddr index.

Updates tailscale/corp#12345

Change-Id: I4cba80979ac49a1231d00a01fdba5f0c2af95dd8
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-29 19:46:19 -07:00
Claus Lensbøl 978b6a81b2 ipn/ipnlocal: always ReSTUN when starting up without a cache (#19586)
78627c1 introduced starting up and preserving the DERP server from
cache, but also changed it so the initial ReSTUN would not fire when
setting the DERPMap.

Change this so when not working from a cache, the ReSTUN will always
fire during startup.

Updates #19585

Signed-off-by: Claus Lensbøl <[email protected]>
2026-04-29 18:56:57 -04:00
Brad Fitzpatrick 15cba0a3f6 tstest/natlab/vmtest: add TestDiscoKeyChange
Add a vmtest that brings up two gokrazy nodes A and B behind two
One2OneNAT networks (so direct UDP works in both directions and any
slowness can't be blamed on NAT traversal), establishes a WireGuard
tunnel A → B with TSMP, then rotates B's disco key four times and
asserts that the data plane recovers in both directions after each
rotation. All pings are TSMP (the data-plane ping; disco pings would
not exercise the WireGuard tunnel itself).

The five pings:

  1. A → B  (initial; brings up the tunnel; 30s budget)
  2. B → A  after rotate (LocalAPI rotate-disco-key debug action)
  3. A → B  after rotate (LocalAPI)
  4. B → A  after restart (SIGKILL; gokrazy supervisor respawns)
  5. A → B  after restart (SIGKILL)

Each post-rotation ping gets a 15-second budget. Two unavoidable
multi-second waits dominate today:

  - The rotate-then-a→b phase takes ~10s on main because of LazyWG.
    After B's WantRunning bounce, B's wgengine resets its
    sentActivityAt/recvActivityAt maps and trims A out of the
    wireguard-go config as an "idle peer"; B only re-adds A on
    inbound activity, by which point A's first few TSMP packets
    have been silently dropped at B's tundev. The
    bradfitz/rm_lazy_wg branch removes that trimming entirely
    (verified locally: this phase drops to <100ms there).

  - The restart phases take ~5s for wireguard-go's RekeyTimeout
    handshake retry. After SIGKILL+respawn the first WG handshake
    init from the restarted node sometimes goes into the void
    (likely the brief peer-removed window in the receiver's
    two-step maybeReconfigWireguardLocked reconfig during which
    the peer is absent from wireguard-go), and wg-go's 5s+jitter
    retransmit timer is the next opportunity to retry. That retry
    succeeds and the staged TSMP packet flushes. Intrinsic to the
    protocol's retransmit policy.

Once LazyWG is removed and the first-handshake-after-reconfig race
is fixed, the budget should drop to 5s.

Supporting changes:

  ipn/ipnlocal: DebugRotateDiscoKey now toggles WantRunning off and
  back on after rotating the disco key. magicsock.Conn.RotateDiscoKey
  only resets local disco state; without also dropping wireguard-go
  session keys, peers keep encrypting with their stale per-peer
  session against us until their rekey timer fires (WireGuard has no
  data-plane signaling to invalidate sessions). Bouncing WantRunning
  runs the engine through Reconfig(empty) → authReconfig, which
  drops every peer's WG session so the next packet either way
  triggers a fresh handshake.

  ipn/ipnlocal, ipn/localapi: add a debug-only "peer-disco-keys"
  LocalAPI action ([LocalBackend.DebugPeerDiscoKeys]) that returns
  a map[NodePublic]DiscoPublic from the current netmap. Tests reach
  it via [local.Client.DebugResultJSON]. We do not surface disco
  keys via [ipnstate.PeerStatus] because adding a non-comparable
  [key.DiscoPublic] field there breaks reflect-based test helpers
  (e.g. TestFilterFormatAndSortExitNodes' use of cmp.Diff), and
  general LocalAPI clients have no need for disco keys. Since the
  debug LocalAPI is gated behind the ts_omit_debug build tag, this
  endpoint is automatically stripped from small binaries.

  cmd/tta: add /restart-tailscaled handler (Linux-only, via /proc walk)
  to drive the SIGKILL phase. On gokrazy the supervisor respawns
  tailscaled within a second.

  tstest/integration/testcontrol: add Server.AllOnline. When set,
  every peer entry in MapResponses is marked Online=true. Several
  disco-key handling fast paths in controlclient and wgengine
  (removeUnwantedDiscoUpdates, removeUnwantedDiscoUpdatesFromFull
  NetmapUpdate, the wgengine tsmpLearnedDisco fast path) only fire
  for online peers; without this flag, tests exercising disco-key
  rotation only hit the offline-peer code paths, which mask issues
  and are several seconds slower in this scenario. Finer-grained
  per-node online tracking can be added later.

  tstest/natlab/vmtest: add Env.RotateDiscoKey,
  Env.RestartTailscaled, Env.PeerDiscoKey, Node.Name, an
  [AllOnline] EnvOption that plumbs through to
  testcontrol.Server.AllOnline, and an exported
  Env.Ping(from, to, type, timeout). Ping replaces the unexported
  helper so callers can specify both a ping type (PingDisco for
  warming peer state, PingTSMP for asserting end-to-end
  connectivity) and a deadline. PeerDiscoKey returns its LocalAPI
  error so callers inside tstest.WaitFor can retry transient
  failures rather than fataling the test.

Updates #12639
Updates #13038

Change-Id: I3644f27fc30e52990ba25a3983498cc582ddb958
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-29 12:58:00 -07:00
Brad Fitzpatrick 22ff402da9 wgengine/magicsock: restore SetDERPMap signature, add SetDERPMapWithoutReSTUN
Commit 78627c132f changed the signature of magicsock.Conn.SetDERPMap to
take an additional bool doReStun parameter. Avoid both the boolean
parameter and the API signature change by restoring SetDERPMap to its
original single-argument form and adding a new SetDERPMapWithoutReSTUN
method for the cache-loading caller that wants to skip the post-set
ReSTUN.

Updates #19490

Change-Id: I97d9e82156bfc546ccf59756d1ea52f039b5de06
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-29 12:46:15 -07:00
Claus Lensbøl 78627c132f wgengine/magicsock,ipn/ipnlocal: store and load homeDERP from cache (#19491)
With netmap caching, the home DERP of the self node was neither saved to
the cache or loaded from it, making nodes not stick to a DERP when
starting without a connection to control.

Instead, make sure that when a cache is available, load that cache,
before looking for DERP servers. This is implemented by allowing a skip
of ReSTUN in setting the DERP map (we must have a DERP map before
setting the home DERP), so the DERP from cache will set itself and be
sticky until a connection to control is established.

Making DERP only change when connected to control is handled by existing
code from f072d017bd.

Updates #19490

Signed-off-by: Claus Lensbøl <[email protected]>
2026-04-29 10:24:09 -04:00
Alex Chan bb91bb842c all: remove everything related to non-seamless key renewal
Seamless key renewal has been the default in all clients since 1.90.
We retained the ability to disable it from the control plane as a
precaution, but we haven't seen any issues that require us to disable it.

We're now removing all the code for non-seamless key renewal, because we
don't expect to turn it on again, and indeed it's been untested in the
field for three releases so might contain latent bugs!

Updates tailscale/corp#33042

Change-Id: I4b80bf07a3a50298d1c303743484169accc8844b
Signed-off-by: Alex Chan <[email protected]>
2026-04-29 10:03:26 +01:00
Brad Fitzpatrick ad5436af0d tstest/largetailnet, tstest/integration/testcontrol: add in-process large-tailnet benchmark
Add a Go benchmark that exercises a single tailnet client (a [tsnet.Server]
running in the test process) against a synthetic large initial netmap and
a stream of caller-driven peer add/remove deltas, all in-process.

The harness is split in two parts:

  - tstest/largetailnet, a reusable package containing a [Streamer]
    that hijacks the map long-poll on a [testcontrol.Server] via the new
    AltMapStream hook, sends one initial MapResponse with N synthetic
    peers, and forwards caller-supplied delta MapResponses on the same
    stream. Helpers like MakePeer / AllocPeer build synthetic peers with
    unique IDs and addresses derived from the Tailscale ULA range.

  - tstest/largetailnet/largetailnet_test.go, BenchmarkGiantTailnet
    (headless tailscaled workload, no IPN bus subscriber) and
    BenchmarkGiantTailnetBusWatcher (GUI-client workload with one
    Notify subscriber attached). Both are gated on
    --actually-test-giant-tailnet (skipped by default), stand up an
    in-process testcontrol + tsnet.Server, let Up block until the
    initial N-peer netmap has been processed, then ResetTimer and run
    add+remove pairs via b.Loop. Per-delta sync is via a test-only
    [ipnlocal.LocalBackend.AwaitNodeKeyForTest] channel that closes
    once the just-added peer key appears in the netmap (no-watcher
    variant) or via bus-Notify drain (bus-watcher variant).

To support the hijack, [testcontrol.Server] grows an AltMapStream hook
and a small MapStreamWriter interface for benchmarks/stress tests that
need to drive a controlled MapResponse sequence; the normal serveMap
path is untouched when AltMapStream is nil. The streamer answers
non-streaming "lite" map polls (which controlclient issues before the
streaming long-poll to push HostInfo) with an empty MapResponse and
returns immediately, so the streaming poll that follows is the one
that gets the initial netmap.

The benchmark is intended for before/after comparisons of netmap- and
delta-handling changes targeted at large tailnets. CPU profiles on
unmodified main show the expected O(N) hotspots:
setControlClientStatusLocked / authReconfigLocked /
userspaceEngine.Reconfig / setNetMapLocked, plus JSON encoding of the
full Notify.NetMap to bus watchers (which dominates the BusWatcher
variant).

Median ms/op over 10 runs on unmodified main, by tailnet size N:

       N      no-watcher   bus-watcher
   10000          32          166
   50000         222          865
  100000         504         1765
  250000        1551         4696

Recommended invocation:

	go test ./tstest/largetailnet/ -run=^$ \
	    -bench='BenchmarkGiantTailnet(BusWatcher)?$' \
	    -benchtime=2000x -timeout=10m \
	    --actually-test-giant-tailnet \
	    --giant-tailnet-n=250000 \
	    -cpuprofile=/tmp/giant.cpu.pprof

Updates #12542

Change-Id: I4f5b2bb271a36ba853d5a0ffe82054ef2b15c585
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-27 11:47:12 -07:00
Brad Fitzpatrick 0e10a3f580 net/tsdial, ipn/localapi, client/local: let clients dial non-Tailscale addresses directly
Add a tsdial.Dialer.UserDialPlan method that resolves an address and
reports whether the dialer would route it via Tailscale. The LocalAPI
/dial handler now uses this to skip proxying for addresses that aren't
Tailscale routes (e.g. localhost), returning a Dial-Self response with
the resolved address so the client can dial it directly. This avoids
an unnecessary round-trip through the daemon for local connections.

The client's UserDial handles the new response by dialing the resolved
address itself, and the server passes the pre-resolved IP:port for
Tailscale dials to avoid redundant DNS lookups.

Thanks to giacomo and Moyao for pointing this out!

Updates tailscale/corp#39702

Change-Id: I78d640f11ccd92f43ddd505cbb0db8fee19f43a6
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-27 09:33:27 -07:00
Evan Lowry 3a05c450ce posture: add HealthTracker for serial number retrieval (#19181)
Device posture checking can fail while enabled if tailscaled does not
have access to smbios. Previously, this was only observable by looking
in the tailscaled logs.

Fixes tailscale/corp#39314

Signed-off-by: Evan Lowry <[email protected]>
2026-04-25 15:42:47 -03:00
kari-ts aa740cb393 ipnlocal/drive: reduce noisey per-peer remote logs (#19493)
This drops the per peer "appending remote" log while constructing the remote list, which can get noisy on big tailnets, and keeps logs around remote availability checks, including whether a peer is missing, offline, lacks PeerAPI reachability, lacks sharing permission, or is available.

Updates tailscale/corp#40580

Signed-off-by: kari-ts <[email protected]>
2026-04-24 08:26:33 -07:00
James 'zofrex' Sanderson 36f094ea3b ipn/ipnlocal: deflake TestStateMachine{,Seamless} (#19475)
Remove the remaining known sources of flakiness in TestStateMachine and
TestStateMachineSeamless.

Updates tailscale/corp#36230
Updates #19377

Signed-off-by: James Sanderson <[email protected]>
2026-04-22 10:22:47 +01:00
James 'zofrex' Sanderson ffae275d4d ipn/ipnlocal,tailcfg: add /debug/tka c2n endpoint (#19198)
Updates tailscale/corp#35015

Signed-off-by: James Sanderson <[email protected]>
2026-04-20 16:00:03 +01:00
James 'zofrex' Sanderson ec86f0ff93 ipn/ipnlocal: make TestStateMachine less flaky (#19434)
TestStateMachine & TestStateMachineSeamless both flake a lot asserting the
"Shutdown" call on cc after a Logout. This is because Shutdown is called on
a goroutine to avoid a deadlock if it's called while holding the
LocalBackend lock (#18052).

This fixes that cause of flakes by waiting for LocalBackend's goroutine
tracker to have no goroutines running (so the goroutine that calls Shutdown
must have finished).

This does not make TestStateMachine non-flaky because it can flake later in
the test, too: the assertion on "unpause" after clearing the netmap between
"Start4" and "Start4 -> netmap" sometimes fails.

Updates tailscale/corp#36230
Updates #19377
Updates #18052

Signed-off-by: James Sanderson <[email protected]>
2026-04-20 15:58:21 +01:00
Alex Chan cf76202aa3 ipn/ipnlocal: log the local and remote TKA HEADs during sync
Update this log message to show both the local and remote TKA HEAD; this
is useful for debugging issues on nodes that have fallen behind the
remote TKA HEAD.

Updates tailscale/corp#39455

Change-Id: Ia62ce15756180d2fbac4a898fb94d6143df08b54
Signed-off-by: Alex Chan <[email protected]>
2026-04-19 16:52:48 +01:00
Scott Graham cb5a53c424 ipn/ipnlocal: preserve b.loginFlags in auto-login cc.Login calls
LocalBackend stores loginFlags at construction so that per-instance
properties (e.g. LoginEphemeral set by tsnet.Server.Ephemeral) persist
for the session. StartLoginInteractiveAs already merges b.loginFlags
into its cc.Login call, but the two auto-login call sites pass bare
controlclient.LoginDefault, silently dropping any stored flags.

Merge b.loginFlags at both auto-login call sites to match the existing
StartLoginInteractiveAs pattern. LoginDefault is zero so this is a
no-op when loginFlags is empty, and restores the documented behavior
when it isn't.

Fixes #15852

Signed-off-by: Scott Graham <[email protected]>
2026-04-17 23:31:18 -05:00
Michael Ben-Ami 1dc08f4d41 appc,feature/conn25: prevent clients from forwarding DNS requests and
modifying DNS responses for domains they are also connectors for

For Connectors 2025, determine if a client is configured as a
connector and what domains it is a connector for. When acting as a
client, don't install Split DNS routes to other connectors for those
domains, and don't alter DNS responses for those domains. The responses
are forwarded back to the original client, which in turn does the alteration,
swapping the real IP for a Magic IP.

A client is also a connector for a domain if it has tags that overlap
with tags in the configured policy, and --advertise-connector=true
in the prefs (not in the self-node Hostinfo from the netmap). We use the prefs
as the source of truth because control only gets a copy from the prefs, and
may drift. And the AppConnector field is currently zeroed out in the
self-node Hostinfo from control.

The extension adds a ProfileStateChange hook to process prefs changes,
and the config type is split into prefs and nodeview sub-configs.

Fixes tailscale/corp#39317

Signed-off-by: Michael Ben-Ami <[email protected]>
2026-04-16 09:41:54 -04:00
Alex Chan 4f47c3c93d ipn/ipnlocal: log AUM hash on startup as base32, not hex
Before:

    tka initialized at head 325557575a59525354484e4a534f494b4c4e56575435583737564b5036584c4d4c335534554255344c344c36484c5a444a323341

After:

    tka initialized at head 2UWWZYRSTHNJSOIKLNVWT5X77VKP6XLML3U4UBU4L4L6HLZDJ23A

Printing the AUM hash as hex makes it difficult to compare to other AUM
hashes; stringifying it will make it consistent with other printing.

Updates #cleanup

Change-Id: Ic1e23a9ce6a71a53cff7d2190f9fa06eb838ab89
Signed-off-by: Alex Chan <[email protected]>
2026-04-16 13:45:29 +01:00
M. J. Fromberger 1e4934659b ipn/ipnlocal: discard cached netmaps upon panic during SetNetworkMap (#19414)
For debugging purposes, unstable builds will sometimes intentionally panic for
unexpected behaviours. We observed such a panic after loading a cached netmap,
but because we had a valid cached map, the client was unable to recover on its
own and the operator had to manually reset the cache.

As a defensive hedge, when netmap caching is enabled, check for a panic during
installation of a net network map: If one occurs, discard any cached netmaps
before letting the panic unwind, so that we do not lose the panic itself, but
reduce the need for manual intervention.

Updates #12639
Updates tailscale/corp#27300

Change-Id: I0436889c6bdc2fa728c9cb83630cd7b00a72ce68
Signed-off-by: M. J. Fromberger <[email protected]>
2026-04-15 11:07:42 -07:00
Naman Sood 6301a6ce4b util/linuxfw,wgengine/router: allow incoming CGNAT range traffic with nodeattr
Clients with the newly added node attribute
`"disable-linux-cgnat-drop-rule"` will not automatically drop inbound
traffic on non-Tailscale network interfaces with the source IP in the
CGNAT IP range. This is an initial proof-of-concept for enabling
connectivity with off-Tailnet CGNAT endpoints.

Fixes tailscale/corp#36270.

Signed-off-by: Naman Sood <[email protected]>
2026-04-14 16:45:06 -04:00
Brad FitzpatrickandAvery Pennarun 9fbe4b3ed2 all: fix six tests that failed with -count=2
Avery found a bunch of tests that fail with -count=2.

Updates tailscale/corp#40176 (tracks making our CI detect them)

Change-Id: Ie3e4398070dd92e4fe0146badddf1254749cca20
Signed-off-by: Brad Fitzpatrick <[email protected]>
Co-authored-by: Avery Pennarun <[email protected]>
2026-04-13 18:52:57 -07:00
Brad Fitzpatrick 5a7ef4a533 ipn/ipnlocal: mark TestStateMachineSeamless as flaky
Updates #19377

Change-Id: I7dbf5b954effbfa821339e79d02d8a6e46d2862a
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-13 15:19:42 -07:00
Adriano Sela Aviles 21880457eb ipn/localapi,client/local: add services over localapi
Updates tailscale/corp#40052

Signed-off-by: Adriano Sela Aviles <[email protected]>
2026-04-13 11:47:23 -07:00
Alex Chan 1ff369a261 tka: keep the CompactionDefaults alongside the other limits
Updates #cleanup

Change-Id: Ib5e481d5a9c7ec7ac3e6b3913909ab1bf21d7a4d
Signed-off-by: Alex Chan <[email protected]>
2026-04-10 16:06:23 +01:00
Jonathan Nobels 03c3551ee5 ipn/ipnlocal: add netmap mutations to the ipn bus (#19120)
ipn/local: add netmap mutations to the ipn bus

updates tailscale/tailscale#1909

This adds a new new NotifyWatchOpt that allows watchers to
receive PeerChange events (derived from node mutations)
on the IPN bus in lieu of a complete netmap.  We'll continue
to send the full netmap for any map response that includes it,
but for  mutations, sending PeerChange events gives the client
the option to manage it's own models more selectively and cuts
way down on json serialization overhead.

On chatty tailnets, this will vastly reduce the amount of
chatter on the bus.

This change should be backwards compatible, it is
purely additive.  Clients that subscribe to NotifyNetmap will
get the full netmap for every delta.  New clients can
omit that and instead opt into NotifyPeerChanges.

Signed-off-by: Jonathan Nobels <[email protected]>
2026-04-09 15:45:41 -04:00
Brad Fitzpatrick a182b864ac tsd, all: add Sys.ExtraRootCAs, plumb through TLS dial paths
Add ExtraRootCAs *x509.CertPool to tsd.System and plumb it through
the control client, noise transport, DERP, and wgengine layers so
that platforms like Android can inject user-installed CA certificates
into Go's TLS verification.

tlsdial.Config now honors base.RootCAs as additional trusted roots,
tried after system roots and before the baked-in LetsEncrypt fallback.
SetConfigExpectedCert gets the same treatment for domain-fronted DERP.

The Android client will set sys.ExtraRootCAs with a pool built from
x509.SystemCertPool + user-installed certs obtained via the Android
KeyStore API, replacing the current SSL_CERT_DIR environment variable
approach.

Updates #8085

Change-Id: Iecce0fd140cd5aa0331b124e55a7045e24d8e0c2
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-07 18:10:54 -07:00
Nick Khyl 1f84729908 ipn/desktop: use runtime.Pinner to force heap-allocation of msg
GetMessage can call back into Go, triggering stack growth and causing the stack
to be copied to a new memory region, which invalidates the original stack pointer
passed to the syscall. Since GetMessage uses that pointer to write the message
before returning, this leads to memory corruption.

In this PR, we fix this by using runtime.Pinner, which requires the pointer to refer
to heap-allocated memory.

Fixes #19263
Fixes #17832

Signed-off-by: Nick Khyl <[email protected]>
2026-04-07 12:55:11 -05:00
Brad Fitzpatrick 1b5b43787c ipn/localapi, cli, clientmetric: add ipnbus feature tag; fix omit.go stub
Add a new "ipnbus" build feature tag so the watch-ipn-bus LocalAPI
endpoint can be independently controlled, rather than being gated
behind HasDebug || HasServe. Minimal/embedded builds that omit both
debug and serve were getting 404s on watch-ipn-bus, breaking
"tailscale up --authkey=..." and other CLI flows that depend on
WatchIPNBus.

In the CLI, check buildfeatures.HasIPNBus before attempting to watch
the IPN bus in "tailscale up"/"tailscale login", and exit early with
an informational message when the feature is omitted.

Also add the missing NewCounterFunc stub to clientmetric/omit.go,
which caused compilation errors when building with
ts_omit_clientmetrics and netstack enabled.

Fixes #19240

Change-Id: I2e3c69a72fc50fa02542b91b8a54859618a463d1
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-07 10:22:37 -07:00
James Tucker 21695cdbf8 ipn/ipnlocal,net/netmon: make frequent darkwake more efficient
Investigating battery costs on a busy tailnet I noticed a large number
of nodes regularly reconnecting to control and DERP. In one case I was
able to analyze closely `pmset` reported the every-minute wake-ups being
triggered by bluetooth. The node was by side effect reconnecting to
control constantly, and this was at times visible to peers as well.

Three changes here improve the situation:
- Short time jumps (less than 10 minutes) no longer produce "major
  network change" events, and so do not trigger full rebind/reconnect.
- Many "incidental" fields on interfaces are ignored, like MTU, flags
  and so on - if the route is still good, the rest should be manageable.
- Additional log output will provide more detail about the cause of
  major network change events.

Updates #3363

Signed-off-by: James Tucker <[email protected]>
2026-04-06 15:46:51 -07:00
Brad Fitzpatrick 5a899e406d ipn/ipnlocal: add health.Tracker to tests where it was warning in CI
To denoise log output, to make it easier to find real failures.

Updates #19252

Change-Id: Iae64a9278c70de24a236c39e3d181a509a512a0b
Signed-off-by: Brad Fitzpatrick <[email protected]>
2026-04-05 20:20:07 -07:00