diff --git a/flakehashes.json b/flakehashes.json index c4eb15084..4533b4475 100644 --- a/flakehashes.json +++ b/flakehashes.json @@ -1,6 +1,6 @@ { "vendor": { "goModSum": "sha256-6lyly8Z1qRZSnEhVANrpw+Y4yn6sY3mCbEcHjiGNa5E=", - "sri": "sha256-4KlSYC6PoRRelnk4c9f0IWfXoA8MfyNK4q6RJL1dVeU=" + "sri": "sha256-7oTXqZhMbbDJTyhHckCfTUpNfSSLTdG8+83w/91txI0=" } } diff --git a/hscontrol/app.go b/hscontrol/app.go index 17daf8bd7..27340f66a 100644 --- a/hscontrol/app.go +++ b/hscontrol/app.go @@ -52,6 +52,7 @@ import ( "github.com/sasha-s/go-deadlock" "golang.org/x/sync/errgroup" "tailscale.com/envknob" + "tailscale.com/net/memnet" "tailscale.com/tailcfg" "tailscale.com/types/key" ) @@ -65,8 +66,6 @@ var ( errEmptyInitialDERPMap = errors.New( "initial DERPMap is empty, Headscale requires at least one entry", ) - errTailSQLDatabase = errors.New("tailsql only supports sqlite") - errTailSQLAuthKey = errors.New("tailsql requires TS_AUTHKEY to be set") ) var ( @@ -117,9 +116,6 @@ type Headscale struct { var ( profilingEnabled = envknob.Bool("HEADSCALE_DEBUG_PROFILING_ENABLED") profilingPath = envknob.String("HEADSCALE_DEBUG_PROFILING_PATH") - tailsqlEnabled = envknob.Bool("HEADSCALE_DEBUG_TAILSQL_ENABLED") - tailsqlStateDir = envknob.String("HEADSCALE_DEBUG_TAILSQL_STATE_DIR") - tailsqlTSKey = envknob.String("TS_AUTHKEY") dumpConfig = envknob.Bool("HEADSCALE_DEBUG_DUMP_CONFIG") ) @@ -588,16 +584,6 @@ func (h *Headscale) Serve(ctx context.Context) error { capver.CanOldCodeBeCleanedUp() - if tailsqlEnabled { - if !h.cfg.Database.IsSQLite() { - return fmt.Errorf("%w, got %q", errTailSQLDatabase, h.cfg.Database.Type) - } - - if tailsqlTSKey == "" { - return errTailSQLAuthKey - } - } - if profilingEnabled { if profilingPath != "" { err = os.MkdirAll(profilingPath, os.ModePerm) @@ -901,13 +887,37 @@ func (h *Headscale) Serve(ctx context.Context) error { var tailsqlCancel context.CancelFunc - if tailsqlEnabled { + if h.cfg.TailSQL.Enabled { + // Embedded nodes reach control in memory: no port, and no TLS or + // proxy between them and the server. Noise encrypts the stream. + var controlNet memnet.Network + + controlLn, err := controlNet.Listen("tcp", embeddedControlAddr) + if err != nil { + return fmt.Errorf("embedded control listener: %w", err) + } + + errorGroup.Go(func() error { return httpServer.Serve(controlLn) }) + + dial := func(ctx context.Context, network, addr string) (net.Conn, error) { + if addr == embeddedControlAddr { + return controlNet.Dial(ctx, network, addr) + } + + return new(net.Dialer).DialContext(ctx, network, addr) + } + var tailsqlCtx context.Context tailsqlCtx, tailsqlCancel = context.WithCancel(ctx) errorGroup.Go(func() error { - return runTailSQLService(tailsqlCtx, util.TSLogfWrapper(), tailsqlStateDir, h.cfg.SQLitePath()) + err := runTailSQLService(tailsqlCtx, h.state, dial, "http://"+embeddedControlAddr, h.cfg.AbsPath(h.cfg.TailSQL.StateDir), h.cfg.SQLitePath()) + if err != nil { + log.Error().Err(err).Msg("tailsql stopped") + } + + return nil }) } diff --git a/hscontrol/config/default.go b/hscontrol/config/default.go index 4fe03aa32..17a404799 100644 --- a/hscontrol/config/default.go +++ b/hscontrol/config/default.go @@ -77,6 +77,7 @@ func Default() types.Config { PKCE: types.PKCEConfig{Method: types.PKCEMethodS256}, }, Taildrop: types.TaildropConfig{Enabled: true}, + TailSQL: types.TailSQLConfig{StateDir: "/var/lib/headscale/tailsql"}, CLI: types.CLIConfig{Timeout: 5 * time.Second}, Tuning: types.Tuning{ BatchChangeDelay: 800 * time.Millisecond, diff --git a/hscontrol/config/load_test.go b/hscontrol/config/load_test.go index a6ca16dfb..414a1153e 100644 --- a/hscontrol/config/load_test.go +++ b/hscontrol/config/load_test.go @@ -4226,6 +4226,9 @@ oidc: client_secret: secret pkce: method: "" +tailsql: + enabled: true + state_dir: "" ` tests := []struct { @@ -4244,6 +4247,12 @@ oidc: file: valid + " extra_records: [{name: a.example.com, type: A, value: 100.64.0.1}]\n extra_records_path: /var/lib/headscale/records.json\n", want: []string{"dns.extra_records and dns.extra_records_path are mutually exclusive"}, }, + {name: "tailsql on sqlite", file: valid + "tailsql:\n enabled: true\n"}, + { + name: "tailsql on postgres", + file: strings.Replace(valid, "type: sqlite", "type: postgres", 1) + "tailsql:\n enabled: true\n", + want: []string{"tailsql.enabled needs database.type sqlite"}, + }, { name: "every rule, in order", file: everyRule, @@ -4265,6 +4274,8 @@ oidc: "derp.server.region_id is required when the embedded DERP server is enabled", "derp.server.stun_listen_addr is required when the embedded DERP server is enabled", "database.type has an unsupported value", + "tailsql.enabled needs database.type sqlite", + "tailsql.state_dir is required when tailsql.enabled is true", "policy.mode has an unsupported value", "log.level has an unsupported value", "log.format has an unsupported value", @@ -4301,6 +4312,7 @@ oidc: "derp.server.region_id is required when the embedded DERP server is enabled", "derp.server.stun_listen_addr is required when the embedded DERP server is enabled", "database.sqlite.path is required when database.type is sqlite", + "tailsql.state_dir is required when tailsql.enabled is true", "policy.mode has an unsupported value", "log.level has an unsupported value", "log.format has an unsupported value", diff --git a/hscontrol/config/validate.go b/hscontrol/config/validate.go index 2783f404f..2e87cde56 100644 --- a/hscontrol/config/validate.go +++ b/hscontrol/config/validate.go @@ -222,6 +222,7 @@ func Validate(c *types.Config) error { validateDERP(c, v) validateDatabase(c, v) + validateTailSQL(c, v) validatePolicy(c, v) validateLog(c, v) validateMagicDNS(c, v) @@ -548,6 +549,33 @@ func validateDatabase(c *types.Config, v *configValidator) { } } +// validateTailSQL records a ConfigError when tailsql is enabled on a +// database it cannot read, or without a place to keep its identity. +func validateTailSQL(c *types.Config, v *configValidator) { + if !c.TailSQL.Enabled { + return + } + + if !c.Database.IsSQLite() { + v.Add(&types.ConfigError{ + Reason: "tailsql.enabled needs database.type sqlite", + Current: []types.KV{ + {Key: "tailsql.enabled", Value: "true"}, + {Key: "database.type", Value: string(c.Database.Type)}, + }, + Hint: "disable tailsql or use sqlite", + }) + } + + if c.TailSQL.StateDir == "" { + v.Add(&types.ConfigError{ + Reason: "tailsql.state_dir is required when tailsql.enabled is true", + Current: []types.KV{{Key: "tailsql.state_dir", Value: ""}}, + Hint: `set tailsql.state_dir, e.g. "/var/lib/headscale/tailsql"`, + }) + } +} + // validateMagicDNS records a ConfigError when MagicDNS is enabled without a // base_domain. func validateMagicDNS(c *types.Config, v *configValidator) { diff --git a/hscontrol/embedded.go b/hscontrol/embedded.go new file mode 100644 index 000000000..d025a6bcd --- /dev/null +++ b/hscontrol/embedded.go @@ -0,0 +1,205 @@ +package hscontrol + +import ( + "context" + "errors" + "fmt" + "path/filepath" + "time" + + "github.com/juanfont/headscale/hscontrol/state" + "github.com/juanfont/headscale/hscontrol/util" + "github.com/rs/zerolog/log" + "tailscale.com/client/local" + "tailscale.com/envknob" + "tailscale.com/ipn" + "tailscale.com/ipn/store" + "tailscale.com/net/netx" + "tailscale.com/tsnet" + "tailscale.com/types/key" + "tailscale.com/types/logger" + "tailscale.com/util/backoff" +) + +// An embedded node is a tsnet node headscale runs in its own process, joined +// to its own tailnet with a tagged pre-auth key it mints itself. It is the +// pattern for tailnet apps shipped inside headscale; tailsql is the first. + +// embeddedKeyTTL bounds a minted key: it is used within seconds, and a leaked +// one should not outlive the join. +const embeddedKeyTTL = 5 * time.Minute + +// embeddedControlAddr is where embedded nodes find control on headscale's +// in-memory network. It is an IP literal because tsnet resolves hostnames +// before calling SystemDial. +const embeddedControlAddr = "127.0.0.1:80" + +var errEmbeddedNeedsLogin = errors.New("embedded node needs login") + +// newEmbeddedNode starts a tsnet node named hostname with tag on headscale's +// own tailnet and keeps it joined until ctx ends. dir holds its identity; dial +// reaches the control server at controlURL. The caller closes the server. +func newEmbeddedNode( + ctx context.Context, + st *state.State, + dial netx.DialFunc, + controlURL, dir, hostname, tag string, +) (*tsnet.Server, error) { + // Headscale tells clients to stop log upload, but only once connected. + envknob.SetNoLogsNoSupport() + + logf := util.TSLogfWrapper() + + stateStore, err := store.New(logf, filepath.Join(dir, "tailscaled.state")) + if err != nil { + return nil, fmt.Errorf("opening state for %s: %w", hostname, err) + } + + // Mint only when headscale does not know this identity, so restarts do not + // leave a used key behind each time. + var authKey string + + if !embeddedNodeRegistered(st, stateStore, tag) { + warnStaleEmbeddedNodes(st, hostname, tag) + + authKey, err = mintEmbeddedKey(st, tag) + if err != nil { + return nil, err + } + } + + ts := &tsnet.Server{ + Dir: dir, + Store: stateStore, + Hostname: hostname, + ControlURL: controlURL, + AuthKey: authKey, + SystemDial: dial, + Logf: logger.Discard, + UserLogf: logf, + } + + _, err = ts.Up(ctx) + if err != nil { + ts.Close() + + return nil, fmt.Errorf("joining %s to the tailnet: %w", hostname, err) + } + + go keepEmbeddedNodeJoined(ctx, st, ts, tag) + + return ts, nil +} + +// embeddedNodeRegistered reports whether headscale holds a node with tag for +// the machine key in stateStore. +func embeddedNodeRegistered(st *state.State, stateStore ipn.StateStore, tag string) bool { + raw, err := stateStore.ReadState(ipn.MachineKeyStateKey) + if err != nil { + return false + } + + var mk key.MachinePrivate + + err = mk.UnmarshalText(raw) + if err != nil { + return false + } + + for _, nv := range st.GetNodesByMachineKeyAllUsers(mk.Public()) { + if nv.HasTag(tag) { + return true + } + } + + return false +} + +func mintEmbeddedKey(st *state.State, tag string) (string, error) { + exp := time.Now().Add(embeddedKeyTTL) + + pak, err := st.CreatePreAuthKey(nil, false, false, &exp, []string{tag}) + if err != nil { + return "", fmt.Errorf("minting key for %s: %w", tag, err) + } + + return pak.Key, nil +} + +// warnStaleEmbeddedNodes names nodes left from a lost identity: the new node +// cannot take their name, so it registers as hostname-1. +func warnStaleEmbeddedNodes(st *state.State, hostname, tag string) { + for _, nv := range st.ListNodes().All() { + if nv.HasTag(tag) && nv.Hostname() == hostname { + log.Warn(). + Uint64("node.id", nv.ID().Uint64()). + Str("node.name", nv.GivenName()). + Msgf("%s registers a new identity; delete the old node to free its name", hostname) + } + } +} + +// keepEmbeddedNodeJoined re-joins the node when control forgets it, such as +// after an admin deletes it. tsnet does not re-login on its own. +func keepEmbeddedNodeJoined(ctx context.Context, st *state.State, ts *tsnet.Server, tag string) { + lc, err := ts.LocalClient() + if err != nil { + log.Error().Err(err).Msg("embedded node: local client") + + return + } + + bo := backoff.NewBackoff("embedded-node", util.TSLogfWrapper(), 5*time.Minute) + + for ctx.Err() == nil { + err := watchEmbeddedNode(ctx, lc, bo, func() error { + k, err := mintEmbeddedKey(st, tag) + if err != nil { + return err + } + + return lc.Start(ctx, ipn.Options{AuthKey: k}) + }) + if ctx.Err() != nil { + return + } + + log.Warn().Err(err).Str("tag", tag).Msg("embedded node: watch ended, retrying") + bo.BackOff(ctx, err) + } +} + +func watchEmbeddedNode(ctx context.Context, lc *local.Client, bo *backoff.Backoff, rejoin func() error) error { + w, err := lc.WatchIPNBus(ctx, ipn.NotifyInitialState) + if err != nil { + return err + } + defer w.Close() + + for { + n, err := w.Next() + if err != nil { + return err + } + + if n.State == nil { + continue + } + + if *n.State == ipn.Running { + bo.BackOff(ctx, nil) + + continue + } + + if *n.State == ipn.NeedsLogin { + // Space attempts out: a rejected key leads straight back here. + bo.BackOff(ctx, errEmbeddedNeedsLogin) + + err := rejoin() + if err != nil { + log.Error().Err(err).Msg("embedded node: rejoining") + } + } + } +} diff --git a/hscontrol/embedded_test.go b/hscontrol/embedded_test.go new file mode 100644 index 000000000..3d10a3004 --- /dev/null +++ b/hscontrol/embedded_test.go @@ -0,0 +1,128 @@ +package hscontrol_test + +import ( + "context" + "errors" + "fmt" + "net" + "strings" + "testing" + "time" + + "github.com/juanfont/headscale/hscontrol" + "github.com/juanfont/headscale/hscontrol/servertest" + "github.com/juanfont/headscale/hscontrol/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "tailscale.com/tsnet" +) + +var errUnexpectedDial = errors.New("unexpected system dial") + +const ( + embeddedHostname = "tailsql" + embeddedTag = "tag:tailsql" +) + +// TestEmbeddedNode proves an embedded node joins headscale's own tailnet over +// memnet, keeps its identity across restarts without minting a new key, and +// re-joins under its name after an admin deletes it. +func TestEmbeddedNode(t *testing.T) { + srv := servertest.NewServer(t) + dir := t.TempDir() + controlAddr := strings.TrimPrefix(srv.URL, "http://") + + // Control is the only thing reached through SystemDial in this test. + dial := func(ctx context.Context, network, addr string) (net.Conn, error) { + if addr == controlAddr { + return srv.MemNet().Dial(ctx, network, addr) + } + + return nil, fmt.Errorf("%w to %s", errUnexpectedDial, addr) + } + + start := func(t *testing.T) (*tsnet.Server, context.CancelFunc) { + t.Helper() + + // The context bounds the node's whole life, rejoin watcher included. + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) + + ts, err := hscontrol.NewEmbeddedNode(ctx, srv.State(), dial, srv.URL, dir, embeddedHostname, embeddedTag) + require.NoError(t, err) + + return ts, func() { + cancel() + ts.Close() + } + } + + embeddedNodes := func() []types.NodeView { + var out []types.NodeView + + for _, nv := range srv.State().ListNodes().All() { + if nv.HasTag(embeddedTag) { + out = append(out, nv) + } + } + + return out + } + + keyCount := func(t *testing.T) int { + t.Helper() + + keys, err := srv.State().ListPreAuthKeys() + require.NoError(t, err) + + return len(keys) + } + + var firstID types.NodeID + + t.Run("join", func(t *testing.T) { + _, stop := start(t) + defer stop() + + nodes := embeddedNodes() + require.Len(t, nodes, 1) + assert.Equal(t, embeddedHostname, nodes[0].GivenName()) + assert.True(t, nodes[0].IsTagged()) + assert.False(t, nodes[0].UserID().Valid(), "an embedded node belongs to no user") + + firstID = nodes[0].ID() + }) + + t.Run("restart_keeps_identity", func(t *testing.T) { + keysBefore := keyCount(t) + + _, stop := start(t) + defer stop() + + nodes := embeddedNodes() + require.Len(t, nodes, 1) + assert.Equal(t, firstID, nodes[0].ID()) + assert.Equal(t, keysBefore, keyCount(t), "a known identity must not mint a key") + }) + + t.Run("rejoins_after_delete", func(t *testing.T) { + _, stop := start(t) + defer stop() + + nv, ok := srv.State().GetNodeByID(firstID) + require.True(t, ok) + + changes, err := srv.State().DeleteNode(nv) + require.NoError(t, err) + srv.App.Change(changes...) + + assert.EventuallyWithT(t, func(c *assert.CollectT) { + nodes := embeddedNodes() + if !assert.Len(c, nodes, 1) { + return + } + + assert.NotEqual(c, firstID, nodes[0].ID()) + assert.Equal(c, embeddedHostname, nodes[0].GivenName()) + }, 60*time.Second, 200*time.Millisecond, "deleted embedded node must re-join under its name") + }) +} diff --git a/hscontrol/export_test.go b/hscontrol/export_test.go new file mode 100644 index 000000000..d9e980cf2 --- /dev/null +++ b/hscontrol/export_test.go @@ -0,0 +1,5 @@ +package hscontrol + +var NewEmbeddedNode = newEmbeddedNode + +var RunTailSQLService = runTailSQLService diff --git a/hscontrol/tailsql.go b/hscontrol/tailsql.go index 14e5f58f7..4856e4273 100644 --- a/hscontrol/tailsql.go +++ b/hscontrol/tailsql.go @@ -4,119 +4,129 @@ import ( "context" "errors" "fmt" + "net" "net/http" - "os" + "regexp" + "time" "github.com/juanfont/headscale/hscontrol/db/sqliteconfig" + "github.com/juanfont/headscale/hscontrol/state" + "github.com/juanfont/headscale/hscontrol/util" + "github.com/rs/zerolog/log" + "github.com/tailscale/tailsql/authorizer" "github.com/tailscale/tailsql/server/tailsql" - "tailscale.com/tsnet" - "tailscale.com/tsweb" - "tailscale.com/types/logger" + "tailscale.com/net/netx" ) -// ErrNoCertDomains is returned when no cert domains are available for HTTPS. -var ErrNoCertDomains = errors.New("no cert domains available for HTTPS") +const ( + tailsqlHostname = "tailsql" + tailsqlTag = "tag:tailsql" +) -func runTailSQLService(ctx context.Context, logf logger.Logf, stateDir, dbPath string) error { - dsn, err := (&sqliteconfig.Config{ - Path: dbPath, - WALAutocheckpoint: -1, // not set - ReadOnly: true, - }).ToURL() +var errTailSQLStatementDenied = errors.New("statement not allowed") + +// tailsqlDenied matches statements that write despite a read-only connection: +// ATTACH and VACUUM INTO create files, PRAGMA can lift query_only. Table-valued +// pragma_* functions stay allowed; \b does not split on "_". +var tailsqlDenied = regexp.MustCompile(`(?i)\b(attach|vacuum|pragma)\b`) + +func checkTailSQLQuery(q tailsql.Query) (tailsql.Query, error) { + q, err := tailsql.DefaultCheckQuery(q) if err != nil { - return fmt.Errorf("building sqlite connection URL: %w", err) + return q, err } - opts := tailsql.Options{ - Hostname: "tailsql-headscale", - StateDir: stateDir, - Sources: []tailsql.DBSpec{ - { - Source: "headscale", - Label: "headscale - sqlite", - Driver: "sqlite", - URL: dsn, - Named: map[string]string{ - "schema": `select * from sqlite_schema`, - }, + if m := tailsqlDenied.FindString(q.Query); m != "" { + return q, fmt.Errorf("%w: %s", errTailSQLStatementDenied, m) + } + + return q, nil +} + +// runTailSQLService serves a read-only SQL UI over the database at dbPath as +// a tagged node on headscale's own tailnet, until ctx ends. +func runTailSQLService( + ctx context.Context, + st *state.State, + dial netx.DialFunc, + controlURL, stateDir, dbPath string, +) error { + logf := util.TSLogfWrapper() + + dsn, err := sqliteconfig.ReadOnly(dbPath).ToURL() + if err != nil { + return fmt.Errorf("tailsql database url: %w", err) + } + + ts, err := newEmbeddedNode(ctx, st, dial, controlURL, stateDir, tailsqlHostname, tailsqlTag) + if err != nil { + return err + } + defer ts.Close() + + lc, err := ts.LocalClient() + if err != nil { + return fmt.Errorf("tailsql local client: %w", err) + } + + tsql, err := tailsql.NewServer(tailsql.Options{ + LocalClient: lc, + Authorize: authorizer.ACLGrants(logf), + CheckQuery: checkTailSQLQuery, + Sources: []tailsql.DBSpec{{ + Source: "headscale", + Label: "headscale - sqlite", + Driver: "sqlite", + URL: dsn, + Named: map[string]string{ + "schema": `select * from sqlite_schema`, }, - }, - } - - tsNode := &tsnet.Server{ - Dir: os.ExpandEnv(opts.StateDir), - Hostname: opts.Hostname, - Logf: logger.Discard, - } - defer tsNode.Close() - - logf("Starting tailscale (hostname=%q)", opts.Hostname) - - lc, err := tsNode.LocalClient() - if err != nil { - return fmt.Errorf("connect local client: %w", err) - } - - opts.LocalClient = lc // for authentication - - // Make sure the Tailscale node starts up. It might not, if it is a new node - // and the user did not provide an auth key. - if st, err := tsNode.Up(ctx); err != nil { //nolint:noinlineerr - return fmt.Errorf("starting tailscale: %w", err) - } else { - logf("tailscale started, node state %q", st.BackendState) - } - - // Reaching here, we have a running Tailscale node, now we can set up the - // HTTP and/or HTTPS plumbing for TailSQL itself. - tsql, err := tailsql.NewServer(opts) + }}, + }) if err != nil { return fmt.Errorf("creating tailsql server: %w", err) } + defer tsql.Close() - lst, err := tsNode.Listen("tcp", ":80") + ln80, err := ts.Listen("tcp", ":80") if err != nil { - return fmt.Errorf("listen port 80: %w", err) + return fmt.Errorf("tailsql listen :80: %w", err) } - if opts.ServeHTTPS { - // When serving TLS, add a redirect from HTTP on port 80 to HTTPS on 443. - certDomains := tsNode.CertDomains() - if len(certDomains) == 0 { - return ErrNoCertDomains - } + var ( + ln = ln80 + url = "http://" + tailsqlHostname + ) - base := "https://" + certDomains[0] + // Headscale sends cert domains only with MagicDNS and dns.certificates. + if domains := ts.CertDomains(); len(domains) > 0 { + url = "https://" + domains[0] - go func() { - _ = http.Serve(lst, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { //nolint:gosec - target := base + r.RequestURI - http.Redirect(w, r, target, http.StatusPermanentRedirect) //nolint:gosec // G710: target prefixed by trusted base URL - })) - }() - - // For the real service, start a separate listener. - // Note: Replaces the port 80 listener. - var err error - - lst, err = tsNode.ListenTLS("tcp", ":443") + ln, err = ts.ListenTLS("tcp", ":443") if err != nil { - return fmt.Errorf("listen TLS: %w", err) + return fmt.Errorf("tailsql listen :443: %w", err) } - logf("enabled serving via HTTPS") + go serveTailSQL(ln80, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Redirect(w, r, url+r.RequestURI, http.StatusPermanentRedirect) //nolint:gosec // G710: url is a trusted cert domain + })) } - mux := tsql.NewMux() - tsweb.Debugger(mux) + go serveTailSQL(ln, tsql.NewMux()) - go func() { - _ = http.Serve(lst, mux) //nolint:gosec - }() + ip4, ip6 := ts.TailscaleIPs() + log.Info(). + Str("url", url). + Stringer("ipv4", ip4). + Stringer("ipv6", ip6). + Msgf("tailsql ready; grant %s the app capability tailscale.com/cap/tailsql to use it", tailsqlTag) - logf("TailSQL started") <-ctx.Done() - logf("TailSQL shutting down...") - return tsNode.Close() + return nil +} + +func serveTailSQL(ln net.Listener, h http.Handler) { + srv := &http.Server{Handler: h, ReadHeaderTimeout: 10 * time.Second} + _ = srv.Serve(ln) } diff --git a/hscontrol/tailsql_access_test.go b/hscontrol/tailsql_access_test.go new file mode 100644 index 000000000..2c1a4bdf5 --- /dev/null +++ b/hscontrol/tailsql_access_test.go @@ -0,0 +1,215 @@ +package hscontrol_test + +import ( + "context" + "database/sql" + "fmt" + "net" + "net/http" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/juanfont/headscale/hscontrol" + "github.com/juanfont/headscale/hscontrol/db/sqliteconfig" + "github.com/juanfont/headscale/hscontrol/dns/dnstest" + "github.com/juanfont/headscale/hscontrol/servertest" + "github.com/juanfont/headscale/hscontrol/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "tailscale.com/tsnet" + "tailscale.com/types/logger" +) + +// tailsqlPolicy is the policy config-example.yaml documents, plus a +// network-only grant for bob. +const tailsqlPolicy = `{ + "tagOwners": { "tag:tailsql": [] }, + "grants": [ + { + "src": ["alice@"], + "dst": ["tag:tailsql"], + "ip": ["tcp:80", "tcp:443"], + "app": { "tailscale.com/cap/tailsql": [{ "src": ["headscale"] }] } + }, + { "src": ["bob@"], "dst": ["tag:tailsql"], "ip": ["tcp:80"] } + ] +}` + +type tailsqlEnv struct { + srv *servertest.TestServer + dial func(ctx context.Context, network, addr string) (net.Conn, error) + ip string +} + +// startTailSQL runs tailsql on srv's tailnet under tailsqlPolicy and waits +// for its node to register. +func startTailSQL(t *testing.T, srv *servertest.TestServer) *tailsqlEnv { + t.Helper() + + controlAddr := strings.TrimPrefix(srv.URL, "http://") + env := &tailsqlEnv{srv: srv} + + env.dial = func(ctx context.Context, network, addr string) (net.Conn, error) { + if addr == controlAddr { + return srv.MemNet().Dial(ctx, network, addr) + } + + return new(net.Dialer).DialContext(ctx, network, addr) + } + + changed, err := srv.State().SetPolicy([]byte(tailsqlPolicy)) + require.NoError(t, err) + + if changed { + changes, err := srv.State().ReloadPolicy() + require.NoError(t, err) + srv.App.Change(changes...) + } + + dbPath := filepath.Join(t.TempDir(), "headscale.db") + dbURL, err := sqliteconfig.Default(dbPath).ToURL() + require.NoError(t, err) + + db, err := sql.Open("sqlite", dbURL) + require.NoError(t, err) + + _, err = db.ExecContext(t.Context(), "CREATE TABLE t (v INTEGER)") + require.NoError(t, err) + require.NoError(t, db.Close()) + + ctx, cancel := context.WithTimeout(t.Context(), 2*time.Minute) + t.Cleanup(cancel) + + go func() { + err := hscontrol.RunTailSQLService(ctx, srv.State(), env.dial, srv.URL, t.TempDir(), dbPath) + assert.NoError(t, err) + }() + + require.EventuallyWithT(t, func(c *assert.CollectT) { + for _, nv := range srv.State().ListNodes().All() { + if nv.HasTag("tag:tailsql") && nv.IPv4().Valid() { + env.ip = nv.IPv4().Get().String() + } + } + + assert.NotEmpty(c, env.ip) + }, 30*time.Second, 100*time.Millisecond) + + return env +} + +// client joins a node for user and returns an HTTP client on the tailnet. +func (env *tailsqlEnv) client(t *testing.T, name string, user *types.User) *http.Client { + t.Helper() + + ts := &tsnet.Server{ + Dir: t.TempDir(), + Hostname: name, + ControlURL: env.srv.URL, + AuthKey: env.srv.CreatePreAuthKey(t, types.UserID(user.ID)), + SystemDial: env.dial, + Logf: logger.Discard, + } + t.Cleanup(func() { ts.Close() }) + + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + + _, err := ts.Up(ctx) + require.NoError(t, err) + + hc := ts.HTTPClient() + hc.Timeout = 5 * time.Second + + return hc +} + +// get returns the status code and Location header of a tailsql request. +func (env *tailsqlEnv) get(ctx context.Context, hc *http.Client, path string) (int, string, error) { + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://%s%s", env.ip, path), nil) + if err != nil { + return 0, "", err + } + + req.Header.Set("Sec-Tailsql", "1") + + resp, err := hc.Do(req) + if err != nil { + return 0, "", err + } + defer resp.Body.Close() + + return resp.StatusCode, resp.Header.Get("Location"), nil +} + +const tailsqlQueryPath = "/json?src=headscale&q=select+count(*)+from+t" + +// TestTailSQLAccess proves the documented policy is accepted and is the only +// way in: the app capability allows a query, network access alone is refused, +// and no grant cannot connect. +func TestTailSQLAccess(t *testing.T) { + srv := servertest.NewServer(t) + alice := srv.CreateUser(t, "alice") + bob := srv.CreateUser(t, "bob") + carol := srv.CreateUser(t, "carol") + env := startTailSQL(t, srv) + + status := func(c *assert.CollectT, hc *http.Client, want int) { + code, _, err := env.get(t.Context(), hc, tailsqlQueryPath) + if assert.NoError(c, err) { + assert.Equal(c, want, code) + } + } + + t.Run("app_capability_allows", func(t *testing.T) { + hc := env.client(t, "alice-laptop", alice) + + assert.EventuallyWithT(t, func(c *assert.CollectT) { + status(c, hc, http.StatusOK) + }, 60*time.Second, 500*time.Millisecond) + }) + + t.Run("network_only_is_forbidden", func(t *testing.T) { + hc := env.client(t, "bob-laptop", bob) + + assert.EventuallyWithT(t, func(c *assert.CollectT) { + status(c, hc, http.StatusForbidden) + }, 60*time.Second, 500*time.Millisecond) + }) + + t.Run("no_grant_cannot_connect", func(t *testing.T) { + hc := env.client(t, "carol-laptop", carol) + + _, _, err := env.get(t.Context(), hc, tailsqlQueryPath) + assert.Error(t, err) + }) +} + +// TestTailSQLHTTPSRedirect proves tailsql moves to HTTPS by itself when +// headscale issues node certificates: port 80 redirects to the cert domain. +// Issuing the certificate needs ACME, so 443 itself is not exercised. +func TestTailSQLHTTPSRedirect(t *testing.T) { + const domain = "ts.example.com" + + srv := servertest.NewServer(t, + servertest.WithMagicDNS(domain), + servertest.WithCertificates(&dnstest.Provider{}), + ) + alice := srv.CreateUser(t, "alice") + env := startTailSQL(t, srv) + + hc := env.client(t, "alice-laptop", alice) + hc.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } + + assert.EventuallyWithT(t, func(c *assert.CollectT) { + code, location, err := env.get(t.Context(), hc, tailsqlQueryPath) + if !assert.NoError(c, err) { + return + } + + assert.Equal(c, http.StatusPermanentRedirect, code) + assert.Equal(c, "https://tailsql."+domain+tailsqlQueryPath, location) + }, 60*time.Second, 500*time.Millisecond) +} diff --git a/hscontrol/tailsql_test.go b/hscontrol/tailsql_test.go new file mode 100644 index 000000000..c09932eaf --- /dev/null +++ b/hscontrol/tailsql_test.go @@ -0,0 +1,94 @@ +package hscontrol + +import ( + "database/sql" + "os" + "path/filepath" + "testing" + + "github.com/juanfont/headscale/hscontrol/db/sqliteconfig" + "github.com/stretchr/testify/require" + "github.com/tailscale/tailsql/server/tailsql" +) + +// TestTailSQLReadOnly runs what a tailsql user could send through the same +// check and connection tailsql uses: nothing may change the database or +// create a file. +func TestTailSQLReadOnly(t *testing.T) { + dir := t.TempDir() + dbPath := filepath.Join(dir, "headscale.db") + + rwURL, err := sqliteconfig.Default(dbPath).ToURL() + require.NoError(t, err) + + rw, err := sql.Open("sqlite", rwURL) + require.NoError(t, err) + + defer rw.Close() + + _, err = rw.ExecContext(t.Context(), "CREATE TABLE t (v INTEGER); INSERT INTO t VALUES (1)") + require.NoError(t, err) + + roURL, err := sqliteconfig.ReadOnly(dbPath).ToURL() + require.NoError(t, err) + + ro, err := sql.Open("sqlite", roURL) + require.NoError(t, err) + + defer ro.Close() + + conn, err := ro.Conn(t.Context()) + require.NoError(t, err) + + defer conn.Close() + + attachPath := filepath.Join(dir, "attached.db") + vacuumPath := filepath.Join(dir, "copy.db") + + writes := []string{ + "INSERT INTO t VALUES (2)", + "UPDATE t SET v = 3", + "DELETE FROM t", + "DROP TABLE t", + "CREATE TABLE x (a)", + "pragma query_only = 0", + "SELECT 1; PRAGMA query_only=0", + "ATTACH DATABASE 'file:" + attachPath + "?mode=rwc' AS x", + "attach '" + attachPath + "' as x", + "VACUUM INTO '" + vacuumPath + "'", + "DELETE FROM t", + } + for _, q := range writes { + _, err := checkTailSQLQuery(tailsql.Query{Source: "headscale", Query: q}) + if err != nil { + continue + } + + _, err = conn.ExecContext(t.Context(), q) + require.Error(t, err, "%q passed the check and ran on the read-only connection", q) + } + + var n int + + require.NoError(t, conn.QueryRowContext(t.Context(), "SELECT count(*) FROM t WHERE v = 1").Scan(&n)) + require.Equal(t, 1, n, "table changed") + + for _, p := range []string{attachPath, vacuumPath} { + _, err := os.Stat(p) + require.ErrorIs(t, err, os.ErrNotExist, "read-only path created %s", p) + } + + reads := []string{ + "select * from sqlite_schema", + "SELECT * FROM pragma_table_info('t')", + } + for _, q := range reads { + _, err := checkTailSQLQuery(tailsql.Query{Source: "headscale", Query: q}) + require.NoError(t, err, q) + + var rows int + + err = conn.QueryRowContext(t.Context(), "SELECT count(*) FROM ("+q+")").Scan(&rows) + require.NoError(t, err, q) + } +} diff --git a/hscontrol/types/config.go b/hscontrol/types/config.go index b4cda6b28..79d1d3143 100644 --- a/hscontrol/types/config.go +++ b/hscontrol/types/config.go @@ -247,6 +247,16 @@ type Config struct { //nolint:recvcheck // MarshalJSON reads a value, so a Confi // AutoUpdate is the tailnet-wide default for client auto-updates. AutoUpdate AutoUpdateConfig `koanf:"auto_update"` + // TailSQL is [tailsql](https://github.com/tailscale/tailsql), a + // read-only SQL web UI over the headscale database, served as the node + // `tailsql` with `tag:tailsql` on headscale's own tailnet. Headscale + // mints its credential, joins it in memory and re-joins it if the node + // is deleted. Nobody can query it until the policy lists + // `"tag:tailsql": []` in `tagOwners` and a grant to `tag:tailsql` gives + // `ip` `tcp:80` (and `tcp:443` with `dns.certificates`) and `app` + // `{"tailscale.com/cap/tailsql": [{"src": ["headscale"]}]}`. + TailSQL TailSQLConfig `koanf:"tailsql"` + // CLI is how the headscale CLI reaches the server: the local // `unix_socket` without authentication, or a remote `cli.address` // with `cli.api_key`. The CLI reads these keys from its own @@ -844,6 +854,16 @@ type TaildropConfig struct { Enabled bool `koanf:"enabled"` } +// TailSQLConfig controls the embedded TailSQL node. +type TailSQLConfig struct { + // Enabled runs tailsql. It needs `database.type` sqlite. + Enabled bool `koanf:"enabled"` + + // StateDir holds the node's identity. Losing it registers a new + // node, `tailsql-1`, and leaves the old one for an admin to delete. + StateDir string `example:"\"/srv/headscale/tailsql\"" koanf:"state_dir"` +} + // AutoUpdateConfig controls the tailnet-wide default for client // auto-update. When Enabled is true, headscale emits the // [tailcfg.NodeAttrDefaultAutoUpdate] cap with value [true] on every diff --git a/hscontrol/types/config_fields_test.go b/hscontrol/types/config_fields_test.go index 2cd60224c..11dacf4e8 100644 --- a/hscontrol/types/config_fields_test.go +++ b/hscontrol/types/config_fields_test.go @@ -133,6 +133,8 @@ func TestConfigFields(t *testing.T) { "logtail.enabled", "taildrop.enabled", "auto_update.enabled", + "tailsql.enabled", + "tailsql.state_dir", "cli.address", "cli.api_key", "cli.timeout", @@ -231,6 +233,7 @@ func TestConfigTree(t *testing.T) { "logtail", "taildrop", "auto_update", + "tailsql", "cli", "tuning", } diff --git a/hscontrol/util/zlog/zf/fields.go b/hscontrol/util/zlog/zf/fields.go index 33ec8b33d..7ccab4786 100644 --- a/hscontrol/util/zlog/zf/fields.go +++ b/hscontrol/util/zlog/zf/fields.go @@ -201,5 +201,4 @@ const ( DebugDumpConfig = "HEADSCALE_DEBUG_DUMP_CONFIG" DebugHighCardinalityMetric = "HEADSCALE_DEBUG_HIGH_CARDINALITY_METRICS" DebugProfilingEnabled = "HEADSCALE_DEBUG_PROFILING_ENABLED" - DebugTailSQLEnabled = "HEADSCALE_DEBUG_TAILSQL_ENABLED" )