Skip to main content

ts_control/
lib.rs

1#![doc = include_str!("../README.md")]
2
3extern crate alloc;
4
5/// Package version of `ts_control` as reported by cargo.
6// TODO(npry): this is used to populate Hostinfo.ipn_version, which requests "long format":
7//  attach build info and whatever else that entails
8const PKG_VERSION: &str = if let Some(version) = option_env!("CARGO_PKG_VERSION") {
9    version
10} else {
11    ""
12};
13
14/// Maximum size of a control-plane RPC response body read into memory.
15///
16/// The control server is the identity trust root, but a buggy/compromised/MITM'd-past-Noise server
17/// must not be able to OOM the client by answering a small request with an unbounded streamed body.
18/// Every control RPC response (register, key-fetch, id-token, set-dns, logout, WIF) carries a small
19/// JSON payload, so 1 MiB is comfortably generous; reads use
20/// [`ResponseExt::collect_bytes_limited`](ts_http_util::ResponseExt::collect_bytes_limited) with this
21/// cap so the allocation is bounded *during* the read. (TKA-sync keeps its own larger 10 MiB bound;
22/// ACME its own 256 KiB bound — those payloads are differently sized.)
23pub(crate) const MAX_CONTROL_RESPONSE: usize = 1024 * 1024;
24
25/// Client-side ACME (Let's Encrypt) DNS-01 cert issuance engine (`acme` feature, SaaS-only).
26#[cfg(feature = "acme")]
27pub mod acme;
28#[cfg(feature = "async_tokio")]
29mod cert;
30mod config;
31mod control_dialer;
32mod derp;
33mod dial_plan;
34mod dns;
35mod hostinfo;
36#[cfg_attr(not(feature = "async_tokio"), expect(dead_code))]
37mod map_request_builder;
38mod node;
39#[cfg(feature = "async_tokio")]
40mod serve;
41mod service;
42mod ssh_policy;
43mod tka;
44#[cfg(feature = "async_tokio")]
45mod tokio;
46#[cfg(feature = "identity-federation")]
47pub mod wif;
48
49use std::fmt;
50
51#[cfg(feature = "async_tokio")]
52pub use cert::{
53    CertError, MISSING_CERT_RPC, certified_key_from_pem, get_certificate, is_tailnet_name,
54};
55#[cfg(feature = "acme")]
56pub use cert::{
57    PublishTxt, SetDnsPublisher, issue_cert_pair_via_setdns, issue_certificate_via_setdns,
58};
59#[doc(inline)]
60pub use config::{
61    Config, DEFAULT_CONTROL_SERVER, DEFAULT_PERSISTENT_KEEPALIVE, ExitProxyConfig, ExitProxyScheme,
62    LocalApi, TransportMode, TunConfig, services_hash,
63};
64pub use control_dialer::{ControlDialer, TcpDialer, complete_connection};
65pub use derp::{Map as DerpMap, Region as DerpRegion, convert_derp_map};
66pub use dial_plan::{DialCandidate, DialMode, DialPlan};
67pub use dns::{DnsConfig, ExtraRecord, Resolver as DnsResolver, ResolverTransport};
68pub use node::{
69    ExitNodeSelector, Id as NodeId, Node, NodeCapMap, PeerChange, StableId as StableNodeId,
70    TailnetAddress, UserProfile, is_tailscale_ip, validate_service_name,
71};
72#[cfg(feature = "async_tokio")]
73pub use serve::{
74    FunnelError, FunnelOptions, MISSING_FUNNEL_RELAY, ServeConfig, ServeState, ServeTarget,
75    accept_tls, funnel_access, listen_funnel, listen_tls, tls_acceptor,
76};
77pub use service::{ServiceError, ServiceMode, resolve_service_listen};
78pub use ssh_policy::{
79    SshAccept, SshAction, SshConnIdentity, SshDecision, SshDenyReason, SshPolicy, SshPrincipal,
80    SshRule,
81};
82pub use tka::TkaStatus;
83pub use ts_control_serde::{
84    Endpoint, EndpointType, NODE_ATTR_SUGGEST_EXIT_NODE, TkaBootstrapRequest, TkaBootstrapResponse,
85    TkaDisableRequest, TkaDisableResponse, TkaInitBeginRequest, TkaInitBeginResponse,
86    TkaInitFinishRequest, TkaInitFinishResponse, TkaSignInfo, TkaSubmitSignatureRequest,
87    TkaSubmitSignatureResponse, TkaSyncOfferRequest, TkaSyncOfferResponse, TkaSyncSendRequest,
88    TkaSyncSendResponse, UserId,
89};
90#[cfg(feature = "identity-federation")]
91pub use wif::{WifConfig, WifError, resolve_auth_key};
92
93/// Re-exported TLS types from the `tokio-rustls`/`ring` stack used by `cert`/`serve`, so
94/// embedders can name [`get_certificate`]/[`listen_tls`] return types without taking their own
95/// direct `tokio-rustls` dependency (and risking a second, mismatched crypto provider).
96#[cfg(feature = "async_tokio")]
97pub mod tls {
98    pub use tokio_rustls::{TlsAcceptor, rustls::sign::CertifiedKey, server::TlsStream};
99}
100
101#[cfg(feature = "async_tokio")]
102pub use crate::tokio::{
103    AsyncControlClient, FilterUpdate, IdTokenError, LogoutError, LogoutInternalErrorKind,
104    NETMAP_CACHE_FILE, NODE_ATTR_CACHE_NETWORK_MAPS, NODE_ATTR_DISABLE_CACHE_NETWORK_MAPS,
105    NetmapCache, PeerUpdate, SetDnsError, SetDnsInternalErrorKind, StateUpdate, TkaSyncError,
106    TkaSyncInternalErrorKind, fetch_id_token, logout, netmap_caching_enabled, set_dns,
107    tka_bootstrap, tka_disable, tka_init_begin, tka_init_finish, tka_submit_signature,
108    tka_sync_offer, tka_sync_send,
109};
110
111/// An error which occurred while connecting to the control server or control plane.
112#[derive(Debug, thiserror::Error, Clone, Eq, PartialEq)]
113pub enum Error {
114    /// A machine was not authorized by control to join tailnet; authorize via the supplied URL.
115    #[error("machine was not authorized by control to join tailnet, authorize at {0}")]
116    MachineNotAuthorized(url::Url),
117
118    /// A machine is not yet authorized and control offered **no** interactive auth URL — it is
119    /// awaiting admin approval on an approval-gated tailnet. **Transient and recoverable**: the node
120    /// holds a valid key and must poll-and-retry registration until an admin approves, then it comes
121    /// up with no re-registration (Go's `ipn.State::NeedsMachineAuth` → `Starting` auto-transition).
122    /// Distinct from [`Internal`](Self::Internal)`(MachineAuthorization, _)` so the control runner can
123    /// tell "awaiting approval" (poll) apart from a hard internal failure (stop), and from
124    /// [`MachineNotAuthorized`](Self::MachineNotAuthorized) which carries a URL for interactive login.
125    #[error("machine awaiting admin approval to join tailnet (no interactive auth URL)")]
126    NeedsMachineAuth,
127
128    /// The user supplied an invalid URL.
129    #[error("invalid URL: {0}")]
130    InvalidUrl(url::Url),
131
132    /// Control rejected registration with a specific reason (e.g. a bad/expired/unknown auth key).
133    /// The string is control's verbatim `RegisterResponse.Error` message.
134    #[error("control rejected registration: {0}")]
135    Registration(String),
136
137    /// Control rate-limited us (HTTP 429). The [`Duration`](core::time::Duration) is the
138    /// server-requested cooldown (from `Retry-After`); the retry loop waits exactly this before the
139    /// next attempt rather than its own backoff, so we never re-hit control inside the cooldown.
140    #[error("control rate limited the request; retry after {0:?}")]
141    RateLimited(core::time::Duration),
142
143    /// Some kind of networking error.
144    ///
145    /// These might be addressed by retrying, or might be an unresolvable error.
146    ///
147    /// [`Operation`] is intended to be informational, rather then inspected during handling.
148    #[error("a networking error occurred in {0}")]
149    NetworkError(Operation),
150
151    /// An internal error that users of the library are not expected to handle.
152    ///
153    /// [`InternalErrorKind`] and [`Operation`] are intended to be informational, rather then
154    /// inspected during handling.
155    #[error("{0} error in {1}")]
156    Internal(InternalErrorKind, Operation),
157}
158
159impl Error {
160    fn io_error(err: std::io::Error, op: Operation) -> Self {
161        if crate::is_network_error(&err) {
162            Error::NetworkError(op)
163        } else {
164            Error::Internal(InternalErrorKind::Io, op)
165        }
166    }
167}
168
169/// What kind of internal error has occurred.
170///
171/// This is intended to be useful for reporting a crash to an end user, rather than being handled.
172#[non_exhaustive]
173#[derive(Debug, Clone, Copy, Eq, PartialEq)]
174pub enum InternalErrorKind {
175    /// An error in URL parsing.
176    Url,
177    /// An unsuccessful HTTP request or upgrade.
178    Http,
179    /// An error in serialization or deserialization.
180    SerDe,
181    /// An error in I/O.
182    Io,
183    /// An invalid message format.
184    MessageFormat,
185    /// An error parsing a string as UTF8.
186    Utf8,
187    /// Noise framework handshake.
188    NoiseHandshake,
189    /// Tailscale challenge packet.
190    Challenge,
191    /// The user's machine was not authorized to register with a Tailnet and there is no URL for
192    /// the user to authorize at.
193    MachineAuthorization,
194}
195
196impl fmt::Display for InternalErrorKind {
197    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
198        match self {
199            InternalErrorKind::Url => write!(f, "URL parsing error"),
200            InternalErrorKind::Http => write!(f, "unsuccessful HTTP request or upgrade"),
201            InternalErrorKind::SerDe => write!(f, "serialization/deserialization error"),
202            InternalErrorKind::Io => write!(f, "I/O error"),
203            InternalErrorKind::MessageFormat => write!(f, "message format error"),
204            InternalErrorKind::Utf8 => write!(f, "invalid UTF8"),
205            InternalErrorKind::NoiseHandshake => write!(f, "error in Noise handshake"),
206            InternalErrorKind::Challenge => write!(f, "error with Tailscale challenge packet"),
207            InternalErrorKind::MachineAuthorization => {
208                write!(f, "machine not authorized to register with Tailnet")
209            }
210        }
211    }
212}
213
214/// The phase of connecting the control plane to a Tailnet in which an error occurs.
215#[derive(Debug, Clone, Copy, Eq, PartialEq)]
216pub enum Operation {
217    /// Requesting a net map.
218    MapRequest,
219    /// Connecting to a control server.
220    ConnectToControlServer,
221    /// Registering the user's device with a Tailnet.
222    Registration,
223}
224
225impl fmt::Display for Operation {
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        match self {
228            Operation::MapRequest => write!(f, "net map request"),
229            Operation::ConnectToControlServer => write!(f, "connection to control server"),
230            Operation::Registration => write!(f, "registration"),
231        }
232    }
233}
234
235impl From<ts_http_util::Error> for Error {
236    fn from(error: ts_http_util::Error) -> Self {
237        tracing::error!(%error, "http error");
238
239        if http_error_is_recoverable(error) {
240            Error::NetworkError(Operation::ConnectToControlServer)
241        } else {
242            Error::Internal(InternalErrorKind::Http, Operation::ConnectToControlServer)
243        }
244    }
245}
246
247/// Returns true if the input io error should be classed as a network error.
248fn is_network_error(err: &std::io::Error) -> bool {
249    use std::io::ErrorKind::*;
250    matches!(
251        err.kind(),
252        ConnectionRefused
253            | ConnectionReset
254            | HostUnreachable
255            | NetworkUnreachable
256            | ConnectionAborted
257            | NotConnected
258            | TimedOut
259            | AddrNotAvailable
260            | Interrupted
261            | NetworkDown
262    )
263}
264
265/// Returns true if the error is likely to be a transient network error.
266fn http_error_is_recoverable(error: ts_http_util::Error) -> bool {
267    match error {
268        ts_http_util::Error::Io => true,
269        ts_http_util::Error::InvalidInput
270        // A TCP timeout (recoverable) should get classed as an IO error, so any other kind of
271        // timeout is probably not.
272        | ts_http_util::Error::Timeout
273        | ts_http_util::Error::InvalidResponse
274        // A peer that streamed an over-cap body is an attack/misconfig signal, not a transient
275        // blip — terminal, do not retry.
276        | ts_http_util::Error::BodyTooLarge => false,
277        // In the future, this might be recoverable with a reset.
278        ts_http_util::Error::ConnectionClosed => false,
279    }
280}