diff --git a/hscontrol/api/v2/README.md b/hscontrol/api/v2/README.md index 64273edcd..d6730c3b2 100644 --- a/hscontrol/api/v2/README.md +++ b/hscontrol/api/v2/README.md @@ -18,6 +18,11 @@ headscale's own conventions. The headscale-native admin API stays at `/api/v1` ## Conventions - Operations derived from Tailscale carry the `Tailscale compat` tag. +- Operations on undocumented Tailscale paths do not carry it, since their wire + format cannot be checked. `POST /device/{id}/update-client` + (`updateDeviceClient`) is one: the Tailscale admin console calls it to start + a client update, which reaches the node as c2n `POST /update`. Its request + and response shapes are headscale's own. - The `{tailnet}` path segment must be `-` (the single Headscale tailnet); anything else is `404`. See `requireDefaultTailnet`. - Errors use **Tailscale's** body (`{"message","data","status"}`), installed as diff --git a/hscontrol/api/v2/c2n.go b/hscontrol/api/v2/c2n.go new file mode 100644 index 000000000..3ad852961 --- /dev/null +++ b/hscontrol/api/v2/c2n.go @@ -0,0 +1,83 @@ +package apiv2 + +import ( + "bufio" + "bytes" + "context" + "net/http" + "net/url" + "time" + + "github.com/danielgtaylor/huma/v2" + "github.com/juanfont/headscale/hscontrol/types" + "github.com/juanfont/headscale/hscontrol/types/change" + "tailscale.com/tailcfg" +) + +// c2nTimeout bounds how long a c2n request waits for the node to answer. +// For an update, the node replies once the update has started, not finished. +const c2nTimeout = 30 * time.Second + +// sendC2N sends a POST to path on the node's c2n handler, carried in a +// [tailcfg.PingRequest], and waits for the node's HTTP response. +func sendC2N(ctx context.Context, b Backend, nodeID types.NodeID, path string) (*http.Response, error) { + c2nReq, err := http.NewRequestWithContext(ctx, http.MethodPost, "http://headscale"+path, nil) + if err != nil { + return nil, huma.Error500InternalServerError("building c2n request", err) + } + + var payload bytes.Buffer + + err = c2nReq.Write(&payload) + if err != nil { + return nil, huma.Error500InternalServerError("encoding c2n request", err) + } + + // The client only answers c2n over Noise, and only an https URL makes + // its Noise transport dial; the host is not used. + callback, err := url.Parse(b.Cfg.ServerURL) + if err != nil { + return nil, huma.Error500InternalServerError("parsing server_url", err) + } + + c2nID, responseCh := b.State.RegisterC2N(nodeID) + defer b.State.CancelC2N(c2nID) + + callback.Scheme = "https" + callback.Path = "/machine/c2n-response" + callback.RawQuery = url.Values{"id": {c2nID}}.Encode() + + b.Change(change.PingNode(nodeID, &tailcfg.PingRequest{ + URL: callback.String(), + Log: true, + Types: "c2n", + Payload: payload.Bytes(), + })) + + timer := time.NewTimer(c2nTimeout) + defer timer.Stop() + + select { + case raw, ok := <-responseCh: + if !ok { + return nil, huma.Error503ServiceUnavailable("server is shutting down") + } + + res, err := http.ReadResponse(bufio.NewReader(bytes.NewReader(raw)), c2nReq) + if err != nil { + return nil, huma.Error502BadGateway("reading c2n response", err) + } + + if res.StatusCode != http.StatusOK { + res.Body.Close() + + return nil, huma.Error502BadGateway("device answered c2n request with " + res.Status) + } + + return res, nil + case <-timer.C: + return nil, huma.Error504GatewayTimeout("device did not answer within " + c2nTimeout.String()) + case <-ctx.Done(): + return nil, ctx.Err() + } +} diff --git a/hscontrol/api/v2/devices.go b/hscontrol/api/v2/devices.go index 4f9687e0c..acbe6c543 100644 --- a/hscontrol/api/v2/devices.go +++ b/hscontrol/api/v2/devices.go @@ -3,6 +3,7 @@ package apiv2 import ( "cmp" "context" + "encoding/json" "net/http" "net/netip" "slices" @@ -14,6 +15,7 @@ import ( "github.com/juanfont/headscale/hscontrol/types" "github.com/juanfont/headscale/hscontrol/util" "tailscale.com/net/tsaddr" + "tailscale.com/tailcfg" ) func init() { @@ -105,6 +107,16 @@ type DevicePostureAttributes struct { Expiries map[string]time.Time `json:"expiries,omitempty"` } +// DeviceClientUpdate is the POST /device/{id}/update-client response. It mirrors +// [tailcfg.C2NUpdateResponse], the device's own answer: Error carries its +// reason when Started is false. +type DeviceClientUpdate struct { + Enabled bool `json:"enabled"` + Supported bool `json:"supported"` + Started bool `json:"started"` + Error string `json:"error"` +} + // Request bodies match the Tailscale SDK wire shapes and, like Tailscale's, // ignore properties they do not define. type ( @@ -136,6 +148,11 @@ type ( Routes []string `json:"routes" nullable:"false"` } + // updateDeviceClientRequest is headscale's own shape: Tailscale's + // update-client endpoint is undocumented, so its wire format is unknown. + updateDeviceClientRequest struct { + Force bool `json:"force,omitempty"` + } ) type ( @@ -170,6 +187,10 @@ type ( DeviceID string `path:"id"` Body setSubnetRoutesRequest } + updateDeviceClientInput struct { + DeviceID string `path:"id"` + Body *updateDeviceClientRequest `required:"false"` + } deviceOutput struct{ Body Device } deviceRoutesOutput struct{ Body DeviceRoutes } @@ -180,6 +201,8 @@ type ( } } emptyOutput struct{ Body struct{} } + + deviceClientUpdateOutput struct{ Body DeviceClientUpdate } ) func registerDevices(api huma.API, b Backend) { @@ -490,6 +513,62 @@ func registerDevices(api huma.API, b Backend) { return &deviceRoutesOutput{Body: routesFromView(node)}, nil }) + + huma.Register(api, requireScope(huma.Operation{ + OperationID: "updateDeviceClient", + Method: http.MethodPost, + Path: "/api/v2/device/{id}/update-client", + Summary: "Update a device's Tailscale client", + Description: "Asks a connected device over c2n to update its Tailscale client. The device only starts the update if it has auto-updates enabled and its platform supports them.", + Tags: []string{"Devices"}, + Security: security, + DefaultStatus: http.StatusOK, + Errors: []int{ + http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound, + http.StatusConflict, http.StatusBadGateway, http.StatusGatewayTimeout, + }, + }, scope.DevicesCore), func(ctx context.Context, in *updateDeviceClientInput) (*deviceClientUpdateOutput, error) { + node, err := lookupNode(b, in.DeviceID) + if err != nil { + return nil, err + } + + if !node.IsOnline().Valid() || !node.IsOnline().Get() { + return nil, huma.Error409Conflict("device is not connected") + } + + force := in.Body != nil && in.Body.Force + + res, err := sendC2N(ctx, b, node.ID(), c2nUpdatePath(force)) + if err != nil { + return nil, err + } + defer res.Body.Close() + + var update tailcfg.C2NUpdateResponse + + err = json.NewDecoder(res.Body).Decode(&update) + if err != nil { + return nil, huma.Error502BadGateway("decoding client update response", err) + } + + return &deviceClientUpdateOutput{Body: DeviceClientUpdate{ + Enabled: update.Enabled, + Supported: update.Supported, + Started: update.Started, + Error: update.Err, + }}, nil + }) +} + +// c2nUpdatePath is the c2n endpoint that starts a client update. force +// overrides the client's refusal to update with active SSH sessions. +func c2nUpdatePath(force bool) string { + if force { + return "/update?force=true" + } + + return "/update" } // lookupNode resolves a device id to its NodeView, mapping a malformed or diff --git a/hscontrol/apiv2_oauth_matrix_test.go b/hscontrol/apiv2_oauth_matrix_test.go index 427bee28b..c4324f5ac 100644 --- a/hscontrol/apiv2_oauth_matrix_test.go +++ b/hscontrol/apiv2_oauth_matrix_test.go @@ -122,6 +122,7 @@ func TestAPIv2OAuthMatrix_Enforcement(t *testing.T) { {"setDeviceName", http.MethodPost, "/api/v2/device/1/name", scope.DevicesCore, map[string]any{}, false}, {"setDeviceTags", http.MethodPost, "/api/v2/device/1/tags", scope.DevicesCore, map[string]any{}, false}, {"setDeviceKey", http.MethodPost, "/api/v2/device/1/key", scope.DevicesCore, map[string]any{}, false}, + {"updateDeviceClient", http.MethodPost, "/api/v2/device/1/update-client", scope.DevicesCore, map[string]any{}, false}, {"setDeviceRoutes", http.MethodPost, "/api/v2/device/1/routes", scope.DevicesRoutes, map[string]any{}, false}, {"getDeviceRoutes", http.MethodGet, "/api/v2/device/1/routes", scope.DevicesRoutesRead, nil, false}, {"getACL", http.MethodGet, "/api/v2/tailnet/-/acl", scope.PolicyFileRead, nil, false}, diff --git a/hscontrol/servertest/apiv2_device_update_client_test.go b/hscontrol/servertest/apiv2_device_update_client_test.go new file mode 100644 index 000000000..bcb80d90f --- /dev/null +++ b/hscontrol/servertest/apiv2_device_update_client_test.go @@ -0,0 +1,186 @@ +package servertest_test + +import ( + "bytes" + "context" + "encoding/json" + "net/http" + "strconv" + "sync" + "testing" + "time" + + "github.com/juanfont/headscale/hscontrol/servertest" + "github.com/juanfont/headscale/hscontrol/types" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "tailscale.com/tailcfg" +) + +// fakeUpdater answers c2n "POST /update" the way tailscaled does, with a +// fixed [tailcfg.C2NUpdateResponse], and records the force query value +// of every request. +type fakeUpdater struct { + res tailcfg.C2NUpdateResponse + + mu sync.Mutex + forces []string +} + +func (f *fakeUpdater) ServeHTTP(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/update" { + http.NotFound(w, r) + return + } + + f.mu.Lock() + f.forces = append(f.forces, r.FormValue("force")) + f.mu.Unlock() + + w.Header().Set("Content-Type", "application/json") + + err := json.NewEncoder(w).Encode(f.res) + if err != nil { + http.Error(w, err.Error(), http.StatusInternalServerError) + } +} + +func (f *fakeUpdater) seenForces() []string { + f.mu.Lock() + defer f.mu.Unlock() + + return append([]string(nil), f.forces...) +} + +type deviceClientUpdate struct { + Enabled bool `json:"enabled"` + Supported bool `json:"supported"` + Started bool `json:"started"` + Error string `json:"error"` +} + +// updateDeviceClient calls POST /api/v2/device/{id}/update-client and +// returns the status code and decoded body. +func updateDeviceClient(t *testing.T, srv *servertest.TestServer, nodeID types.NodeID, force bool) (int, deviceClientUpdate) { + t.Helper() + + body, err := json.Marshal(map[string]bool{"force": force}) + require.NoError(t, err) + + ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) + defer cancel() + + req, err := http.NewRequestWithContext(ctx, http.MethodPost, + srv.URL+"/api/v2/device/"+strconv.FormatUint(nodeID.Uint64(), 10)+"/update-client", + bytes.NewReader(body)) + require.NoError(t, err) + + req.Header.Set("Authorization", "Bearer "+srv.CreateAPIKey(t, nil)) + req.Header.Set("Content-Type", "application/json") + + client := &http.Client{Transport: &http.Transport{DialContext: srv.MemNet().Dial}} + + resp, err := client.Do(req) + require.NoError(t, err) + + defer resp.Body.Close() + + var out deviceClientUpdate + if resp.StatusCode == http.StatusOK { + require.NoError(t, json.NewDecoder(resp.Body).Decode(&out)) + } + + return resp.StatusCode, out +} + +// TestAPIv2DeviceUpdateClient verifies the full c2n round-trip: the API sends a +// c2n [tailcfg.PingRequest] carrying "POST /update", the real +// [controlclient.Direct] runs it against its c2n handler and posts the +// response back over Noise, and the API returns the node's answer. +func TestAPIv2DeviceUpdateClient(t *testing.T) { + t.Parallel() + + updater := &fakeUpdater{res: tailcfg.C2NUpdateResponse{ + Enabled: true, + Supported: true, + Started: true, + }} + + h := servertest.NewHarness(t, 1, + servertest.WithDefaultClientOptions(servertest.WithC2NHandler(updater))) + + nm := h.Client(0).Netmap() + require.NotNil(t, nm) + + nodeID := types.NodeID(nm.SelfNode.ID()) //nolint:gosec + + code, res := updateDeviceClient(t, h.Server, nodeID, false) + require.Equal(t, http.StatusOK, code) + assert.True(t, res.Enabled) + assert.True(t, res.Supported) + assert.True(t, res.Started) + assert.Empty(t, res.Error) + + code, _ = updateDeviceClient(t, h.Server, nodeID, true) + require.Equal(t, http.StatusOK, code) + + assert.Equal(t, []string{"", "true"}, updater.seenForces(), + "force must reach the client as ?force=true only when requested") +} + +// TestAPIv2DeviceUpdateClientRefused verifies that a client refusing the update +// (auto-updates off, unsupported platform, active SSH) is reported back +// as a successful call with started=false and the client's reason. +func TestAPIv2DeviceUpdateClientRefused(t *testing.T) { + t.Parallel() + + updater := &fakeUpdater{res: tailcfg.C2NUpdateResponse{ + Supported: true, + Err: "not enabled", + }} + + h := servertest.NewHarness(t, 1, + servertest.WithDefaultClientOptions(servertest.WithC2NHandler(updater))) + + nodeID := types.NodeID(h.Client(0).Netmap().SelfNode.ID()) //nolint:gosec + + code, res := updateDeviceClient(t, h.Server, nodeID, false) + require.Equal(t, http.StatusOK, code) + assert.False(t, res.Enabled) + assert.False(t, res.Started) + assert.Equal(t, "not enabled", res.Error) +} + +// TestAPIv2DeviceUpdateClientNotConnected verifies that a disconnected device is +// rejected with 409 instead of waiting for an answer that cannot come. +func TestAPIv2DeviceUpdateClientNotConnected(t *testing.T) { + t.Parallel() + + h := servertest.NewHarness(t, 1) + + nodeID := types.NodeID(h.Client(0).Netmap().SelfNode.ID()) //nolint:gosec + + h.Client(0).Disconnect(t) + + // The node is marked offline after the disconnect grace period. + require.EventuallyWithT(t, func(c *assert.CollectT) { + nv, ok := h.Server.State().GetNodeByID(nodeID) + assert.True(c, ok) + + isOnline, known := nv.IsOnline().GetOk() + assert.True(c, known && !isOnline, "node should be offline") + }, 20*time.Second, 200*time.Millisecond) + + code, _ := updateDeviceClient(t, h.Server, nodeID, false) + assert.Equal(t, http.StatusConflict, code) +} + +// TestAPIv2DeviceUpdateClientUnknownDevice verifies that an unknown device ID is a 404. +func TestAPIv2DeviceUpdateClientUnknownDevice(t *testing.T) { + t.Parallel() + + h := servertest.NewHarness(t, 0) + + code, _ := updateDeviceClient(t, h.Server, types.NodeID(9999), false) + assert.Equal(t, http.StatusNotFound, code) +} diff --git a/hscontrol/servertest/client.go b/hscontrol/servertest/client.go index 53444d69d..c0fdc544e 100644 --- a/hscontrol/servertest/client.go +++ b/hscontrol/servertest/client.go @@ -3,6 +3,7 @@ package servertest import ( "context" "fmt" + "net/http" "path" "slices" "strings" @@ -13,6 +14,7 @@ import ( "github.com/juanfont/headscale/hscontrol/types" "github.com/juanfont/headscale/hscontrol/types/testcapture" "tailscale.com/control/controlclient" + _ "tailscale.com/feature/c2n" // registers the c2n answer hook used by [WithC2NHandler] "tailscale.com/health" "tailscale.com/net/netmon" "tailscale.com/net/tsdial" @@ -54,6 +56,8 @@ type TestClient struct { // stopFollowup ends the follow-up [TestClient.RotateDisco] left waiting. stopFollowup context.CancelFunc + // c2nHandler answers c2n requests; see [WithC2NHandler]. + c2nHandler http.Handler // Connection lifecycle. pollCtx context.Context //nolint:containedctx // test-only; context stored for cancel control @@ -107,6 +111,7 @@ type clientConfig struct { approve func(authID string) error loginFlags controlclient.LoginFlags endpoints []tailcfg.Endpoint + c2nHandler http.Handler } // WithoutNetmapHistory retains only the latest netmap and one queued update. @@ -170,6 +175,12 @@ func WithEndpoints(eps ...tailcfg.Endpoint) ClientOption { return func(c *clientConfig) { c.endpoints = eps } } +// WithC2NHandler makes the client answer c2n requests from the server +// with handler, as tailscaled answers them with its LocalBackend. +func WithC2NHandler(handler http.Handler) ClientOption { + return func(c *clientConfig) { c.c2nHandler = handler } +} + // WithUser sets the user for the client. If not set, the harness // creates a default user. func WithUser(user *types.User) ClientOption { @@ -252,6 +263,7 @@ func TryNewClient(tb testing.TB, server *TestServer, name string, opts ...Client approve: cc.approve, loginFlags: cc.loginFlags, endpoints: cc.endpoints, + c2nHandler: cc.c2nHandler, updates: make(chan *netmap.NetworkMap, updateBuffer), bus: bus, dialer: dialer, @@ -326,6 +338,7 @@ func (c *TestClient) newDirect( HealthTracker: c.tracker, Dialer: c.dialer, Bus: c.bus, + C2NHandler: c.c2nHandler, }) if err == nil && len(c.endpoints) > 0 { direct.SetEndpoints(c.endpoints)