diff --git a/docs/DOCUMENTATION.md b/docs/DOCUMENTATION.md index df05958..6541e19 100644 --- a/docs/DOCUMENTATION.md +++ b/docs/DOCUMENTATION.md @@ -135,7 +135,7 @@ Each browser profile has its own Tailscale identity. Different profiles can use ### Identity & Configuration - Create, switch, and delete multiple Tailscale profiles (identities). -- Point a profile at a self-hosted HTTP(S) control server such as Headscale. Changing servers signs the profile out and starts a new login on the new server. +- Point a profile at a self-hosted HTTP(S) control server such as Headscale. Changing servers starts a fresh login on the new server and keeps the previous account in Profiles. The previous server does not need to be reachable. - Shields Up blocks all incoming connections. - Run as Exit Node advertises this browser node as an exit node. - Login and logout authenticate with Tailscale. Login URLs must match allowed origins. @@ -237,7 +237,7 @@ interface StatusUpdate { When `NeedsLogin` is active, the extension opens a validated `browseToURL` immediately when available. If the URL is missing and the helper advertises `supportsLogin`, the extension sends `login`, waits for a fresh `browseToURL` or `authURL`, validates the URL, and then opens it. -`set-prefs.prefs.controlURL` uses an empty string for Tailscale's default control plane and an HTTP(S) URL for a custom server. The helper validates the URL at the native-message boundary. A confirmed change clears server-scoped exit-node state, logs out the old identity, restarts with the new prefs, and requires a fresh login; failures attempt to restore the previous server. +`set-prefs.prefs.controlURL` uses an empty string for Tailscale's default control plane and an HTTP(S) URL for a custom server. The helper validates the URL and preferences before switching to an empty local profile. The new profile clears server-scoped exit-node state and requires a fresh login. The previous account remains in Profiles, and failures attempt to restore its identity and preferences. Switching does not require remote logout. Settings for the pending login survive a helper restart. If a status payload would exceed the browser's 1 MiB native-message limit, the helper removes peers from the end until it fits and sets `peersTruncated` plus `totalPeers`. The popup displays a health warning instead of silently losing all status updates on very large tailnets. @@ -381,6 +381,8 @@ The native host is a Go binary at `host/` using `tailscale.com/tsnet` pinned to | `proxy.go` / `proxy_policy.go` | SOCKS5/HTTP multiplexing, authenticated destination policy, lazy quad-100 web client, and buffered CONNECT tunneling | | `dns.go` / `exit_dns.go` | Restricted split-DNS forwarding and exit-node DNS behavior | | `profiles.go` | Profile management through the current local-client snapshot | +| `saved_prefs.go` | Loads saved profile preferences before tsnet startup and persists settings for pending logins | +| `control_url.go` | Changes coordination servers using a fresh local profile, with rollback to the previous account | | `taildrop.go` | Chunk reassembly, asynchronous cancellable `PushFile`, progress, and cleanup | | `install.go` / `install_*.go` | Cross-platform native host installation and cleanup, including Chrome Flatpak sandbox state and registration | | `peers.go` | Peer/status conversion from Tailscale types | @@ -397,6 +399,8 @@ The native host is a Go binary at `host/` using `tailscale.com/tsnet` pinned to 5. **Host reads commands** in a loop from stdin, dispatches to handlers, and writes replies to stdout. 6. **On stdin EOF** (browser closed), the host cancels the watcher and active Taildrop transfers, closes the tsnet server, and exits cleanly. +Before starting tsnet, the host reads the selected account's saved preferences and supplies its coordination server, hostname, and advertised tags. It restores subnet-route acceptance, DNS, Shields Up, LAN access, SSH, and advertised routes before publishing the session to the proxy and status watcher. New browser profiles accept subnet routes by default. The extension supplies the startup connection intent and restores its selected exit node after the account is running. An unreadable preference record stops initialization instead of replacing the saved settings with defaults. + ### Proxy Architecture The proxy uses Tailscale's `proxymux.SplitSOCKSAndHTTP()` to multiplex a single listener: diff --git a/host/control_url.go b/host/control_url.go new file mode 100644 index 0000000..de7bb5c --- /dev/null +++ b/host/control_url.go @@ -0,0 +1,88 @@ +package main + +import ( + "context" + "fmt" + "net/netip" + "time" + + "tailscale.com/client/local" + "tailscale.com/ipn" +) + +// switchControlURL starts a fresh local profile without requiring the previous +// control server to acknowledge logout. Keep the previous profile unchanged so +// a failed switch can restore its identity as well as its preferences. +func (h *Host) switchControlURL(lc *local.Client, partial partialPrefsUpdate) error { + finish := h.beginProxyProfileChange(lc) + defer finish() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + + // Re-read after draining web mutations and stopping startup correction. + currentPrefs, err := lc.GetPrefs(ctx) + if err != nil { + return fmt.Errorf("failed to get current prefs: %w", err) + } + mp, changed, err := maskedPrefsForUpdate(partial, currentPrefs) + if err != nil { + return err + } + if !changed { + updated, err := lc.EditPrefs(ctx, mp) + if err != nil { + return fmt.Errorf("failed to set prefs: %w", err) + } + return h.savePendingProfilePrefs(lc, updated, false) + } + current, _, err := lc.ProfileStatus(ctx) + if err != nil { + return fmt.Errorf("failed to read current profile: %w", err) + } + updated := currentPrefs.Clone() + updated.ApplyEdits(mp) + updated.Persist = nil + updated.ProfileName = "" + updated.LoggedOut = false + updated.ExitNodeID = "" + updated.ExitNodeIP = netip.Addr{} + updated.AutoExitNode = "" + updated.InternalExitNodePrior = "" + if err := lc.CheckPrefs(ctx, updated); err != nil { + return fmt.Errorf("failed to set prefs: %w", err) + } + + rollback := func(cause error) error { + rollbackCtx, rollbackCancel := context.WithTimeout(context.Background(), 30*time.Second) + defer rollbackCancel() + var restoreErr error + if current.ID != "" { + restoreErr = lc.SwitchProfile(rollbackCtx, current.ID) + } else { + restoreErr = lc.SwitchToEmptyProfile(rollbackCtx) + if restoreErr == nil { + restoreErr = h.savePendingProfilePrefs(lc, currentPrefs, true) + } + if restoreErr == nil { + restoreErr = lc.Start(rollbackCtx, ipn.Options{UpdatePrefs: currentPrefs}) + } + } + if restoreErr != nil { + h.clearCachedStatus(nil) + return fmt.Errorf("failed to change control server: %w; also failed to restore previous profile: %v", cause, restoreErr) + } + h.clearCachedStatus(currentPrefs) + return fmt.Errorf("failed to change control server: %w; restored previous profile", cause) + } + if err := lc.SwitchToEmptyProfile(ctx); err != nil { + return rollback(err) + } + if err := h.savePendingProfilePrefs(lc, updated, true); err != nil { + return rollback(fmt.Errorf("failed to save pending profile: %w", err)) + } + if err := lc.Start(ctx, ipn.Options{UpdatePrefs: updated}); err != nil { + return rollback(err) + } + h.clearCachedStatus(updated) + return nil +} diff --git a/host/host.go b/host/host.go index cddd501..7dc406d 100644 --- a/host/host.go +++ b/host/host.go @@ -95,6 +95,10 @@ type Host struct { // proxyDial is a test seam; production leaves it nil and uses tsnet. proxyDial func(context.Context, string, string) (net.Conn, error) + + // stateDirForProfile is a test seam for exercising init with isolated state. + // Production leaves it nil and uses the normal per-browser state directory. + stateDirForProfile func(string) (string, error) } // newHost creates a new Host that reads from r and writes to w. @@ -362,6 +366,7 @@ func (h *Host) handleRequestLocked(req Request) { } } +// startupPrefs supplies defaults only when the profile has no saved settings. func startupPrefs() *ipn.MaskedPrefs { return &ipn.MaskedPrefs{ Prefs: ipn.Prefs{ @@ -419,16 +424,17 @@ func (h *Host) handleInit(req Request) { h.cancelTransfers() h.clearCachedStatus(nil) - homeDir, err := os.UserHomeDir() - if err != nil { - h.send(Reply{ - Cmd: "init", - Init: &InitReply{Error: fmt.Sprintf("failed to get home dir: %v", err)}, - }) - return + stateDirForProfile := h.stateDirForProfile + if stateDirForProfile == nil { + stateDirForProfile = func(initID string) (string, error) { + homeDir, err := os.UserHomeDir() + if err != nil { + return "", fmt.Errorf("failed to get home dir: %w", err) + } + return hostStateDir(homeDir, initID) + } } - - stateDir, err := hostStateDir(homeDir, req.InitID) + stateDir, err := stateDirForProfile(req.InitID) if err != nil { h.send(Reply{ Cmd: "init", @@ -444,11 +450,10 @@ func (h *Host) handleInit(req Request) { return } - server := &tsnet.Server{ - Dir: stateDir, - Hostname: "browser-ext", - RunWebClient: true, - Logf: log.Printf, + server, saved, err := newProfileServer(stateDir) + if err != nil { + h.send(Reply{Cmd: "init", Init: &InitReply{Error: err.Error()}}) + return } if err := server.Start(); err != nil { @@ -469,16 +474,15 @@ func (h *Host) handleInit(req Request) { return } - // tsnet does not accept subnet routes by default. Tailchrome's proxy rules - // are built from accepted PrimaryRoutes, so enable route acceptance before - // publishing the first status update. + // tsnet.Start resets preferences. Restore the saved settings before making + // the session available to the proxy or publishing its first status. prefsCtx, prefsCancel := context.WithTimeout(context.Background(), 10*time.Second) - _, err = lc.EditPrefs(prefsCtx, startupPrefs()) + _, err = lc.EditPrefs(prefsCtx, restoredStartupPrefs(saved)) prefsCancel() if err != nil { h.send(Reply{ Cmd: "init", - Init: &InitReply{Error: fmt.Sprintf("failed to accept subnet routes: %v", err)}, + Init: &InitReply{Error: fmt.Sprintf("failed to apply startup prefs: %v", err)}, }) server.Close() return @@ -945,72 +949,22 @@ func (h *Host) handleSetPrefs(req Request) { h.cancelStartupCorrection() } if controlURLChanged { - finishProfileChange := h.beginProxyProfileChange(lc) - defer finishProfileChange() - } - - updatedPrefs, err := lc.EditPrefs(ctx, mp) - if err != nil { - h.sendError("set-prefs", fmt.Sprintf("failed to set prefs: %v", err)) - return - } - - if controlURLChanged { - // Exit-node selection and node identity are scoped to the previous - // tailnet; clear them so a now-invalid ExitNodeID (a StableNodeID from - // the old control server) isn't carried onto the new one. - updatedPrefs.ExitNodeID = "" - updatedPrefs.ExitNodeIP = netip.Addr{} - - h.clearCachedStatus(updatedPrefs) - - // Explicitly log out so the previous control plane's node key and - // profile identity are discarded. Without this, restarting with the - // new ControlURL would carry the old identity to the new server and - // the IPN engine could skip the interactive login prompt. - logoutCtx, logoutCancel := context.WithTimeout(context.Background(), 10*time.Second) - if err := lc.Logout(logoutCtx); err != nil { - logoutCancel() - log.Printf("logout during controlURL change failed, restoring previous URL: %v", err) - - rollbackCtx, rollbackCancel := context.WithTimeout(context.Background(), 30*time.Second) - rollbackErr := lc.Start(rollbackCtx, ipn.Options{UpdatePrefs: currentPrefs}) - rollbackCancel() - if rollbackErr != nil { - h.clearCachedStatus(currentPrefs) - h.sendError("set-prefs", fmt.Sprintf("failed to logout before changing control URL: %v; also failed to restore previous control URL: %v", err, rollbackErr)) - return - } - - h.clearCachedStatus(currentPrefs) + if err := h.switchControlURL(lc, partial); err != nil { h.handleGetStatus() - h.sendError("set-prefs", fmt.Sprintf("failed to logout before changing control URL: %v; restored previous control URL", err)) + h.sendError("set-prefs", err.Error()) return } - logoutCancel() - - restartCtx, restartCancel := context.WithTimeout(context.Background(), 30*time.Second) - if err := lc.Start(restartCtx, ipn.Options{UpdatePrefs: updatedPrefs}); err != nil { - restartCancel() - log.Printf("restart with updated control URL failed, restoring previous URL: %v", err) - - rollbackCtx, rollbackCancel := context.WithTimeout(context.Background(), 30*time.Second) - rollbackErr := lc.Start(rollbackCtx, ipn.Options{UpdatePrefs: currentPrefs}) - rollbackCancel() - if rollbackErr != nil { - h.clearCachedStatus(currentPrefs) - h.sendError("set-prefs", fmt.Sprintf("failed to restart with updated control URL: %v; also failed to restore previous control URL: %v", err, rollbackErr)) - return - } - - h.clearCachedStatus(currentPrefs) - h.handleGetStatus() - // The logout above already discarded the previous session, so the - // prefs are restored but the node is signed out and must log in again. - h.sendError("set-prefs", fmt.Sprintf("failed to switch control server: %v; reverted to your previous server, but you have been signed out and must log in again", err)) + h.handleListProfiles() + } else { + updatedPrefs, err := lc.EditPrefs(ctx, mp) + if err != nil { + h.sendError("set-prefs", fmt.Sprintf("failed to set prefs: %v", err)) + return + } + if err := h.savePendingProfilePrefs(lc, updatedPrefs, false); err != nil { + h.sendError("set-prefs", fmt.Sprintf("failed to save pending profile: %v", err)) return } - restartCancel() } h.handleGetStatus() diff --git a/host/profile_prefs_integration_test.go b/host/profile_prefs_integration_test.go new file mode 100644 index 0000000..5773637 --- /dev/null +++ b/host/profile_prefs_integration_test.go @@ -0,0 +1,295 @@ +package main + +import ( + "bytes" + "context" + "encoding/json" + "net" + "net/http" + "net/http/httptest" + "path/filepath" + "slices" + "sync" + "testing" + "time" + + "tailscale.com/client/local" + "tailscale.com/net/netns" + "tailscale.com/tstest/integration/testcontrol" + "tailscale.com/types/logger" +) + +func newPrefsTestControl(t *testing.T, requireAuth bool) (*testcontrol.Server, func()) { + t.Helper() + control := &testcontrol.Server{DERPMap: splitDNSTestDERP(t), RequireAuth: requireAuth, Logf: logger.Discard} + server := httptest.NewUnstartedServer(control) + control.HTTPTestServer = server + var connections sync.Map + server.Config.ConnState = func(conn net.Conn, state http.ConnState) { + if state == http.StateNew { + connections.Store(conn, struct{}{}) + } + if state == http.StateClosed { + connections.Delete(conn) + } + } + server.Start() + stop := func() { + server.Listener.Close() + // HTTP shutdown alone leaves the hijacked control connections alive. + connections.Range(func(conn, _ any) bool { conn.(net.Conn).Close(); return true }) + server.Close() + } + t.Cleanup(stop) + return control, stop +} + +func prefsTestRequest(t *testing.T, h *Host, request Request) []Reply { + t.Helper() + payload, err := json.Marshal(request) + if err != nil { + t.Fatal(err) + } + var input bytes.Buffer + appendNativeMessage(t, &input, payload) + h.stdin = &input + h.readMessages() + h.mu.Lock() + replies := decodeAllReplies(t, h.stdout.(*bytes.Buffer)) + h.mu.Unlock() + for _, reply := range replies { + if reply.Error != nil { + t.Fatalf("%s failed: %s", request.Cmd, reply.Error.Message) + } + if reply.Init != nil && reply.Init.Error != "" { + t.Fatalf("init failed: %s", reply.Init.Error) + } + } + return replies +} + +func initPrefsTestHost(t *testing.T, root, id string, wantRunning bool) *Host { + t.Helper() + h := newHost(nil, new(bytes.Buffer)) + h.stateDirForProfile = func(id string) (string, error) { return filepath.Join(root, id), nil } + t.Cleanup(h.shutdownSession) + replies := prefsTestRequest(t, h, Request{Cmd: "init", InitID: id, WantRunning: &wantRunning}) + if !slices.ContainsFunc(replies, func(r Reply) bool { return r.Init != nil }) || h.ts == nil { + t.Fatal("init did not acknowledge an active session") + } + return h +} + +func TestInitRestoresSavedProfilePrefs(t *testing.T) { + if testing.Short() { + t.Skip("starts an embedded tailnet node") + } + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + netns.SetEnabled(false) + t.Cleanup(func() { netns.SetEnabled(true) }) + control, _ := newPrefsTestControl(t, false) + controlURL := control.HTTPTestServer.URL + t.Setenv("TS_CONTROL_URL", controlURL) + root := t.TempDir() + first := initPrefsTestHost(t, root, "browser-a", true) + before, err := first.ts.Up(ctx) + if err != nil { + t.Fatal(err) + } + fresh, err := first.lc.GetPrefs(ctx) + if err != nil { + t.Fatal(err) + } + if !fresh.RouteAll { + t.Fatal("new browser profile does not accept subnet routes") + } + prefsTestRequest(t, first, Request{Cmd: "set-prefs", Prefs: json.RawMessage(`{ + "hostname":"work-browser", "routeAll":false, "corpDNS":false, + "shieldsUp":true, "exitNodeAllowLANAccess":true, + "advertiseRoutes":["10.9.0.0/24","fd00:9::/64"], "advertiseExitNode":true + }`)}) + saved, err := first.lc.GetPrefs(ctx) + if err != nil { + t.Fatal(err) + } + first.shutdownSession() + + // A saved server must win over the environment before the first connection. + fallback := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + t.Error("restarted profile contacted the fallback coordination server") + w.WriteHeader(http.StatusServiceUnavailable) + })) + t.Cleanup(fallback.Close) + t.Setenv("TS_CONTROL_URL", fallback.URL) + for _, wantRunning := range []bool{true, false} { + restarted := initPrefsTestHost(t, root, "browser-a", wantRunning) + if !wantRunning { + select { + case <-restarted.correctionDone: + case <-ctx.Done(): + t.Fatal("startup did not apply wantRunning=false") + } + } + got, err := restarted.lc.GetPrefs(ctx) + if err != nil { + t.Fatal(err) + } + if got.ControlURL != controlURL || got.Hostname != "work-browser" || got.RouteAll || got.CorpDNS || !got.ShieldsUp || !got.ExitNodeAllowLANAccess || got.WantRunning != wantRunning { + t.Fatalf("startup did not restore saved preferences: %s", got.Pretty()) + } + if !slices.Equal(got.AdvertiseRoutes, saved.AdvertiseRoutes) || !got.AdvertisesExitNode() { + t.Fatalf("advertised routes after restart = %v, want %v", got.AdvertiseRoutes, saved.AdvertiseRoutes) + } + if wantRunning { + after, err := restarted.ts.Up(ctx) + if err != nil { + t.Fatal(err) + } + if after.Self.PublicKey != before.Self.PublicKey { + t.Fatal("restart changed the profile's node identity") + } + } else { + prefsTestRequest(t, restarted, Request{Cmd: "set-prefs", Prefs: json.RawMessage(`{"hostname":""}`)}) + } + restarted.shutdownSession() + } + cleared := initPrefsTestHost(t, root, "browser-a", false) + prefs, err := cleared.lc.GetPrefs(ctx) + if err != nil { + t.Fatal(err) + } + if prefs.Hostname != "" { + t.Fatal("restart replaced an explicitly cleared hostname") + } +} + +func TestControlURLSwitchPreservesProfilesWithoutRemoteLogout(t *testing.T) { + if testing.Short() { + t.Skip("starts embedded tailnet nodes") + } + netns.SetEnabled(false) + t.Cleanup(func() { netns.SetEnabled(true) }) + for _, offline := range []bool{false, true} { + name := "previous-server-online" + if offline { + name = "previous-server-offline" + } + t.Run(name, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + previous, stopPrevious := newPrefsTestControl(t, false) + next, _ := newPrefsTestControl(t, true) + t.Setenv("TS_CONTROL_URL", previous.HTTPTestServer.URL) + root := t.TempDir() + h := initPrefsTestHost(t, root, "browser", true) + before, err := h.ts.Up(ctx) + if err != nil { + t.Fatal(err) + } + prefsTestRequest(t, h, Request{Cmd: "set-prefs", Prefs: json.RawMessage(`{"hostname":"previous-browser","shieldsUp":true}`)}) + oldProfile, _, err := h.lc.ProfileStatus(ctx) + if err != nil || oldProfile.ID == "" { + t.Fatalf("initial profile not saved: %v", err) + } + if offline { + stopPrevious() + } + payload, err := json.Marshal(map[string]string{"controlURL": next.HTTPTestServer.URL}) + if err != nil { + t.Fatal(err) + } + started := time.Now() + prefsTestRequest(t, h, Request{Cmd: "set-prefs", Prefs: payload}) + if time.Since(started) > 5*time.Second { + t.Fatal("changing servers waited for the old server") + } + current, all, err := h.lc.ProfileStatus(ctx) + if err != nil { + t.Fatal(err) + } + if current.ID != "" || len(all) != 1 || all[0].ID != oldProfile.ID || all[0].ControlURL != oldProfile.ControlURL { + t.Fatal("switch did not preserve the old account and select a fresh login") + } + prefs, err := h.lc.GetPrefs(ctx) + if err != nil { + t.Fatal(err) + } + if prefs.ControlURL != next.HTTPTestServer.URL || (prefs.Persist != nil && prefs.Persist.NodeID != "") || prefs.ExitNodeID != "" || prefs.ExitNodeIP.IsValid() { + t.Fatal("new server inherited the old account or exit node") + } + // Edits made before the new login must also survive a helper restart. + prefsTestRequest(t, h, Request{Cmd: "set-prefs", Prefs: json.RawMessage(`{"hostname":"pending-browser","routeAll":false,"corpDNS":false}`)}) + h.shutdownSession() + h = initPrefsTestHost(t, root, "browser", true) + prefs, err = h.lc.GetPrefs(ctx) + if err != nil { + t.Fatal(err) + } + if prefs.ControlURL != next.HTTPTestServer.URL || prefs.Hostname != "pending-browser" || prefs.RouteAll || prefs.CorpDNS || !prefs.ShieldsUp { + t.Fatal("restart lost the pending server or preferences") + } + loginURL := prefsTestLoginURL(t, ctx, h.lc) + if !next.CompleteAuth(loginURL) { + t.Fatal("new server did not issue a fresh login") + } + after, err := h.ts.Up(ctx) + if err != nil { + t.Fatal(err) + } + if after.Self.PublicKey == before.Self.PublicKey { + t.Fatal("control server change reused the old node identity") + } + + // The registered new account supersedes pending settings on restart. + h.shutdownSession() + h = initPrefsTestHost(t, root, "browser", true) + afterRestart, err := h.ts.Up(ctx) + if err != nil { + t.Fatal(err) + } + if afterRestart.Self.PublicKey != after.Self.PublicKey { + t.Fatal("pending preferences discarded the completed login") + } + + // Returning to the previous account restores its own settings. + prefsTestRequest(t, h, Request{Cmd: "switch-profile", ProfileID: string(oldProfile.ID)}) + prefs, err = h.lc.GetPrefs(ctx) + if err != nil { + t.Fatal(err) + } + if prefs.ControlURL != previous.HTTPTestServer.URL || prefs.Hostname != "previous-browser" || !prefs.ShieldsUp { + t.Fatal("changing servers modified the previous account") + } + if !offline { + restored, err := h.ts.Up(ctx) + if err != nil { + t.Fatal(err) + } + if restored.Self.PublicKey != before.Self.PublicKey { + t.Fatal("returning to the previous account required a new identity") + } + } + }) + } +} + +func prefsTestLoginURL(t *testing.T, ctx context.Context, lc *local.Client) string { + t.Helper() + ticker := time.NewTicker(10 * time.Millisecond) + defer ticker.Stop() + for { + status, err := lc.StatusWithoutPeers(ctx) + if err != nil { + t.Fatal(err) + } + if status.AuthURL != "" { + return status.AuthURL + } + select { + case <-ticker.C: + case <-ctx.Done(): + t.Fatal("timed out waiting for the new server's login URL") + } + } +} diff --git a/host/profiles.go b/host/profiles.go index 9a7ba46..1e166da 100644 --- a/host/profiles.go +++ b/host/profiles.go @@ -78,6 +78,10 @@ func (h *Host) handleNewProfile() { h.sendError("new-profile", fmt.Sprintf("failed to create new profile: %v", err)) return } + if err := h.savePendingProfilePrefs(lc, nil, true); err != nil { + h.sendError("new-profile", fmt.Sprintf("failed to save new profile: %v", err)) + return + } // Send updated profiles after creating. h.handleListProfiles() diff --git a/host/saved_prefs.go b/host/saved_prefs.go new file mode 100644 index 0000000..e24c414 --- /dev/null +++ b/host/saved_prefs.go @@ -0,0 +1,171 @@ +package main + +import ( + "encoding/json" + "errors" + "fmt" + "log" + "path/filepath" + + "tailscale.com/client/local" + "tailscale.com/ipn" + "tailscale.com/ipn/store" + "tailscale.com/tsnet" +) + +// Tailscale saves a profile's preferences only after its first successful login. +// Keep settings for the pending login in the same state store, without keys or +// account identity. A persisted current profile always takes precedence. +const pendingProfilePrefsKey ipn.StateKey = "tailchrome-pending-prefs" + +// loadSavedProfilePrefs reads the active profile before tsnet.Start replaces +// its preferences. tsnet uses CurrentProfileStateKey on every platform, including +// Windows (LocalBackendStartKeyOSNeutral). +func loadSavedProfilePrefs(st ipn.StateStore) (*ipn.Prefs, error) { + current, err := st.ReadState(ipn.CurrentProfileStateKey) + if err != nil && !errors.Is(err, ipn.ErrStateNotExist) { + return nil, fmt.Errorf("reading current profile: %w", err) + } + key := pendingProfilePrefsKey + if len(current) != 0 { + key = ipn.StateKey(current) + raw, err := st.ReadState(ipn.KnownProfilesStateKey) + if errors.Is(err, ipn.ErrStateNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("reading known profiles: %w", err) + } + var profiles map[ipn.ProfileID]ipn.LoginProfile + if err := json.Unmarshal(raw, &profiles); err != nil { + return nil, fmt.Errorf("parsing known profiles: %w", err) + } + found := false + for _, profile := range profiles { + if profile.Key == key { + found = true + break + } + } + if !found { + // Match Tailscale's fallback for a deleted or unknown profile. + return nil, nil + } + } + raw, err := st.ReadState(key) + if errors.Is(err, ipn.ErrStateNotExist) { + return nil, nil + } + if err != nil { + return nil, fmt.Errorf("reading saved prefs: %w", err) + } + if len(raw) == 0 { + return nil, nil + } + // Config holds the node identity and may contain a platform-specific TPM + // key. Let Tailscale decode it; only restore user preferences here. + var fields map[string]json.RawMessage + if err := json.Unmarshal(raw, &fields); err != nil { + return nil, fmt.Errorf("parsing saved prefs: %w", err) + } + if fields == nil { + return nil, fmt.Errorf("saved prefs must be a JSON object") + } + delete(fields, "Config") + raw, err = json.Marshal(fields) + if err != nil { + return nil, err + } + prefs := ipn.NewPrefs() + if err := json.Unmarshal(raw, prefs); err != nil { + return nil, fmt.Errorf("parsing saved prefs: %w", err) + } + return prefs, nil +} + +func newProfileServer(stateDir string) (*tsnet.Server, *ipn.Prefs, error) { + st, err := store.New(log.Printf, filepath.Join(stateDir, "tailscaled.state")) + if err != nil { + return nil, nil, fmt.Errorf("failed to open state: %w", err) + } + saved, err := loadSavedProfilePrefs(st) + if err != nil { + // Do not start on a different server or overwrite unreadable settings. + return nil, nil, fmt.Errorf("failed to load saved prefs: %w", err) + } + server := &tsnet.Server{ + Dir: stateDir, Store: st, Hostname: "browser-ext", + RunWebClient: true, Logf: log.Printf, + } + if saved != nil { + if saved.Hostname != "" { + server.Hostname = saved.Hostname + } + server.ControlURL = saved.ControlURL + if isDefaultControlURL(server.ControlURL) { + // An explicitly saved default must not fall back to TS_CONTROL_URL. + server.ControlURL = ipn.DefaultControlURL + } + server.AdvertiseTags = saved.AdvertiseTags + } + return server, saved, nil +} + +func restoredStartupPrefs(saved *ipn.Prefs) *ipn.MaskedPrefs { + if saved == nil { + return startupPrefs() + } + // ControlURL and Hostname reach tsnet before it connects. The extension + // supplies WantRunning and restores the exit-node selection for the account. + return &ipn.MaskedPrefs{ + Prefs: ipn.Prefs{ + RouteAll: saved.RouteAll, CorpDNS: saved.CorpDNS, + ShieldsUp: saved.ShieldsUp, RunSSH: saved.RunSSH, + Hostname: saved.Hostname, + ExitNodeAllowLANAccess: saved.ExitNodeAllowLANAccess, + AdvertiseRoutes: saved.AdvertiseRoutes, + }, + RouteAllSet: true, CorpDNSSet: true, ShieldsUpSet: true, RunSSHSet: true, HostnameSet: true, + ExitNodeAllowLANAccessSet: true, AdvertiseRoutesSet: true, + } +} + +// savePendingProfilePrefs complements Tailscale's persistence for a profile +// that has not logged in yet. A new login or a switch to an existing account +// writes CurrentProfileStateKey and supersedes this pending configuration. +// reset is used only after switching to an empty profile, before starting login. +func (h *Host) savePendingProfilePrefs(lc *local.Client, prefs *ipn.Prefs, reset bool) error { + server, currentClient, _ := h.sessionSnapshot() + if server == nil || server.Store == nil || currentClient != lc { + return nil + } + st := server.Store + if !reset { + current, err := st.ReadState(ipn.CurrentProfileStateKey) + if err != nil && !errors.Is(err, ipn.ErrStateNotExist) { + return err + } + if len(current) != 0 { + return nil + } + } + var data []byte + if prefs != nil { + saved := prefs.Clone() + saved.Persist = nil + var err error + data, err = json.Marshal(saved) + if err != nil { + return err + } + } + if err := st.WriteState(pendingProfilePrefsKey, data); err != nil { + return err + } + if reset { + // SwitchToEmptyProfile leaves the previous startup profile selected on + // disk. Clear only that pointer; retain the account for switching back. + return st.WriteState(ipn.CurrentProfileStateKey, nil) + } + return nil +} diff --git a/host/saved_prefs_test.go b/host/saved_prefs_test.go new file mode 100644 index 0000000..a7b628d --- /dev/null +++ b/host/saved_prefs_test.go @@ -0,0 +1,196 @@ +package main + +import ( + "bytes" + "errors" + "os" + "path/filepath" + "strings" + "testing" + + "tailscale.com/client/local" + "tailscale.com/ipn" + "tailscale.com/ipn/store" + "tailscale.com/ipn/store/mem" + "tailscale.com/tsnet" + "tailscale.com/types/key" + "tailscale.com/types/logger" + "tailscale.com/types/persist" +) + +func writePrefsTestState(t *testing.T, st ipn.StateStore, entries map[ipn.StateKey]string) { + t.Helper() + for key, value := range entries { + if err := st.WriteState(key, []byte(value)); err != nil { + t.Fatal(err) + } + } +} + +func TestLoadSavedProfilePrefs(t *testing.T) { + const known = `{"a":{"ID":"a","Key":"profile-a"},"b":{"ID":"b","Key":"profile-b"}}` + for _, tc := range []struct { + name, current, known, raw, pending, wantHostname string + wantError bool + }{ + {name: "new browser profile"}, + {name: "selected account", current: "profile-b", known: known, raw: `{"Hostname":"selected"}`, wantHostname: "selected"}, + {name: "deleted account", current: "profile-deleted", known: known}, + {name: "missing account prefs", current: "profile-b", known: known}, + {name: "pending login", pending: `{"Hostname":"pending"}`, wantHostname: "pending"}, + {name: "account supersedes pending login", current: "profile-b", known: known, raw: `{"Hostname":"selected"}`, pending: `{"Hostname":"pending"}`, wantHostname: "selected"}, + {name: "ignore identity and TPM data", current: "profile-b", known: known, raw: `{"Hostname":"selected","Config":{"AttestationKey":{"platform":"specific"}}}`, wantHostname: "selected"}, + {name: "invalid known profiles", current: "profile-b", known: `{`, wantError: true}, + {name: "invalid account prefs", current: "profile-b", known: known, raw: `{"ShieldsUp":"invalid"}`, wantError: true}, + {name: "invalid pending prefs", pending: `null`, wantError: true}, + } { + t.Run(tc.name, func(t *testing.T) { + st := new(mem.Store) + entries := map[ipn.StateKey]string{"profile-a": `{"Hostname":"other-account"}`} + if tc.current != "" { + entries[ipn.CurrentProfileStateKey] = tc.current + } + if tc.known != "" { + entries[ipn.KnownProfilesStateKey] = tc.known + } + if tc.raw != "" { + entries["profile-b"] = tc.raw + } + if tc.pending != "" { + entries[pendingProfilePrefsKey] = tc.pending + } + writePrefsTestState(t, st, entries) + got, err := loadSavedProfilePrefs(st) + if (err != nil) != tc.wantError { + t.Fatalf("error = %v, wantError = %v", err, tc.wantError) + } + if tc.wantError { + return + } + if tc.wantHostname == "" { + if got != nil { + t.Fatal("restored preferences for an absent profile") + } + return + } + if got == nil || got.Hostname != tc.wantHostname || got.Persist != nil { + t.Fatal("did not restore only the selected profile's preferences") + } + }) + } +} + +type failingPrefsStore struct { + ipn.StateStore + readKey, writeKey ipn.StateKey +} + +func (s failingPrefsStore) ReadState(key ipn.StateKey) ([]byte, error) { + if key == s.readKey { + return nil, errors.New("state read failed") + } + return s.StateStore.ReadState(key) +} + +func (s failingPrefsStore) WriteState(key ipn.StateKey, data []byte) error { + if key == s.writeKey { + return errors.New("state write failed") + } + return s.StateStore.WriteState(key, data) +} + +func TestLoadSavedProfilePrefsReportsReadErrors(t *testing.T) { + for _, key := range []ipn.StateKey{ipn.CurrentProfileStateKey, ipn.KnownProfilesStateKey, "profile-a"} { + t.Run(string(key), func(t *testing.T) { + st := new(mem.Store) + writePrefsTestState(t, st, map[ipn.StateKey]string{ + ipn.CurrentProfileStateKey: "profile-a", + ipn.KnownProfilesStateKey: `{"a":{"Key":"profile-a"}}`, + "profile-a": `{"ShieldsUp":true}`, + }) + if _, err := loadSavedProfilePrefs(failingPrefsStore{StateStore: st, readKey: key}); err == nil { + t.Fatal("state read error was treated as a new profile") + } + }) + } +} + +func TestSavedDefaultControlURLOverridesEnvironment(t *testing.T) { + t.Setenv("TS_CONTROL_URL", "https://environment.example.com") + for _, raw := range []string{`""`, `"https://controlplane.tailscale.com"`, `"https://login.tailscale.com"`} { + t.Run(raw, func(t *testing.T) { + dir := t.TempDir() + st, err := store.New(logger.Discard, filepath.Join(dir, "tailscaled.state")) + if err != nil { + t.Fatal(err) + } + writePrefsTestState(t, st, map[ipn.StateKey]string{pendingProfilePrefsKey: `{"ControlURL":` + raw + `}`}) + server, _, err := newProfileServer(dir) + if err != nil { + t.Fatal(err) + } + if server.ControlURL != ipn.DefaultControlURL { + t.Fatalf("saved default changed to %q", server.ControlURL) + } + }) + } +} + +func TestPendingProfilePrefsDoNotStoreIdentity(t *testing.T) { + st := new(mem.Store) + lc := &local.Client{} + h := newHost(nil, nil) + h.ts, h.lc = &tsnet.Server{Store: st}, lc + writePrefsTestState(t, st, map[ipn.StateKey]string{ipn.CurrentProfileStateKey: "old-profile"}) + prefs := &ipn.Prefs{ControlURL: "https://headscale.example.com", ShieldsUp: true, + Persist: &persist.Persist{PrivateNodeKey: key.NewNode(), NodeID: "old-node"}} + if err := h.savePendingProfilePrefs(lc, prefs, true); err != nil { + t.Fatal(err) + } + raw, err := st.ReadState(pendingProfilePrefsKey) + if err != nil { + t.Fatal(err) + } + if bytes.Contains(raw, []byte("old-node")) || bytes.Contains(raw, []byte("privkey:")) { + t.Fatal("pending profile contains credentials or account identity") + } + saved, err := loadSavedProfilePrefs(st) + if err != nil { + t.Fatal(err) + } + if saved == nil || saved.Persist != nil || !saved.ShieldsUp || saved.ControlURL != prefs.ControlURL { + t.Fatal("pending login preferences were not retained") + } + if prefs.Persist == nil { + t.Fatal("saving preferences mutated the caller's identity") + } +} + +func TestInitRejectsCorruptSavedPrefs(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "tailscaled.state") + st, err := store.New(logger.Discard, path) + if err != nil { + t.Fatal(err) + } + writePrefsTestState(t, st, map[ipn.StateKey]string{pendingProfilePrefsKey: `{"ShieldsUp":"invalid"}`}) + before, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + var output bytes.Buffer + h := newHost(nil, &output) + h.stateDirForProfile = func(string) (string, error) { return dir, nil } + h.handleRequest(Request{Cmd: "init", InitID: "test"}) + reply := decodeReply(t, &output) + if reply.Init == nil || !strings.Contains(reply.Init.Error, "failed to load saved prefs") || h.ts != nil { + t.Fatal("init started a node after failing to read saved preferences") + } + after, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(before, after) { + t.Fatal("failed init overwrote the saved state") + } +} diff --git a/host/web_control_url_test.go b/host/web_control_url_test.go index b20cdb9..bcc3968 100644 --- a/host/web_control_url_test.go +++ b/host/web_control_url_test.go @@ -7,6 +7,7 @@ import ( "net" "net/http" "net/http/httptest" + "net/netip" "slices" "strings" "testing" @@ -16,8 +17,11 @@ import ( "tailscale.com/client/web" "tailscale.com/ipn" "tailscale.com/ipn/ipnstate" + "tailscale.com/ipn/store/mem" "tailscale.com/tailcfg" + "tailscale.com/tsnet" "tailscale.com/types/logger" + "tailscale.com/types/persist" ) func TestControlURLChangeInvalidatesWebSession(t *testing.T) { @@ -25,24 +29,33 @@ func TestControlURLChangeInvalidatesWebSession(t *testing.T) { for _, tc := range []struct { name, currentURL, requestedURL, failAt, wantError string changesSession bool + anonymous bool wantMutations []string }{ {name: "new server", currentURL: oldURL, requestedURL: newURL, changesSession: true, - wantMutations: []string{"edit", "logout", "start " + newURL}}, + wantMutations: []string{"new-profile", "start " + newURL}}, {name: "same server", currentURL: oldURL, requestedURL: oldURL, wantMutations: []string{"edit"}}, {name: "equivalent server URL", currentURL: oldURL, requestedURL: "https://OLD.example.com:443/", wantMutations: []string{"edit"}}, {name: "default server alias", currentURL: "", requestedURL: "https://login.tailscale.com", wantMutations: []string{"edit"}}, - {name: "edit fails", currentURL: oldURL, requestedURL: newURL, changesSession: true, failAt: "edit", + {name: "edit fails", currentURL: oldURL, requestedURL: oldURL, failAt: "edit", wantMutations: []string{"edit"}, wantError: "failed to set prefs"}, - {name: "logout fails", currentURL: oldURL, requestedURL: newURL, changesSession: true, failAt: "logout", - wantMutations: []string{"edit", "logout", "start " + oldURL}, wantError: "restored previous control URL"}, + {name: "invalid prefs", currentURL: oldURL, requestedURL: newURL, changesSession: true, failAt: "check", + wantError: "failed to set prefs"}, + {name: "profile lookup fails", currentURL: oldURL, requestedURL: newURL, changesSession: true, failAt: "profiles", + wantError: "failed to read current profile"}, + {name: "new profile fails", currentURL: oldURL, requestedURL: newURL, changesSession: true, failAt: "new-profile", + wantMutations: []string{"new-profile", "switch old"}, wantError: "restored previous profile"}, + {name: "saving pending prefs fails", currentURL: oldURL, requestedURL: newURL, changesSession: true, failAt: "save", + wantMutations: []string{"new-profile", "switch old"}, wantError: "failed to save pending profile"}, {name: "restart fails", currentURL: oldURL, requestedURL: newURL, changesSession: true, failAt: "restart", - wantMutations: []string{"edit", "logout", "start " + newURL, "start " + oldURL}, wantError: "reverted to your previous server"}, + wantMutations: []string{"new-profile", "start " + newURL, "switch old"}, wantError: "restored previous profile"}, + {name: "restart fails before first login", currentURL: oldURL, requestedURL: newURL, changesSession: true, anonymous: true, failAt: "restart", + wantMutations: []string{"new-profile", "start " + newURL, "new-profile", "start " + oldURL}, wantError: "restored previous profile"}, {name: "rollback also fails", currentURL: oldURL, requestedURL: newURL, changesSession: true, failAt: "rollback", - wantMutations: []string{"edit", "logout", "start " + newURL, "start " + oldURL}, wantError: "also failed to restore previous control URL"}, + wantMutations: []string{"new-profile", "start " + newURL, "switch old"}, wantError: "also failed to restore previous profile"}, } { t.Run(tc.name, func(t *testing.T) { var output bytes.Buffer @@ -51,6 +64,11 @@ func TestControlURLChangeInvalidatesWebSession(t *testing.T) { h.watchCancel = watchCancel mutations := make(chan string, 4) watcherStarted := make(chan struct{}, 1) + currentPrefs := &ipn.Prefs{ + ControlURL: tc.currentURL, ProfileName: "work", Hostname: "work-browser", ShieldsUp: true, + ExitNodeID: "old-exit", ExitNodeIP: netip.MustParseAddr("100.64.0.1"), + AutoExitNode: "any", InternalExitNodePrior: "old-exit", Persist: &persist.Persist{NodeID: "old-node"}, + } checkSessionBeforeMutation := func(mutation string) { t.Helper() h.sessionMu.RLock() @@ -81,7 +99,7 @@ func TestControlURLChangeInvalidatesWebSession(t *testing.T) { switch r.URL.Path { case "/localapi/v0/prefs": if r.Method == http.MethodGet { - json.NewEncoder(w).Encode(&ipn.Prefs{ControlURL: tc.currentURL}) + json.NewEncoder(w).Encode(currentPrefs) return } checkSessionBeforeMutation("edit") @@ -94,13 +112,51 @@ func TestControlURLChangeInvalidatesWebSession(t *testing.T) { t.Error(err) } json.NewEncoder(w).Encode(&prefs.Prefs) - case "/localapi/v0/logout": - checkSessionBeforeMutation("logout") - if tc.failAt == "logout" { - http.Error(w, "logout failed", http.StatusInternalServerError) + case "/localapi/v0/check-prefs": + var prefs ipn.Prefs + if err := json.NewDecoder(r.Body).Decode(&prefs); err != nil { + t.Error(err) + } + if prefs.Persist != nil || prefs.ProfileName != "" || prefs.ExitNodeID != "" || prefs.ExitNodeIP.IsValid() || prefs.AutoExitNode != "" || prefs.InternalExitNodePrior != "" { + t.Error("server switch carried identity or exit-node settings to the new profile") + } + if prefs.ControlURL != newURL || prefs.Hostname != "work-browser" || !prefs.ShieldsUp { + t.Error("server switch lost device preferences") + } + if tc.failAt == "check" { + http.Error(w, "invalid prefs", http.StatusBadRequest) + } + case "/localapi/v0/profiles/current": + if tc.failAt == "profiles" { + http.Error(w, "profile lookup failed", http.StatusInternalServerError) + return + } + profile := ipn.LoginProfile{ID: "old", Name: "work"} + if tc.anonymous { + profile = ipn.LoginProfile{} + } + json.NewEncoder(w).Encode(profile) + case "/localapi/v0/profiles/": + if r.Method == http.MethodGet { + json.NewEncoder(w).Encode([]ipn.LoginProfile{{ID: "old", Name: "work"}}) + return + } + checkSessionBeforeMutation("new-profile") + if tc.failAt == "new-profile" { + http.Error(w, "new profile failed", http.StatusInternalServerError) + return + } + w.WriteHeader(http.StatusCreated) + case "/localapi/v0/profiles/old": + checkSessionBeforeMutation("switch old") + if tc.failAt == "rollback" { + http.Error(w, "profile restore failed", http.StatusInternalServerError) return } w.WriteHeader(http.StatusNoContent) + case "/localapi/v0/logout": + t.Error("changing servers must not depend on remote logout") + http.Error(w, "old server unreachable", http.StatusGatewayTimeout) case "/localapi/v0/start": var opts ipn.Options if err := json.NewDecoder(r.Body).Decode(&opts); err != nil || opts.UpdatePrefs == nil { @@ -143,6 +199,9 @@ func TestControlURLChangeInvalidatesWebSession(t *testing.T) { t.Fatal(err) } h.lc = lc + if tc.failAt == "save" { + h.ts = &tsnet.Server{Store: failingPrefsStore{StateStore: new(mem.Store), writeKey: pendingProfilePrefsKey}} + } h.sessionGeneration = 7 cache := &webServerCache{client: lc, generation: 7, server: server} h.webCache = cache diff --git a/packages/shared/src/popup/components/coordination-server-row.ts b/packages/shared/src/popup/components/coordination-server-row.ts index 867cc98..bb85cdc 100644 --- a/packages/shared/src/popup/components/coordination-server-row.ts +++ b/packages/shared/src/popup/components/coordination-server-row.ts @@ -110,7 +110,7 @@ export function createCoordinationServerRow( input.disabled = !supported; save.disabled = !supported; note.textContent = supported - ? "Leave blank for the default Tailscale server. Saving signs you out and requires a new login." + ? "Leave blank for the default Tailscale server. Changing servers requires a new login." : "Update the native helper to change the coordination server."; }