tailscale/config.rs
1//! Types and utilities for configuring a Tailscale [`Device`](crate::Device).
2
3use std::path::Path;
4
5use serde::Serializer;
6use ts_control::ExitProxyConfig;
7use ts_keys::PersistState;
8
9use crate::keys::NodeState;
10
11const CONTROL_URL_VAR: &str = "TS_CONTROL_URL";
12const HOSTNAME_VAR: &str = "TS_HOSTNAME";
13const AUTHKEY_VAR: &str = "TS_AUTH_KEY";
14const CLIENT_ID_VAR: &str = "TS_CLIENT_ID";
15const CLIENT_SECRET_VAR: &str = "TS_CLIENT_SECRET";
16const ID_TOKEN_VAR: &str = "TS_ID_TOKEN";
17const AUDIENCE_VAR: &str = "TS_AUDIENCE";
18
19/// Config for connecting to Tailscale.
20pub struct Config {
21 /// The cryptographic keys representing this node's identity.
22 pub key_state: PersistState,
23
24 // TODO(npry): let clients also define an app name once the sdk-level name moves
25 // to a dedicated field
26 /// The name of this client.
27 ///
28 /// This is reported to control in the `Hostinfo.App` field.
29 pub client_name: Option<String>,
30
31 /// The URL of the control server to connect to.
32 pub control_server_url: url::Url,
33
34 /// Allow fetching the control server's machine public key (`GET /key`) over plain **http** when
35 /// [`control_server_url`](Config::control_server_url) is `http://`.
36 ///
37 /// By default (`false`) the key bootstrap is always upgraded to `https`, even for an `http://`
38 /// control URL — so registration **fails** against a control plane that only serves plain http
39 /// (e.g. a self-hosted Headscale on a `http://host:port` LAN endpoint / NodePort with no TLS).
40 /// Set `true` for such a deployment. Only safe when you control both ends over a trusted network
41 /// path; no effect when the control URL is `https://`. Fail-closed default is `false`.
42 pub allow_http_key_fetch: bool,
43
44 /// The hostname this node will request.
45 ///
46 /// If left blank, uses the hostname reported by the OS.
47 pub requested_hostname: Option<String>,
48
49 /// Tags this node will request.
50 pub requested_tags: Vec<String>,
51
52 /// Whether this node registers as *ephemeral*.
53 ///
54 /// This is the equivalent of `tailscale up --ephemeral`. An ephemeral node is
55 /// garbage-collected by the control server shortly after it disconnects, which is the right
56 /// default for short-lived clients. A long-lived node that must survive brief disconnects —
57 /// such as a persistent exit node or subnet router — should set this to `false`, or control
58 /// will GC it out of the tailnet while it is momentarily offline. Defaults to `true`.
59 pub ephemeral: bool,
60
61 /// Whether to accept (and route traffic to) subnet routes advertised by peers.
62 ///
63 /// This is the equivalent of `tailscale up --accept-routes`. Defaults to `false`: only each
64 /// peer's own tailnet address is reachable. Set to `true` to use peers that act as subnet
65 /// routers, so traffic destined for an advertised subnet egresses via the advertising peer.
66 pub accept_routes: bool,
67
68 /// The peer to route internet-bound traffic through (exit node).
69 ///
70 /// This is the equivalent of `tailscale up --exit-node`. The peer may be named by stable node
71 /// ID, tailnet IP, or MagicDNS name via [`ExitNodeSelector`](crate::ExitNodeSelector) (a bare
72 /// IP or name can be parsed with `selector.parse()`). Defaults to `None`: internet-bound
73 /// traffic has no overlay route and is dropped (fail-closed). When set to a peer that
74 /// advertises a default route, all traffic not matching a more-specific route egresses through
75 /// that peer. The selection is re-resolved as the netmap changes.
76 pub exit_node: Option<ts_control::ExitNodeSelector>,
77
78 /// Subnet routes to advertise as a subnet router.
79 ///
80 /// This is the equivalent of `tailscale up --advertise-routes`. Defaults to empty: this node
81 /// advertises no routes. Each prefix is sent to the control server in `HostInfo.RoutableIPs`;
82 /// once the route is approved, peers with `accept_routes` may send traffic for that subnet
83 /// through this node. Only IPv4 prefixes are advertised — IPv6 prefixes are dropped to uphold
84 /// the IPv6-off posture (we never forward IPv6, so advertising it would be a black hole).
85 pub advertise_routes: Vec<ipnet::IpNet>,
86
87 /// Whether to advertise this node as an exit node.
88 ///
89 /// This is the equivalent of `tailscale up --advertise-exit-node`. Defaults to `false`. When
90 /// `true`, the default route `0.0.0.0/0` is advertised so that, once approved, other peers may
91 /// route their internet-bound traffic out through this node's real origin IP. Because that
92 /// means *other* peers' traffic egresses via our IP, it is strictly opt-in. `::/0` is never
93 /// advertised (IPv6-off).
94 pub advertise_exit_node: bool,
95
96 /// TCP ports the inbound forwarder accepts and splices to real OS sockets, for every advertised
97 /// route ([`advertise_routes`](Config::advertise_routes) / [`advertise_exit_node`](Config::advertise_exit_node)).
98 ///
99 /// Acting as a subnet router or exit node means inbound overlay flows to advertised
100 /// destinations are dialed out as real OS connections (mirroring Go `tsnet`'s forwarders). The
101 /// underlying netstack has no all-port accept mode, so the set of forwarded ports is explicit
102 /// rather than the full 1–65535 range. Defaults to empty: a node may advertise routes but
103 /// forward nothing until ports are configured (fail-closed — nothing is dialed).
104 pub forward_tcp_ports: Vec<u16>,
105
106 /// UDP ports the inbound forwarder accepts and splices to real OS sockets, for every advertised
107 /// route. See [`forward_tcp_ports`](Config::forward_tcp_ports); defaults to empty.
108 pub forward_udp_ports: Vec<u16>,
109
110 /// Forward **all** TCP/UDP ports (1–65535) on every advertised route, like a Go subnet router.
111 ///
112 /// This is the equivalent of a `tailscale up --advertise-routes` node forwarding every port,
113 /// instead of the explicit [`forward_tcp_ports`](Config::forward_tcp_ports) /
114 /// [`forward_udp_ports`](Config::forward_udp_ports) sets. When `true`, those explicit sets are
115 /// ignored and the forwarder runs an on-demand per-port listener manager. Anti-leak is
116 /// unchanged: every flow still routes through the same dialer chokepoint, so
117 /// [`forward_exit_egress`](Config::forward_exit_egress) still governs exit-node egress. Defaults
118 /// to `false`.
119 pub forward_all_ports: bool,
120
121 /// Whether exit-node (`0.0.0.0/0`) inbound flows are actually egressed via **this host's real
122 /// origin IP**.
123 ///
124 /// Anti-leak opt-in, separate from [`advertise_exit_node`](Config::advertise_exit_node):
125 /// advertising the default route only offers this node as an exit to control; it does not by
126 /// itself egress a peer's internet-bound traffic. Defaults to `false` (fail-closed): the
127 /// forwarder structurally refuses exit-node egress, dropping `0.0.0.0/0` flows at dial time
128 /// rather than leaking them out our real IP. Set to `true` only on a node whose real IP *is* the
129 /// intended egress (e.g. a residential exit), never on a host whose IP must stay hidden (e.g. a
130 /// cloud VPS). Subnet routes are dialed identically regardless of this flag.
131 pub forward_exit_egress: bool,
132
133 /// Shields-up (Go `tailscale set --shields-up` / `ipn` `ShieldsUp`): when `true`, refuse all
134 /// **inbound** connections from peers that terminate on this node. The packet filter drops
135 /// inbound packets destined to this node's own addresses; forwarded subnet/exit transit and
136 /// replies to connections this node itself initiated are unaffected. Defaults to `false`.
137 pub block_incoming: bool,
138
139 /// Optional upstream proxy that exit-node egress is routed through, so the node egresses via
140 /// the proxy's IP rather than its own origin IP.
141 ///
142 /// This is a **product capability beyond strict Go `tsnet` parity**: it lets a cloud exit node
143 /// route the traffic it egresses through a residential proxy provider configured by the
144 /// deployer, so the cloud host's real IP never appears upstream. Only consulted when
145 /// [`forward_exit_egress`](Config::forward_exit_egress) is `true`. When `Some`, the forwarder is
146 /// wired with a SOCKS5 / HTTP `CONNECT` proxy dialer that **fails closed** — any proxy connect
147 /// or handshake failure drops the flow rather than dialing direct, so the real IP never leaks.
148 /// When `None` (the default) and exit egress is enabled, egress uses this host's real IP. See
149 /// the proxy-egress section of the repo's `AGENTS.md`/`CLAUDE.md`.
150 pub exit_proxy: Option<ExitProxyConfig>,
151
152 /// Per-direction TCP send/receive buffer size (bytes) for the userspace netstack, or `None` to
153 /// use the netstack default (256 KiB per direction, ~512 KiB per socket).
154 ///
155 /// The underlying smoltcp stack has no TCP window auto-tuning, so this value is the hard cap on
156 /// a single flow's bandwidth-delay product: at an 80 ms RTT a 16 KiB window throttles a flow to
157 /// ~1.6 Mbps, which visibly slows large model-API responses even at 1x. Each socket allocates
158 /// this size for both its rx and tx buffer, so a socket consumes ~2× this value. The default
159 /// (256 KiB) suits high-RTT links carrying a few large flows; lower it on memory-constrained
160 /// deployments running many concurrent sockets. Applies to both the application and forwarder
161 /// netstacks.
162 pub tcp_buffer_size: Option<usize>,
163
164 /// WireGuard persistent-keepalive interval applied to every peer, or `None` to disable
165 /// (`PersistentKeepalive`; this is the equivalent of Tailscale setting `PersistentKeepalive=25`
166 /// on a peer when control marks it `KeepAlive=true`).
167 ///
168 /// When `Some(interval)` (the default, `Some(25s)`), each peer emits an empty authenticated
169 /// keepalive after `interval` of outbound silence, holding the path/NAT mapping warm. This is the
170 /// load-bearing fix for **idle DERP-relayed sessions wedging**: on a userspace-netstack node whose
171 /// only path to a peer is the relay, an idle session otherwise ages past expiry with no traffic to
172 /// keep it warm and no timer to refresh it, so the next dial rehandshakes over a cold path and
173 /// loops forever. The persistent keepalive re-arms unconditionally (unlike the reactive WireGuard
174 /// §6.5 keepalive, which is armed only by inbound traffic and dies ~10s after the last inbound
175 /// packet) and the empty packet deliberately does **not** advance the session's rotation/expiry
176 /// timers, so a genuinely dead peer is still detected and rekey still fires on schedule.
177 ///
178 /// Set to `None` to opt out (e.g. an embedder that has its own keepalive strategy or only ever
179 /// runs over a direct, always-warm path). The default is on because this fork's primary
180 /// deployment is the relayed case the wedge bites.
181 pub persistent_keepalive_interval: Option<std::time::Duration>,
182
183 /// Whether to enable IPv6 **on the tailnet overlay** (peer-to-peer reachability over the node's
184 /// Tailscale IPv6 address). Defaults to `false`: the node is IPv4-only on the overlay.
185 ///
186 /// This is an opt-in for general embedders that want Go `tsnet`-style dual-stack overlay
187 /// reachability. It is deliberately **off by default** to preserve this fork's sacred anti-leak
188 /// posture: its primary deployment is a privacy proxy / cloud exit node where IPv6 is disabled
189 /// everywhere to prevent tunnel-bypass IP leakage. When `false`, behavior is byte-for-byte the
190 /// historical IPv4-only path: the underlay binds `0.0.0.0:0`, IPv6 candidates/STUN are refused,
191 /// the netstack is handed no IPv6 overlay address, and MagicDNS answers AAAA as NODATA.
192 ///
193 /// **This flag governs only the overlay.** It has NO effect on the exit-node / forwarder egress
194 /// path: exit and subnet egress to the public internet stays hardcoded IPv4 in `ts_forwarder`
195 /// regardless of this flag, so the residential-proxy / real-origin-IP isolation invariant can
196 /// never be weakened by enabling overlay IPv6. On a host with IPv6 disabled at the kernel, the
197 /// dual-stack overlay bind simply fails and the node stays inert on IPv6 rather than panicking.
198 pub enable_ipv6: bool,
199
200 /// How this node's **application** overlay data path is realized.
201 ///
202 /// Defaults to [`TransportMode::Netstack`](ts_control::TransportMode::Netstack), the userspace
203 /// smoltcp netstack used by the fork's primary unprivileged proxy / exit-node deployment.
204 /// [`TransportMode::Tun`](ts_control::TransportMode::Tun) instead routes the node's overlay
205 /// packets through a real kernel TUN interface (for embedders that want the host OS networking
206 /// stack to see the tailnet directly); it requires privileges (root / `CAP_NET_ADMIN`) and a
207 /// platform with TUN support. This governs only the application data path — never the
208 /// exit-node / forwarder egress path, which keeps its own IPv4-only userspace netstack.
209 pub transport_mode: ts_control::TransportMode,
210
211 /// Whether to ask control to wire this node up server-side for Tailscale Funnel, even when no
212 /// Funnel endpoint is currently active (Go `tsnet`'s "would like to be wired up for Funnel"
213 /// signal, `HostInfo.WireIngress`, capver 113).
214 ///
215 /// When `true`, registration and map requests set `HostInfo.WireIngress` so control provisions
216 /// the DNS / ingress records a Funnel node needs, making a later
217 /// [`Device::listen_funnel`](crate::Device::listen_funnel) (or
218 /// `serve`) session work immediately. Defaults to `false` (fail-closed): a node requests Funnel
219 /// wiring only when explicitly opted in.
220 ///
221 /// Note this fork cannot yet *terminate* public Funnel ingress — `Device::listen_funnel` is
222 /// fail-closed (no client-side ACME engine, and a self-hosted control plane provides no public
223 /// ingress relay). Setting this flag only requests server-side wiring; it does not by itself
224 /// make Funnel live.
225 pub wire_ingress: bool,
226
227 /// VIP services this node advertises that it **hosts** (`svc:<dns-label>` names), the advertise
228 /// side of Tailscale VIP services (Go `tsnet`'s `Hostinfo.ServicesHash` + c2n
229 /// `GET /vip-services`).
230 ///
231 /// Each entry is a full `svc:`-prefixed name. The valid names (each validated as a well-formed
232 /// `svc:<dns-label>`; malformed names are dropped and logged) are hashed into
233 /// `HostInfo.ServicesHash` on registration and every map request, and reported when control
234 /// fetches the hosted-service list via the c2n `/vip-services` endpoint. Defaults to empty:
235 /// advertise nothing (the hash is `""`, behavior unchanged). Actually *hosting* a service still
236 /// requires control to assign it a VIP and the node to be tagged.
237 pub advertise_services: Vec<String>,
238
239 /// Filesystem directory that received Taildrop files land in, or `None` to disable Taildrop
240 /// (the default, fail-closed).
241 ///
242 /// When `Some(dir)` **and** a peerAPI port is configured (Taildrop is served on the shared
243 /// peerAPI listener, so it needs the same bind), the runtime serves the Taildrop peerAPI route
244 /// `PUT /v0/put/<name>` and writes incoming files under `dir` (created if absent). When `None`,
245 /// no Taildrop server is run and a peer's `PUT` is refused (`403`). The embedder consumes
246 /// received files via the [`Device::taildrop_waiting_files`](crate::Device::taildrop_waiting_files)
247 /// / [`taildrop_open_file`](crate::Device::taildrop_open_file) /
248 /// [`taildrop_delete_file`](crate::Device::taildrop_delete_file) methods.
249 pub taildrop_dir: Option<std::path::PathBuf>,
250
251 /// Pre-auth key for non-interactive registration (Go `tsnet.Server.AuthKey`). When set, used as
252 /// the registration auth key. If it is an OAuth client secret (prefix `tskey-client-`) and the
253 /// `identity-federation` feature is enabled, it is exchanged for an auth key before registration.
254 /// Falls back to the `TS_AUTH_KEY` env var (see [`auth_key_from_env`]). Defaults to `None`.
255 pub auth_key: Option<String>,
256
257 /// OAuth client ID for workload-identity federation (Go `tsnet.Server.ClientID`). SaaS-only;
258 /// requires the `identity-federation` feature. With [`id_token`](Config::id_token) or
259 /// [`audience`](Config::audience), the node exchanges an IdP-issued OIDC token for a Tailscale
260 /// auth key. Defaults to `None` (`TS_CLIENT_ID` env fallback).
261 pub client_id: Option<String>,
262
263 /// OAuth client secret used to mint auth keys via OAuth (Go `tsnet.Server.ClientSecret`).
264 /// SaaS-only; requires the `identity-federation` feature. Defaults to `None` (`TS_CLIENT_SECRET`).
265 ///
266 /// Treat as **fully operator-trusted input**: a `tskey-client-…?baseURL=…` secret redirects the
267 /// credential exchange to that host, so a hostile value would exfiltrate the secret and the
268 /// minted auth key. Never source it from a less-trusted origin.
269 pub client_secret: Option<String>,
270
271 /// IdP-issued OIDC ID token to exchange with control for an auth key via workload-identity
272 /// federation (Go `tsnet.Server.IDToken`). SaaS-only; requires the `identity-federation` feature
273 /// and [`client_id`](Config::client_id). Mutually exclusive with [`audience`](Config::audience).
274 /// Defaults to `None` (`TS_ID_TOKEN`).
275 pub id_token: Option<String>,
276
277 /// Audience for requesting an OIDC ID token from the ambient workload identity (GitHub Actions /
278 /// GCP / AWS), to exchange for an auth key via workload-identity federation (Go
279 /// `tsnet.Server.Audience`). SaaS-only; requires the `identity-federation` feature +
280 /// [`client_id`](Config::client_id). Mutually exclusive with [`id_token`](Config::id_token).
281 /// Defaults to `None` (`TS_AUDIENCE`).
282 pub audience: Option<String>,
283}
284
285impl Config {
286 /// Create a new config with its [`key_state`](Config::key_state) populated from the specified key file and using
287 /// default options for other configuration.
288 ///
289 /// See [`load_key_file`] for more details and an alternative with more options for reading
290 /// the key file.
291 pub async fn default_with_key_file(p: impl AsRef<Path>) -> Result<Self, crate::Error> {
292 Ok(Config {
293 key_state: load_key_file(p, Default::default()).await?,
294 ..Default::default()
295 })
296 }
297
298 /// Run the application overlay over a real kernel **TUN** interface instead of the default
299 /// userspace netstack — a builder shortcut for setting
300 /// [`transport_mode`](Config::transport_mode) to
301 /// [`TransportMode::Tun`](ts_control::TransportMode::Tun).
302 ///
303 /// `name` is the desired interface name (`None` lets the OS pick, e.g. `utunN` on macOS); `mtu`
304 /// is the interface MTU (`None` uses the transport default; Tailscale's overlay MTU is 1280).
305 /// TUN mode requires root / `CAP_NET_ADMIN` and the engine's `tun` feature to be enabled.
306 /// Chainable: `Config::default().use_tun(Some("tailscale0".into()), None)`.
307 #[must_use]
308 pub fn use_tun(mut self, name: Option<String>, mtu: Option<u16>) -> Self {
309 self.transport_mode = ts_control::TransportMode::Tun(ts_control::TunConfig { name, mtu });
310 self
311 }
312
313 /// Construct a default config, setting certain fields from environment variables.
314 ///
315 /// The fields are only set if the corresponding environment variable is present, using
316 /// the default value otherwise.
317 ///
318 /// Loads:
319 ///
320 /// - `control_server_url` from `TS_CONTROL_URL`
321 /// - `requested_hostname` from `TS_HOSTNAME`
322 /// - `auth_key` from `TS_AUTH_KEY`
323 /// - `client_id` from `TS_CLIENT_ID`
324 /// - `client_secret` from `TS_CLIENT_SECRET`
325 /// - `id_token` from `TS_ID_TOKEN`
326 /// - `audience` from `TS_AUDIENCE`
327 pub fn default_from_env() -> Config {
328 let mut config = Config::default();
329
330 if let Ok(u) = std::env::var(CONTROL_URL_VAR) {
331 match u.parse() {
332 Ok(u) => config.control_server_url = u,
333 Err(e) => {
334 tracing::error!(error = %e, "parsing {CONTROL_URL_VAR} (fall back to default value)");
335 }
336 }
337 };
338
339 config.requested_hostname = std::env::var(HOSTNAME_VAR).ok();
340
341 if let Some(auth_key) = auth_key_from_env() {
342 config.auth_key = Some(auth_key);
343 }
344 if let Ok(client_id) = std::env::var(CLIENT_ID_VAR) {
345 config.client_id = Some(client_id);
346 }
347 if let Ok(client_secret) = std::env::var(CLIENT_SECRET_VAR) {
348 config.client_secret = Some(client_secret);
349 }
350 if let Ok(id_token) = std::env::var(ID_TOKEN_VAR) {
351 config.id_token = Some(id_token);
352 }
353 if let Ok(audience) = std::env::var(AUDIENCE_VAR) {
354 config.audience = Some(audience);
355 }
356
357 config
358 }
359
360 /// Rotate this config's node key in place for an embedder-driven re-registration, mirroring Go's
361 /// `regen` flow: the current node key is recorded as the old key and a fresh node key is
362 /// generated. Re-create the [`Device`](crate::Device) from this config to perform the rotation;
363 /// the next registration sends the prior key as `OldNodeKey` for key continuity.
364 ///
365 /// Reactive and embedder-driven by design (you decide when to rotate, e.g. after observing
366 /// [`Device::self_key_expired`](crate::Device::self_key_expired) flip, or on a policy of your
367 /// own). This fork does not auto-rotate before expiry — neither does Go, which treats key expiry
368 /// as a deliberate periodic re-authentication checkpoint. Rotation still requires a valid auth
369 /// key, exactly like a fresh registration.
370 pub fn rotate_node_key(&mut self) {
371 self.key_state.rotate_node_key();
372 }
373}
374
375/// Load an auth key from the `TS_AUTH_KEY` environment variable.
376pub fn auth_key_from_env() -> Option<String> {
377 std::env::var(AUTHKEY_VAR).ok()
378}
379
380/// Load key state from a path on the filesystem, or create a file with a new key state if
381/// one doesn't exist.
382///
383/// The `bad_format` argument allows you to specify whether an existing file should be
384/// overwritten if the contents can't be parsed.
385pub async fn load_key_file(
386 p: impl AsRef<Path>,
387 bad_format: BadFormatBehavior,
388) -> Result<PersistState, crate::Error> {
389 let p = p.as_ref();
390
391 tracing::trace!(key_file = %p.display(), "loading key file");
392
393 let key_file = load_or_init::<KeyFile>(
394 &p,
395 Default::default,
396 |x| match x {
397 #[allow(deprecated)]
398 KeyFile::Old(old) => Some(KeyFile::New(KeyFileNew {
399 key_state: PersistState::from(&old.key_state),
400 })),
401 _ => None,
402 },
403 bad_format,
404 )
405 .await?;
406 Ok(key_file.key_state())
407}
408
409#[derive(serde::Deserialize)]
410#[serde(untagged)]
411enum KeyFile {
412 #[deprecated]
413 Old(KeyFileOld),
414 New(KeyFileNew),
415}
416
417impl KeyFile {
418 #[allow(deprecated)]
419 pub fn key_state(&self) -> PersistState {
420 match self {
421 Self::Old(old) => (&old.key_state).into(),
422 Self::New(new) => new.key_state.clone(),
423 }
424 }
425}
426
427impl Default for KeyFile {
428 fn default() -> Self {
429 KeyFile::New(KeyFileNew::default())
430 }
431}
432
433impl serde::Serialize for KeyFile {
434 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
435 where
436 S: Serializer,
437 {
438 KeyFileNew {
439 key_state: self.key_state(),
440 }
441 .serialize(serializer)
442 }
443}
444
445#[derive(serde::Deserialize, serde::Serialize, Default)]
446struct KeyFileNew {
447 key_state: PersistState,
448}
449
450#[derive(serde::Deserialize)]
451struct KeyFileOld {
452 key_state: NodeState,
453}
454
455impl From<&Config> for ts_control::Config {
456 fn from(value: &Config) -> ts_control::Config {
457 ts_control::Config {
458 client_name: value.client_name.clone(),
459 hostname: value.requested_hostname.clone(),
460 server_url: value.control_server_url.clone(),
461 tags: value.requested_tags.clone(),
462 ephemeral: value.ephemeral,
463 accept_routes: value.accept_routes,
464 exit_node: value.exit_node.clone(),
465 advertise_routes: value.advertise_routes.clone(),
466 advertise_exit_node: value.advertise_exit_node,
467 forward_tcp_ports: value.forward_tcp_ports.clone(),
468 forward_udp_ports: value.forward_udp_ports.clone(),
469 forward_all_ports: value.forward_all_ports,
470 forward_exit_egress: value.forward_exit_egress,
471 block_incoming: value.block_incoming,
472 exit_proxy: value.exit_proxy.clone(),
473 tcp_buffer_size: value.tcp_buffer_size,
474 persistent_keepalive_interval: value.persistent_keepalive_interval,
475 peerapi_port: None,
476 taildrop_dir: value.taildrop_dir.clone(),
477 enable_ipv6: value.enable_ipv6,
478 transport_mode: value.transport_mode.clone(),
479 wire_ingress: value.wire_ingress,
480 // A fresh runtime-local flag (default `false`): the runtime flips it when
481 // `Device::listen_funnel` starts a listener. Not derived from the embedder config.
482 ingress_active: std::sync::Arc::new(std::sync::atomic::AtomicBool::new(false)),
483 advertise_services: value.advertise_services.clone(),
484 allow_http_key_fetch: value.allow_http_key_fetch,
485 }
486 }
487}
488
489impl Default for Config {
490 fn default() -> Self {
491 Self {
492 key_state: Default::default(),
493 client_name: None,
494 control_server_url: ts_control::DEFAULT_CONTROL_SERVER.clone(),
495 allow_http_key_fetch: false,
496 requested_hostname: None,
497 requested_tags: vec![],
498 ephemeral: true,
499 accept_routes: false,
500 exit_node: None,
501 advertise_routes: vec![],
502 advertise_exit_node: false,
503 forward_tcp_ports: vec![],
504 forward_udp_ports: vec![],
505 forward_all_ports: false,
506 forward_exit_egress: false,
507 block_incoming: false,
508 exit_proxy: None,
509 tcp_buffer_size: None,
510 persistent_keepalive_interval: Some(ts_control::DEFAULT_PERSISTENT_KEEPALIVE),
511 enable_ipv6: false,
512 transport_mode: ts_control::TransportMode::default(),
513 wire_ingress: false,
514 advertise_services: vec![],
515 taildrop_dir: None,
516 auth_key: None,
517 client_id: None,
518 client_secret: None,
519 id_token: None,
520 audience: None,
521 }
522 }
523}
524
525#[cfg(test)]
526mod tests {
527 use super::*;
528
529 // The `From<&Config> for ts_control::Config` impl hand-copies every field, so it silently
530 // drops any field a future edit forgets to add. These tests assert each dataplane field
531 // crosses the boundary, with special attention to the anti-leak ones (`forward_exit_egress`,
532 // `exit_proxy`) whose loss would change egress behavior.
533 #[test]
534 fn from_config_threads_all_dataplane_fields() {
535 let cfg = Config {
536 accept_routes: true,
537 advertise_exit_node: true,
538 forward_all_ports: true,
539 forward_exit_egress: true,
540 forward_tcp_ports: vec![80, 443],
541 forward_udp_ports: vec![53],
542 tcp_buffer_size: Some(1024 * 128),
543 persistent_keepalive_interval: Some(std::time::Duration::from_secs(17)),
544 enable_ipv6: true,
545 wire_ingress: true,
546 transport_mode: ts_control::TransportMode::Tun(ts_control::TunConfig {
547 name: Some("tailscale0".to_owned()),
548 mtu: Some(1280),
549 }),
550 advertise_routes: vec!["10.0.0.0/24".parse().unwrap()],
551 requested_tags: vec!["tag:exit".to_owned()],
552 advertise_services: vec!["svc:samba".to_owned()],
553 ephemeral: false,
554 exit_proxy: Some(ExitProxyConfig {
555 addr: "198.51.100.9:8080".parse().unwrap(),
556 scheme: ts_control::ExitProxyScheme::Socks5,
557 auth: Some(("u".to_owned(), "p".to_owned())),
558 }),
559 taildrop_dir: Some(std::path::PathBuf::from("/var/lib/taildrop")),
560 ..Default::default()
561 };
562
563 let control: ts_control::Config = (&cfg).into();
564
565 assert!(control.accept_routes);
566 assert!(control.advertise_exit_node);
567 assert!(control.forward_all_ports);
568 assert!(control.forward_exit_egress);
569 assert!(!control.ephemeral);
570 assert_eq!(control.forward_tcp_ports, vec![80, 443]);
571 assert_eq!(control.forward_udp_ports, vec![53]);
572 assert_eq!(control.tcp_buffer_size, Some(1024 * 128));
573 assert_eq!(
574 control.persistent_keepalive_interval,
575 Some(std::time::Duration::from_secs(17))
576 );
577 assert_eq!(control.tags, vec!["tag:exit".to_owned()]);
578 let proxy = control.exit_proxy.expect("exit_proxy crosses the boundary");
579 assert_eq!(proxy.addr, "198.51.100.9:8080".parse().unwrap());
580 assert_eq!(proxy.scheme, ts_control::ExitProxyScheme::Socks5);
581 assert_eq!(proxy.auth, Some(("u".to_owned(), "p".to_owned())));
582 assert!(control.enable_ipv6);
583 assert!(control.wire_ingress);
584 assert_eq!(control.advertise_services, vec!["svc:samba".to_owned()]);
585 assert_eq!(
586 control.taildrop_dir,
587 Some(std::path::PathBuf::from("/var/lib/taildrop"))
588 );
589 assert_eq!(
590 control.transport_mode,
591 ts_control::TransportMode::Tun(ts_control::TunConfig {
592 name: Some("tailscale0".to_owned()),
593 mtu: Some(1280),
594 })
595 );
596 }
597
598 #[test]
599 fn from_config_default_is_netstack_transport() {
600 // The unprivileged userspace netstack is the safe default; opting into a kernel TUN
601 // interface (which needs root) must be explicit.
602 let control: ts_control::Config = (&Config::default()).into();
603 assert_eq!(control.transport_mode, ts_control::TransportMode::Netstack);
604 }
605
606 #[test]
607 fn from_config_default_has_no_exit_proxy() {
608 let control: ts_control::Config = (&Config::default()).into();
609 assert!(control.exit_proxy.is_none());
610 assert!(!control.forward_exit_egress);
611 }
612
613 /// Persistent keepalive is **on by default at 25s** — this is the idle-wedge fix's safe default
614 /// for the relayed case (an idle DERP-relayed session would otherwise age out and wedge). The
615 /// default mirrors `ts_control::DEFAULT_PERSISTENT_KEEPALIVE` and crosses the control boundary.
616 #[test]
617 fn from_config_default_enables_persistent_keepalive_25s() {
618 let cfg = Config::default();
619 assert_eq!(
620 cfg.persistent_keepalive_interval,
621 Some(std::time::Duration::from_secs(25))
622 );
623 let control: ts_control::Config = (&cfg).into();
624 assert_eq!(
625 control.persistent_keepalive_interval,
626 Some(ts_control::DEFAULT_PERSISTENT_KEEPALIVE)
627 );
628 }
629
630 #[test]
631 fn wif_fields_default_none() {
632 // Workload-identity-federation config is SaaS-only and opt-in: a default config never
633 // carries an auth key or any OAuth/OIDC federation material.
634 let cfg = Config::default();
635 assert!(cfg.auth_key.is_none());
636 assert!(cfg.client_id.is_none());
637 assert!(cfg.client_secret.is_none());
638 assert!(cfg.id_token.is_none());
639 assert!(cfg.audience.is_none());
640 }
641
642 #[test]
643 fn from_config_default_is_ipv4_only() {
644 // The IPv6-off posture is the safe default: enabling overlay IPv6 must be an explicit opt-in.
645 let control: ts_control::Config = (&Config::default()).into();
646 assert!(!control.enable_ipv6);
647 }
648
649 /// `use_tun` is a chainable builder that sets `transport_mode` to `Tun(TunConfig { name, mtu })`,
650 /// and the selection threads through to the control config. Also exercises the facade re-exports
651 /// `tailscale::TransportMode` / `tailscale::TunConfig` by naming them without the `ts_control::`
652 /// path (the whole point of the re-export — a downstream crate can use only the facade).
653 #[test]
654 fn use_tun_builder_sets_transport_mode() {
655 use crate::{TransportMode, TunConfig};
656
657 // Default is netstack.
658 assert_eq!(Config::default().transport_mode, TransportMode::Netstack);
659
660 let cfg = Config::default().use_tun(Some("tailscale0".to_string()), Some(1280));
661 assert_eq!(
662 cfg.transport_mode,
663 TransportMode::Tun(TunConfig {
664 name: Some("tailscale0".to_string()),
665 mtu: Some(1280),
666 })
667 );
668
669 // The selection crosses the From<&Config> boundary into the control config.
670 let control: ts_control::Config = (&cfg).into();
671 assert_eq!(
672 control.transport_mode,
673 TransportMode::Tun(TunConfig {
674 name: Some("tailscale0".to_string()),
675 mtu: Some(1280),
676 })
677 );
678 }
679}
680
681/// What to do if the key file can't be parsed.
682///
683/// Default behavior: return an error.
684#[derive(Debug, Copy, Clone, PartialEq, Eq, Default)]
685pub enum BadFormatBehavior {
686 /// Return an error.
687 #[default]
688 Error,
689
690 /// Overwrite the file with a newly-generated set of keys.
691 Overwrite,
692}
693
694/// Attempt to load a file from a path. If it doesn't exist, create it with the
695/// specified default value.
696#[tracing::instrument(skip_all, fields(?bad_format_behavior, path = %path.as_ref().display()))]
697async fn load_or_init<KeyState>(
698 path: impl AsRef<Path>,
699 default: impl FnOnce() -> KeyState,
700 migrate: impl FnOnce(&KeyState) -> Option<KeyState>,
701 bad_format_behavior: BadFormatBehavior,
702) -> Result<KeyState, crate::Error>
703where
704 KeyState: serde::Serialize + serde::de::DeserializeOwned,
705{
706 let path = path.as_ref();
707
708 tokio::fs::create_dir_all(path.parent().unwrap())
709 .await
710 .map_err(|e| {
711 tracing::error!(error = %e, "creating parent dirs for key file");
712 crate::Error::KeyFileWrite
713 })?;
714
715 match tokio::fs::read(path).await {
716 Ok(contents) => match serde_json::from_slice::<KeyState>(&contents) {
717 Ok(state) => {
718 if let Some(migrated) = migrate(&state) {
719 match try_write(path, &migrated).await {
720 Ok(_) => {
721 tracing::info!("migrated key file to new disco-less format");
722 return Ok(migrated);
723 }
724 Err(e) => {
725 tracing::error!(error = %e, "unable to migrate key file");
726 }
727 }
728 }
729
730 return Ok(state);
731 }
732 Err(e) => match bad_format_behavior {
733 BadFormatBehavior::Error => {
734 tracing::error!(error = %e, "parsing key file");
735 return Err(crate::Error::KeyFileRead);
736 }
737 BadFormatBehavior::Overwrite => {
738 tracing::warn!(
739 error = %e,
740 config_file_contents_len = contents.len(),
741 "failed loading version from key file, overwriting",
742 );
743 }
744 },
745 },
746 Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
747 Err(e) => {
748 tracing::error!(error = %e, path = %path.display(), "reading key file");
749 return Err(crate::Error::KeyFileRead);
750 }
751 }
752
753 let value = default();
754 try_write(path, &value).await?;
755 Ok(value)
756}
757
758async fn try_write(
759 path: impl AsRef<Path>,
760 value: &impl serde::Serialize,
761) -> Result<(), crate::Error> {
762 tokio::fs::write(
763 path,
764 serde_json::to_vec(value).map_err(|e| {
765 tracing::error!(error = %e, "serializing key state");
766 crate::Error::KeyFileWrite
767 })?,
768 )
769 .await
770 .map_err(|e| {
771 tracing::error!(error = %e, "saving key state");
772 crate::Error::KeyFileWrite
773 })?;
774
775 Ok(())
776}