mirror of
https://github.com/juanfont/headscale.git
synced 2026-11-19 11:57:07 +09:00
api/v2: expose last control address as device attribute
This commit is contained in:
1 parent
9fa176b211
commit
bae1d6fd84
19 files changed
+759
-9
No files matched your search
@@ -93,6 +93,12 @@ type Device struct {
|
||||
User string `json:"user"`
|
||||
}
|
||||
|
||||
// DevicePostureAttributes defines model for DevicePostureAttributes.
|
||||
type DevicePostureAttributes struct {
|
||||
Attributes map[string]interface{} `json:"attributes"`
|
||||
Expiries map[string]time.Time `json:"expiries"`
|
||||
}
|
||||
|
||||
// DeviceRoutes defines model for DeviceRoutes.
|
||||
type DeviceRoutes struct {
|
||||
AdvertisedRoutes []string `json:"advertisedRoutes"`
|
||||
@@ -446,6 +452,13 @@ type ClientInterface interface {
|
||||
// Corresponds with GET /api/v2/device/{id} (the `GetDevice` operationId).
|
||||
GetDevice(ctx context.Context, id string, params *GetDeviceParams, reqEditors ...RequestEditorFn) (*http.Response, error)
|
||||
|
||||
// GetDevicePostureAttributes Get device posture attributes
|
||||
//
|
||||
// Requires the `devices:posture_attributes:read` OAuth scope (an admin API key is all-access).
|
||||
//
|
||||
// Corresponds with GET /api/v2/device/{id}/attributes (the `GetDevicePostureAttributes` operationId).
|
||||
GetDevicePostureAttributes(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error)
|
||||
|
||||
// AuthorizeDeviceWithBody Authorize a device
|
||||
//
|
||||
// Requires the `devices:core` OAuth scope (an admin API key is all-access).
|
||||
@@ -717,6 +730,23 @@ func (c *Client) GetDevice(ctx context.Context, id string, params *GetDevicePara
|
||||
return c.Client.Do(req)
|
||||
}
|
||||
|
||||
// GetDevicePostureAttributes Get device posture attributes
|
||||
//
|
||||
// Requires the `devices:posture_attributes:read` OAuth scope (an admin API key is all-access).
|
||||
//
|
||||
// Corresponds with GET /api/v2/device/{id}/attributes (the `GetDevicePostureAttributes` operationId).
|
||||
func (c *Client) GetDevicePostureAttributes(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*http.Response, error) {
|
||||
req, err := NewGetDevicePostureAttributesRequest(c.Server, id)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
req = req.WithContext(ctx)
|
||||
if err := c.applyEditors(ctx, req, reqEditors); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return c.Client.Do(req)
|
||||
}
|
||||
|
||||
// AuthorizeDeviceWithBody Authorize a device
|
||||
//
|
||||
// Requires the `devices:core` OAuth scope (an admin API key is all-access).
|
||||
@@ -1355,6 +1385,40 @@ func NewGetDeviceRequest(server string, id string, params *GetDeviceParams) (*ht
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// NewGetDevicePostureAttributesRequest constructs an http.Request for the GetDevicePostureAttributes method
|
||||
func NewGetDevicePostureAttributesRequest(server string, id string) (*http.Request, error) {
|
||||
var err error
|
||||
|
||||
var pathParam0 string
|
||||
|
||||
pathParam0, err = runtime.StyleParamWithOptions("simple", false, "id", id, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
serverURL, err := url.Parse(server)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
operationPath := fmt.Sprintf("/api/v2/device/%s/attributes", pathParam0)
|
||||
if operationPath[0] == '/' {
|
||||
operationPath = "." + operationPath
|
||||
}
|
||||
|
||||
queryURL, err := serverURL.Parse(operationPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return req, nil
|
||||
}
|
||||
|
||||
// NewAuthorizeDeviceRequest calls the generic AuthorizeDevice builder with application/json body
|
||||
func NewAuthorizeDeviceRequest(server string, id string, body AuthorizeDeviceJSONRequestBody) (*http.Request, error) {
|
||||
var bodyReader io.Reader
|
||||
@@ -2409,6 +2473,15 @@ type ClientWithResponsesInterface interface {
|
||||
// Corresponds with GET /api/v2/device/{id} (the `GetDevice` operationId).
|
||||
GetDeviceWithResponse(ctx context.Context, id string, params *GetDeviceParams, reqEditors ...RequestEditorFn) (*GetDeviceResponse, error)
|
||||
|
||||
// GetDevicePostureAttributesWithResponse Get device posture attributes
|
||||
//
|
||||
// Requires the `devices:posture_attributes:read` OAuth scope (an admin API key is all-access).
|
||||
//
|
||||
// Returns a wrapper object for the known response body format(s).
|
||||
//
|
||||
// Corresponds with GET /api/v2/device/{id}/attributes (the `GetDevicePostureAttributes` operationId).
|
||||
GetDevicePostureAttributesWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*GetDevicePostureAttributesResponse, error)
|
||||
|
||||
// AuthorizeDeviceWithBodyWithResponse Authorize a device
|
||||
//
|
||||
// Requires the `devices:core` OAuth scope (an admin API key is all-access).
|
||||
@@ -2818,6 +2891,82 @@ func (r GetDeviceResponse) ContentType() string {
|
||||
return ""
|
||||
}
|
||||
|
||||
type GetDevicePostureAttributesResponse struct {
|
||||
Body []byte
|
||||
HTTPResponse *http.Response
|
||||
// JSON200 the response for an HTTP 200 `application/json` response
|
||||
JSON200 *DevicePostureAttributes
|
||||
// ApplicationproblemJSON401 the response for an HTTP 401 `application/problem+json` response
|
||||
ApplicationproblemJSON401 *ErrorModel
|
||||
// ApplicationproblemJSON403 the response for an HTTP 403 `application/problem+json` response
|
||||
ApplicationproblemJSON403 *ErrorModel
|
||||
// ApplicationproblemJSON404 the response for an HTTP 404 `application/problem+json` response
|
||||
ApplicationproblemJSON404 *ErrorModel
|
||||
// ApplicationproblemJSON422 the response for an HTTP 422 `application/problem+json` response
|
||||
ApplicationproblemJSON422 *ErrorModel
|
||||
// ApplicationproblemJSON500 the response for an HTTP 500 `application/problem+json` response
|
||||
ApplicationproblemJSON500 *ErrorModel
|
||||
}
|
||||
|
||||
// GetJSON200 returns the response for an HTTP 200 `application/json` response
|
||||
func (r GetDevicePostureAttributesResponse) GetJSON200() *DevicePostureAttributes {
|
||||
return r.JSON200
|
||||
}
|
||||
|
||||
// GetApplicationproblemJSON401 returns the response for an HTTP 401 `application/problem+json` response
|
||||
func (r GetDevicePostureAttributesResponse) GetApplicationproblemJSON401() *ErrorModel {
|
||||
return r.ApplicationproblemJSON401
|
||||
}
|
||||
|
||||
// GetApplicationproblemJSON403 returns the response for an HTTP 403 `application/problem+json` response
|
||||
func (r GetDevicePostureAttributesResponse) GetApplicationproblemJSON403() *ErrorModel {
|
||||
return r.ApplicationproblemJSON403
|
||||
}
|
||||
|
||||
// GetApplicationproblemJSON404 returns the response for an HTTP 404 `application/problem+json` response
|
||||
func (r GetDevicePostureAttributesResponse) GetApplicationproblemJSON404() *ErrorModel {
|
||||
return r.ApplicationproblemJSON404
|
||||
}
|
||||
|
||||
// GetApplicationproblemJSON422 returns the response for an HTTP 422 `application/problem+json` response
|
||||
func (r GetDevicePostureAttributesResponse) GetApplicationproblemJSON422() *ErrorModel {
|
||||
return r.ApplicationproblemJSON422
|
||||
}
|
||||
|
||||
// GetApplicationproblemJSON500 returns the response for an HTTP 500 `application/problem+json` response
|
||||
func (r GetDevicePostureAttributesResponse) GetApplicationproblemJSON500() *ErrorModel {
|
||||
return r.ApplicationproblemJSON500
|
||||
}
|
||||
|
||||
// GetBody returns the raw response body bytes
|
||||
func (r GetDevicePostureAttributesResponse) GetBody() []byte {
|
||||
return r.Body
|
||||
}
|
||||
|
||||
// Status returns HTTPResponse.Status
|
||||
func (r GetDevicePostureAttributesResponse) Status() string {
|
||||
if r.HTTPResponse != nil {
|
||||
return r.HTTPResponse.Status
|
||||
}
|
||||
return http.StatusText(0)
|
||||
}
|
||||
|
||||
// StatusCode returns HTTPResponse.StatusCode
|
||||
func (r GetDevicePostureAttributesResponse) StatusCode() int {
|
||||
if r.HTTPResponse != nil {
|
||||
return r.HTTPResponse.StatusCode
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers
|
||||
func (r GetDevicePostureAttributesResponse) ContentType() string {
|
||||
if r.HTTPResponse != nil {
|
||||
return r.HTTPResponse.Header.Get("Content-Type")
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type AuthorizeDeviceResponse struct {
|
||||
Body []byte
|
||||
HTTPResponse *http.Response
|
||||
@@ -4348,6 +4497,21 @@ func (c *ClientWithResponses) GetDeviceWithResponse(ctx context.Context, id stri
|
||||
return ParseGetDeviceResponse(rsp)
|
||||
}
|
||||
|
||||
// GetDevicePostureAttributesWithResponse Get device posture attributes
|
||||
//
|
||||
// Requires the `devices:posture_attributes:read` OAuth scope (an admin API key is all-access).
|
||||
//
|
||||
// Returns a wrapper object for the known response body format(s).
|
||||
//
|
||||
// Corresponds with GET /api/v2/device/{id}/attributes (the `GetDevicePostureAttributes` operationId).
|
||||
func (c *ClientWithResponses) GetDevicePostureAttributesWithResponse(ctx context.Context, id string, reqEditors ...RequestEditorFn) (*GetDevicePostureAttributesResponse, error) {
|
||||
rsp, err := c.GetDevicePostureAttributes(ctx, id, reqEditors...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return ParseGetDevicePostureAttributesResponse(rsp)
|
||||
}
|
||||
|
||||
// AuthorizeDeviceWithBodyWithResponse Authorize a device
|
||||
//
|
||||
// Requires the `devices:core` OAuth scope (an admin API key is all-access).
|
||||
@@ -4894,6 +5058,67 @@ func ParseGetDeviceResponse(rsp *http.Response) (*GetDeviceResponse, error) {
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// ParseGetDevicePostureAttributesResponse parses an HTTP response from a GetDevicePostureAttributesWithResponse call
|
||||
func ParseGetDevicePostureAttributesResponse(rsp *http.Response) (*GetDevicePostureAttributesResponse, error) {
|
||||
bodyBytes, err := io.ReadAll(rsp.Body)
|
||||
defer func() { _ = rsp.Body.Close() }()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
response := &GetDevicePostureAttributesResponse{
|
||||
Body: bodyBytes,
|
||||
HTTPResponse: rsp,
|
||||
}
|
||||
|
||||
switch {
|
||||
case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
|
||||
var dest DevicePostureAttributes
|
||||
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.JSON200 = &dest
|
||||
|
||||
case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401:
|
||||
var dest ErrorModel
|
||||
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.ApplicationproblemJSON401 = &dest
|
||||
|
||||
case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 403:
|
||||
var dest ErrorModel
|
||||
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.ApplicationproblemJSON403 = &dest
|
||||
|
||||
case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404:
|
||||
var dest ErrorModel
|
||||
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.ApplicationproblemJSON404 = &dest
|
||||
|
||||
case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 422:
|
||||
var dest ErrorModel
|
||||
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.ApplicationproblemJSON422 = &dest
|
||||
|
||||
case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 500:
|
||||
var dest ErrorModel
|
||||
if err := json.Unmarshal(bodyBytes, &dest); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
response.ApplicationproblemJSON500 = &dest
|
||||
|
||||
}
|
||||
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// ParseAuthorizeDeviceResponse parses an HTTP response from a AuthorizeDeviceWithResponse call
|
||||
func ParseAuthorizeDeviceResponse(rsp *http.Response) (*AuthorizeDeviceResponse, error) {
|
||||
bodyBytes, err := io.ReadAll(rsp.Body)
|
||||
|
||||
@@ -27,8 +27,9 @@ headscale's own conventions. The headscale-native admin API stays at `/api/v1`
|
||||
sends) or **Bearer**: an admin API key (`hskey-api-…`), or an OAuth access
|
||||
token (`hskey-oauthtok-…`). See `authMiddleware`.
|
||||
- Each operation declares the Tailscale scope it requires (`auth_keys`,
|
||||
`oauth_keys`, `devices:core`, `devices:routes`, `policy_file`,
|
||||
`feature_settings`, each with a `:read` subset, plus `all`/`all:read`).
|
||||
`oauth_keys`, `devices:core`, `devices:routes`,
|
||||
`devices:posture_attributes`, `policy_file`, `feature_settings`, each with a
|
||||
`:read` subset, plus `all`/`all:read`).
|
||||
`requireScope` records it both for the middleware and in the generated
|
||||
OpenAPI, as an `x-required-scope` extension and a sentence in the operation
|
||||
description, so the scope shows up in the docs and spec. Enforcement: an
|
||||
|
||||
@@ -97,6 +97,13 @@ type DeviceRoutes struct {
|
||||
Enabled []string `json:"enabledRoutes" nullable:"false"`
|
||||
}
|
||||
|
||||
// DevicePostureAttributes is the Tailscale-compatible posture attribute
|
||||
// response. Headscale currently exposes only the server-derived public address.
|
||||
type DevicePostureAttributes struct {
|
||||
Attributes map[string]any `json:"attributes" nullable:"false"`
|
||||
Expiries map[string]time.Time `json:"expiries" nullable:"false"`
|
||||
}
|
||||
|
||||
// Request bodies match the Tailscale SDK wire shapes and, like Tailscale's,
|
||||
// ignore properties they do not define.
|
||||
type (
|
||||
@@ -135,6 +142,9 @@ type (
|
||||
DeviceID string `doc:"Device id (the decimal node id)." path:"id"`
|
||||
Fields string `doc:"Set to \"all\" for route fields." query:"fields"`
|
||||
}
|
||||
deviceAttributesInput struct {
|
||||
DeviceID string `doc:"Device id (the decimal node id)." path:"id"`
|
||||
}
|
||||
listDevicesInput struct {
|
||||
Tailnet string `doc:"Tailnet; must be \"-\"." path:"tailnet"`
|
||||
Fields string `query:"fields"`
|
||||
@@ -160,9 +170,10 @@ type (
|
||||
Body setSubnetRoutesRequest
|
||||
}
|
||||
|
||||
deviceOutput struct{ Body Device }
|
||||
deviceRoutesOutput struct{ Body DeviceRoutes }
|
||||
listDevicesOutput struct {
|
||||
deviceOutput struct{ Body Device }
|
||||
deviceRoutesOutput struct{ Body DeviceRoutes }
|
||||
devicePostureAttributesOutput struct{ Body DevicePostureAttributes }
|
||||
listDevicesOutput struct {
|
||||
Body struct {
|
||||
Devices []Device `json:"devices" nullable:"false"`
|
||||
}
|
||||
@@ -190,6 +201,23 @@ func registerDevices(api huma.API, b Backend) {
|
||||
return &deviceOutput{Body: deviceFromView(node, in.Fields == "all", b.Cfg.BaseDomain)}, nil
|
||||
})
|
||||
|
||||
huma.Register(api, requireScope(huma.Operation{
|
||||
OperationID: "getDevicePostureAttributes",
|
||||
Method: http.MethodGet,
|
||||
Path: "/api/v2/device/{id}/attributes",
|
||||
Summary: "Get device posture attributes",
|
||||
Tags: deviceTags,
|
||||
Security: security,
|
||||
Errors: []int{http.StatusUnauthorized, http.StatusForbidden, http.StatusNotFound},
|
||||
}, scope.DevicesPostureAttributesRead), func(ctx context.Context, in *deviceAttributesInput) (*devicePostureAttributesOutput, error) {
|
||||
node, err := lookupNode(b, in.DeviceID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &devicePostureAttributesOutput{Body: devicePostureAttributesFromView(node)}, nil
|
||||
})
|
||||
|
||||
huma.Register(api, requireScope(huma.Operation{
|
||||
OperationID: "listDevices",
|
||||
Method: http.MethodGet,
|
||||
@@ -596,6 +624,18 @@ func deviceFromView(view types.NodeView, allFields bool, baseDomain string) Devi
|
||||
return d
|
||||
}
|
||||
|
||||
func devicePostureAttributesFromView(view types.NodeView) DevicePostureAttributes {
|
||||
attributes := make(map[string]any)
|
||||
if addr := view.LastControlAddress(); addr.Valid() {
|
||||
attributes["ip:publicAddress"] = addr.Get().String()
|
||||
}
|
||||
|
||||
return DevicePostureAttributes{
|
||||
Attributes: attributes,
|
||||
Expiries: make(map[string]time.Time),
|
||||
}
|
||||
}
|
||||
|
||||
func routesFromView(view types.NodeView) DeviceRoutes {
|
||||
return DeviceRoutes{
|
||||
Advertised: emptyIfNil(util.PrefixesToString(view.AnnouncedRoutes())),
|
||||
|
||||
@@ -120,6 +120,22 @@ func getDeviceRoutes(t *testing.T, api humatest.TestAPI, deviceID string) apiv2.
|
||||
return routes
|
||||
}
|
||||
|
||||
func getDevicePostureAttributes(
|
||||
t *testing.T,
|
||||
api humatest.TestAPI,
|
||||
deviceID string,
|
||||
) apiv2.DevicePostureAttributes {
|
||||
t.Helper()
|
||||
|
||||
resp := api.Get("/api/v2/device/" + deviceID + "/attributes")
|
||||
require.Equalf(t, http.StatusOK, resp.Code, "body: %s", resp.Body)
|
||||
|
||||
var attrs apiv2.DevicePostureAttributes
|
||||
require.NoError(t, json.Unmarshal(resp.Body.Bytes(), &attrs))
|
||||
|
||||
return attrs
|
||||
}
|
||||
|
||||
func approvedRouteStrings(nv types.NodeView) []string {
|
||||
return util.PrefixesToString(nv.ApprovedRoutes().AsSlice())
|
||||
}
|
||||
@@ -130,6 +146,10 @@ func TestAPIv2Device_Get(t *testing.T) {
|
||||
resp := e.api.Get("/api/v2/device/" + e.deviceID + "?fields=all")
|
||||
require.Equalf(t, http.StatusOK, resp.Code, "body: %s", resp.Body)
|
||||
|
||||
var raw map[string]json.RawMessage
|
||||
require.NoError(t, json.Unmarshal(resp.Body.Bytes(), &raw))
|
||||
assert.NotContains(t, raw, "otherKnown"+"IPs")
|
||||
|
||||
var dev apiv2.Device
|
||||
require.NoError(t, json.Unmarshal(resp.Body.Bytes(), &dev))
|
||||
assert.Equal(t, e.deviceID, dev.ID)
|
||||
@@ -191,6 +211,49 @@ func TestAPIv2Device_Get_UnknownID_404(t *testing.T) {
|
||||
assert.Equal(t, http.StatusNotFound, e.api.Get("/api/v2/device/not-a-number").Code)
|
||||
}
|
||||
|
||||
func TestAPIv2Device_GetPostureAttributes(t *testing.T) {
|
||||
e := newDeviceTestEnv(t)
|
||||
|
||||
t.Run("unknown address", func(t *testing.T) {
|
||||
attrs := getDevicePostureAttributes(t, e.api, e.deviceID)
|
||||
assert.NotNil(t, attrs.Attributes)
|
||||
assert.Empty(t, attrs.Attributes)
|
||||
assert.NotNil(t, attrs.Expiries)
|
||||
assert.Empty(t, attrs.Expiries)
|
||||
})
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
addr string
|
||||
}{
|
||||
{name: "IPv4", addr: "203.0.113.10"},
|
||||
{name: "IPv6", addr: "2001:db8::10"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
changed, err := e.app.state.SetLastControlAddress(
|
||||
e.nodeID,
|
||||
netip.MustParseAddr(test.addr),
|
||||
)
|
||||
require.NoError(t, err)
|
||||
assert.True(t, changed)
|
||||
|
||||
attrs := getDevicePostureAttributes(t, e.api, e.deviceID)
|
||||
assert.Equal(t, test.addr, attrs.Attributes["ip:publicAddress"])
|
||||
assert.NotNil(t, attrs.Expiries)
|
||||
assert.Empty(t, attrs.Expiries)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIv2Device_GetPostureAttributes_UnknownID_404(t *testing.T) {
|
||||
e := newDeviceTestEnv(t)
|
||||
|
||||
assert.Equal(t, http.StatusNotFound,
|
||||
e.api.Get("/api/v2/device/999999/attributes").Code)
|
||||
assert.Equal(t, http.StatusNotFound,
|
||||
e.api.Get("/api/v2/device/not-a-number/attributes").Code)
|
||||
}
|
||||
|
||||
func TestAPIv2Device_List(t *testing.T) {
|
||||
e := newDeviceTestEnv(t)
|
||||
|
||||
@@ -205,10 +268,21 @@ func TestAPIv2Device_List(t *testing.T) {
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(resp.Body.Bytes(), &out))
|
||||
|
||||
var raw struct {
|
||||
Devices []map[string]json.RawMessage `json:"devices"`
|
||||
}
|
||||
require.NoError(t, json.Unmarshal(resp.Body.Bytes(), &raw))
|
||||
|
||||
for _, device := range raw.Devices {
|
||||
assert.NotContains(t, device, "otherKnown"+"IPs")
|
||||
}
|
||||
|
||||
return out.Devices
|
||||
}
|
||||
|
||||
assert.True(t, containsDeviceID(list(), e.deviceID))
|
||||
devices := list()
|
||||
require.Len(t, devices, 1)
|
||||
assert.True(t, containsDeviceID(devices, e.deviceID))
|
||||
assert.Len(t, list(), e.app.state.ListNodes().Len(), "list count == ListNodes")
|
||||
|
||||
// A second node appears; deleting it removes it from both the list and state.
|
||||
|
||||
@@ -114,6 +114,7 @@ func TestAPIv2OAuthMatrix_Enforcement(t *testing.T) {
|
||||
|
||||
ops := []matrixOp{
|
||||
{"getDevice", http.MethodGet, "/api/v2/device/1", scope.DevicesCoreRead, nil, false},
|
||||
{"getDevicePostureAttributes", http.MethodGet, "/api/v2/device/1/attributes", scope.DevicesPostureAttributesRead, nil, false},
|
||||
{"listDevices", http.MethodGet, "/api/v2/tailnet/-/devices", scope.DevicesCoreRead, nil, false},
|
||||
{"deleteDevice", http.MethodDelete, "/api/v2/device/1", scope.DevicesCore, nil, false},
|
||||
{"authorizeDevice", http.MethodPost, "/api/v2/device/1/authorized", scope.DevicesCore, map[string]any{}, false},
|
||||
|
||||
@@ -358,6 +358,23 @@ WHERE auth_key_id IN (
|
||||
},
|
||||
Rollback: func(db *gorm.DB) error { return nil },
|
||||
},
|
||||
{
|
||||
// Persist the source IP most recently observed on an authenticated
|
||||
// control connection from each node. Existing rows intentionally
|
||||
// remain NULL until the node next connects.
|
||||
ID: "202609040900-add-last-control-address",
|
||||
Migrate: func(tx *gorm.DB) error {
|
||||
if !tx.Migrator().HasColumn(&types.Node{}, "last_control_address") {
|
||||
err := tx.Migrator().AddColumn(&types.Node{}, "LastControlAddress")
|
||||
if err != nil {
|
||||
return fmt.Errorf("adding last_control_address to nodes: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
},
|
||||
Rollback: func(db *gorm.DB) error { return nil },
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@@ -1106,3 +1106,45 @@ func TestOpenDBReturnsOpenError(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLastControlAddressMigration(t *testing.T) {
|
||||
dbPath := t.TempDir() + "/headscale.db"
|
||||
cfg := &types.Config{
|
||||
Database: types.DatabaseConfig{
|
||||
Type: types.DatabaseSqlite,
|
||||
Sqlite: types.SqliteConfig{
|
||||
Path: dbPath,
|
||||
},
|
||||
},
|
||||
Policy: types.PolicyConfig{Mode: types.PolicyModeDB},
|
||||
}
|
||||
|
||||
database, err := NewHeadscaleDatabase(cfg)
|
||||
require.NoError(t, err, "a fresh database must match schema.sql")
|
||||
require.True(t, database.DB.Migrator().HasColumn(&types.Node{}, "last_control_address"))
|
||||
|
||||
user := database.CreateUserForTest("migration-user")
|
||||
node := database.CreateRegisteredNodeForTest(user, "migration-node")
|
||||
require.Nil(t, node.LastControlAddress)
|
||||
|
||||
result := database.DB.Exec(
|
||||
"DELETE FROM migrations WHERE id = ?",
|
||||
"202609040900-add-last-control-address",
|
||||
)
|
||||
require.NoError(t, result.Error)
|
||||
require.Equal(t, int64(1), result.RowsAffected)
|
||||
require.NoError(t,
|
||||
database.DB.Exec("ALTER TABLE nodes DROP COLUMN last_control_address").Error)
|
||||
require.False(t, database.DB.Migrator().HasColumn(&types.Node{}, "last_control_address"))
|
||||
require.NoError(t, database.Close())
|
||||
|
||||
upgraded, err := NewHeadscaleDatabase(cfg)
|
||||
require.NoError(t, err, "a database without last_control_address must upgrade")
|
||||
t.Cleanup(func() { _ = upgraded.Close() })
|
||||
|
||||
require.True(t, upgraded.DB.Migrator().HasColumn(&types.Node{}, "last_control_address"))
|
||||
reloaded, err := upgraded.GetNodeByID(node.ID)
|
||||
require.NoError(t, err)
|
||||
assert.Nil(t, reloaded.LastControlAddress,
|
||||
"existing nodes must receive NULL rather than an invented address")
|
||||
}
|
||||
@@ -179,6 +179,26 @@ func SetLastSeen(tx *gorm.DB, nodeID types.NodeID, lastSeen time.Time) error {
|
||||
return tx.Model(&types.Node{}).Where("id = ?", nodeID).Update("last_seen", lastSeen).Error
|
||||
}
|
||||
|
||||
// SetLastControlAddress persists the source IP most recently observed on an
|
||||
// authenticated control connection from a node. It updates only this metadata
|
||||
// column and deliberately leaves UpdatedAt unchanged.
|
||||
func (hsdb *HSDatabase) SetLastControlAddress(nodeID types.NodeID, addr netip.Addr) error {
|
||||
return hsdb.Write(func(tx *gorm.DB) error {
|
||||
result := tx.Model(&types.Node{}).
|
||||
Where("id = ?", nodeID).
|
||||
UpdateColumn("last_control_address", addr.String())
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
|
||||
if result.RowsAffected == 0 {
|
||||
return gorm.ErrRecordNotFound
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
}
|
||||
|
||||
func (hsdb *HSDatabase) NodeSetExpiry(nodeID types.NodeID, expiry *time.Time) error {
|
||||
return hsdb.Write(func(tx *gorm.DB) error {
|
||||
return NodeSetExpiry(tx, nodeID, expiry)
|
||||
|
||||
@@ -79,6 +79,7 @@ CREATE TABLE nodes(
|
||||
host_info text,
|
||||
ipv4 text,
|
||||
ipv6 text,
|
||||
last_control_address text,
|
||||
hostname text,
|
||||
given_name varchar(63),
|
||||
-- user_id is NULL for tagged nodes (owned by tags, not a user).
|
||||
|
||||
@@ -827,6 +827,8 @@ func (ns *noiseServer) PollNetMapHandler(
|
||||
mapRequest.Hostinfo = mapRequest.Hostinfo.Clone()
|
||||
mapRequest.DebugFlags = nil
|
||||
|
||||
ns.recordLastControlAddress(nv, req.RemoteAddr)
|
||||
|
||||
sess := ns.headscale.newMapSession(req.Context(), mapRequest, writer, nv)
|
||||
sess.log.Trace().Caller().Msg("a node sending a MapRequest with Noise protocol")
|
||||
|
||||
@@ -1074,3 +1076,36 @@ func (ns *noiseServer) getAndValidateNode(mapRequest tailcfg.MapRequest) (types.
|
||||
|
||||
return nv, nil
|
||||
}
|
||||
|
||||
// recordLastControlAddress records the outer request's already-resolved peer
|
||||
// address after node-key and Noise machine-key validation. Failure to parse or
|
||||
// persist this auxiliary metadata must not break an otherwise valid map poll.
|
||||
func (ns *noiseServer) recordLastControlAddress(node types.NodeView, remoteAddr string) {
|
||||
addr, ok := parsePeerAddr(remoteAddr)
|
||||
if !ok {
|
||||
log.Warn().
|
||||
Str("remote_addr", remoteAddr).
|
||||
EmbedObject(node).
|
||||
Msg("could not parse node control connection address")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
changed, err := ns.headscale.state.SetLastControlAddress(node.ID(), addr.Unmap())
|
||||
if err != nil {
|
||||
log.Error().
|
||||
Err(err).
|
||||
Str("remote_addr", remoteAddr).
|
||||
EmbedObject(node).
|
||||
Msg("could not persist node control connection address")
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
if changed {
|
||||
log.Debug().
|
||||
Stringer("last_control_address", addr.Unmap()).
|
||||
EmbedObject(node).
|
||||
Msg("updated node control connection address")
|
||||
}
|
||||
}
|
||||
@@ -318,6 +318,118 @@ func TestPollNetMapHandler_OversizedBody(t *testing.T) {
|
||||
assert.Equal(t, http.StatusInternalServerError, rec.Code)
|
||||
}
|
||||
|
||||
func pollMapRequest(
|
||||
t *testing.T,
|
||||
ns *noiseServer,
|
||||
remoteAddr string,
|
||||
mapRequest tailcfg.MapRequest,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
|
||||
payload, err := json.Marshal(mapRequest)
|
||||
require.NoError(t, err)
|
||||
|
||||
req := httptest.NewRequestWithContext(
|
||||
t.Context(),
|
||||
http.MethodPost,
|
||||
"/machine/map",
|
||||
bytes.NewReader(payload),
|
||||
)
|
||||
req.RemoteAddr = remoteAddr
|
||||
rec := httptest.NewRecorder()
|
||||
|
||||
ns.PollNetMapHandler(rec, req)
|
||||
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestPollNetMapHandler_LastControlAddress(t *testing.T) {
|
||||
app := createTestApp(t)
|
||||
user := app.state.CreateUserForTest("control-address-user")
|
||||
node := app.state.CreateRegisteredNodeForTest(user, "control-address-node")
|
||||
node.User = user
|
||||
node.Endpoints = types.AddrPorts{
|
||||
netip.MustParseAddrPort("198.51.100.77:41641"),
|
||||
}
|
||||
view := app.state.PutNodeInStoreForTest(*node)
|
||||
|
||||
ns := &noiseServer{headscale: app, machineKey: view.MachineKey()}
|
||||
request := tailcfg.MapRequest{
|
||||
Version: tailcfg.CurrentCapabilityVersion,
|
||||
NodeKey: view.NodeKey(),
|
||||
OmitPeers: true,
|
||||
Endpoints: []netip.AddrPort{
|
||||
netip.MustParseAddrPort("198.51.100.77:41641"),
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
remoteAddr string
|
||||
want string
|
||||
}{
|
||||
{name: "direct IPv4 with port", remoteAddr: "203.0.113.10:52184", want: "203.0.113.10"},
|
||||
{name: "direct IPv6 with port", remoteAddr: "[2001:db8::10]:52184", want: "2001:db8::10"},
|
||||
{name: "trusted proxy IPv4 without port", remoteAddr: "192.0.2.44", want: "192.0.2.44"},
|
||||
{name: "trusted proxy IPv6 without port", remoteAddr: "2001:db8::44", want: "2001:db8::44"},
|
||||
{name: "IPv4-mapped IPv6", remoteAddr: "[::ffff:203.0.113.44]:52184", want: "203.0.113.44"},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
resp := pollMapRequest(t, ns, test.remoteAddr, request)
|
||||
require.Equalf(t, http.StatusOK, resp.Code, "body: %s", resp.Body)
|
||||
|
||||
stored, ok := app.state.GetNodeByID(view.ID())
|
||||
require.True(t, ok)
|
||||
require.True(t, stored.LastControlAddress().Valid())
|
||||
assert.Equal(t, test.want, stored.LastControlAddress().Get().String())
|
||||
})
|
||||
}
|
||||
|
||||
before, ok := app.state.GetNodeByID(view.ID())
|
||||
require.True(t, ok)
|
||||
require.True(t, before.LastControlAddress().Valid())
|
||||
wantUnchanged := before.LastControlAddress().Get()
|
||||
|
||||
t.Run("invalid address is ignored", func(t *testing.T) {
|
||||
resp := pollMapRequest(t, ns, "not-an-address", request)
|
||||
require.Equalf(t, http.StatusOK, resp.Code, "body: %s", resp.Body)
|
||||
|
||||
stored, ok := app.state.GetNodeByID(view.ID())
|
||||
require.True(t, ok)
|
||||
require.True(t, stored.LastControlAddress().Valid())
|
||||
assert.Equal(t, wantUnchanged, stored.LastControlAddress().Get())
|
||||
})
|
||||
|
||||
t.Run("machine key mismatch cannot overwrite", func(t *testing.T) {
|
||||
rogue := &noiseServer{headscale: app, machineKey: key.NewMachine().Public()}
|
||||
resp := pollMapRequest(t, rogue, "192.0.2.99:1234", request)
|
||||
assert.Equal(t, http.StatusNotFound, resp.Code)
|
||||
|
||||
stored, ok := app.state.GetNodeByID(view.ID())
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, wantUnchanged, stored.LastControlAddress().Get())
|
||||
})
|
||||
|
||||
t.Run("unknown node cannot overwrite", func(t *testing.T) {
|
||||
unknownRequest := request
|
||||
unknownRequest.NodeKey = key.NewNode().Public()
|
||||
resp := pollMapRequest(t, ns, "192.0.2.100:1234", unknownRequest)
|
||||
assert.Equal(t, http.StatusNotFound, resp.Code)
|
||||
|
||||
stored, ok := app.state.GetNodeByID(view.ID())
|
||||
require.True(t, ok)
|
||||
assert.Equal(t, wantUnchanged, stored.LastControlAddress().Get())
|
||||
})
|
||||
|
||||
api := registerAPIV2(t, app)
|
||||
attrs := getDevicePostureAttributes(t, api, view.StringID())
|
||||
assert.Equal(t, wantUnchanged.String(), attrs.Attributes["ip:publicAddress"])
|
||||
encodedAttrs, err := json.Marshal(attrs)
|
||||
require.NoError(t, err)
|
||||
assert.NotContains(t, string(encodedAttrs), "198.51.100.77",
|
||||
"reported Magicsock endpoints must not influence posture attributes")
|
||||
}
|
||||
|
||||
// TestRegistrationHandler_OversizedBody calls the real handler with a
|
||||
// [http.MaxBytesReader]-wrapped body to verify it returns an error response
|
||||
// rather than consuming unbounded memory.
|
||||
|
||||
@@ -38,6 +38,9 @@ const (
|
||||
DevicesRoutes Scope = "devices:routes"
|
||||
DevicesRoutesRead Scope = "devices:routes:read"
|
||||
|
||||
DevicesPostureAttributes Scope = "devices:posture_attributes"
|
||||
DevicesPostureAttributesRead Scope = "devices:posture_attributes:read"
|
||||
|
||||
PolicyFile Scope = "policy_file"
|
||||
PolicyFileRead Scope = "policy_file:read"
|
||||
|
||||
@@ -59,6 +62,7 @@ func Known() []Scope {
|
||||
OAuthKeys, OAuthKeysRead,
|
||||
DevicesCore, DevicesCoreRead,
|
||||
DevicesRoutes, DevicesRoutesRead,
|
||||
DevicesPostureAttributes, DevicesPostureAttributesRead,
|
||||
PolicyFile, PolicyFileRead,
|
||||
FeatureSettings, FeatureSettingsRead,
|
||||
Users, UsersRead,
|
||||
|
||||
@@ -71,7 +71,13 @@ func TestGrantsHandPicked(t *testing.T) {
|
||||
{granted: []Scope{AuthKeysRead}, want: AuthKeysRead, ok: true},
|
||||
{granted: []Scope{DevicesCore}, want: AuthKeys, ok: false},
|
||||
{granted: []Scope{DevicesCoreRead}, want: AuthKeysRead, ok: false},
|
||||
{granted: []Scope{DevicesPostureAttributesRead}, want: DevicesPostureAttributesRead, ok: true},
|
||||
{granted: []Scope{DevicesPostureAttributes}, want: DevicesPostureAttributesRead, ok: true},
|
||||
{granted: []Scope{DevicesPostureAttributesRead}, want: DevicesPostureAttributes, ok: false},
|
||||
{granted: []Scope{DevicesCoreRead}, want: DevicesPostureAttributesRead, ok: false},
|
||||
{granted: []Scope{All}, want: AuthKeys, ok: true},
|
||||
{granted: []Scope{All}, want: DevicesPostureAttributesRead, ok: true},
|
||||
{granted: []Scope{AllRead}, want: DevicesPostureAttributesRead, ok: true},
|
||||
{granted: []Scope{All}, want: FeatureSettingsRead, ok: true},
|
||||
{granted: []Scope{AllRead}, want: PolicyFileRead, ok: true},
|
||||
{granted: []Scope{AllRead}, want: PolicyFile, ok: false},
|
||||
@@ -201,6 +207,7 @@ func TestRequiresTags(t *testing.T) {
|
||||
{scopes: []Scope{DevicesCore}, requires: true},
|
||||
{scopes: []Scope{AuthKeys}, requires: true},
|
||||
{scopes: []Scope{OAuthKeys}, requires: false},
|
||||
{scopes: []Scope{DevicesPostureAttributes}, requires: false},
|
||||
{scopes: []Scope{PolicyFile, AuthKeys}, requires: true},
|
||||
{scopes: []Scope{DevicesCoreRead}, requires: false},
|
||||
{scopes: nil, requires: false},
|
||||
@@ -227,9 +234,9 @@ func TestKnownIsComplete(t *testing.T) {
|
||||
seen[s] = true
|
||||
}
|
||||
|
||||
// 7 resources × 2 (write+read) + 2 super-scopes = 16.
|
||||
if len(known) != 16 {
|
||||
t.Errorf("Known() has %d scopes, want 16", len(known))
|
||||
// 8 resources × 2 (write+read) + 2 super-scopes = 18.
|
||||
if len(known) != 18 {
|
||||
t.Errorf("Known() has %d scopes, want 18", len(known))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -165,6 +165,38 @@ func TestSnapshotFromNodes(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetLastControlAddressReusesPeerTopology(t *testing.T) {
|
||||
peerCalculations := 0
|
||||
nodes := types.Nodes{
|
||||
new(createTestNode(1, 1, "user1", "node1")),
|
||||
new(createTestNode(2, 1, "user1", "node2")),
|
||||
}
|
||||
store := NewNodeStore(nodes, func(nodes []types.NodeView) map[types.NodeID][]types.NodeID {
|
||||
peerCalculations++
|
||||
|
||||
return allowAllPeersFunc(nodes)
|
||||
}, 1, time.Millisecond)
|
||||
store.Start()
|
||||
t.Cleanup(store.Stop)
|
||||
|
||||
require.Equal(t, 1, peerCalculations)
|
||||
|
||||
addr := netip.MustParseAddr("203.0.113.10")
|
||||
updated, ok := store.UpdateNode(1, func(n *types.Node) {
|
||||
n.LastControlAddress = &addr
|
||||
})
|
||||
require.True(t, ok)
|
||||
require.True(t, updated.LastControlAddress().Valid())
|
||||
assert.Equal(t, addr, updated.LastControlAddress().Get())
|
||||
assert.Equal(t, 1, peerCalculations, "metadata must not recalculate peer membership")
|
||||
|
||||
peers := store.ListPeers(2)
|
||||
require.Equal(t, 1, peers.Len())
|
||||
require.True(t, peers.At(0).LastControlAddress().Valid())
|
||||
assert.Equal(t, addr, peers.At(0).LastControlAddress().Get(),
|
||||
"reused peer topology must contain refreshed node views")
|
||||
}
|
||||
|
||||
// Helper functions
|
||||
|
||||
func createTestNode(nodeID types.NodeID, userID uint, username, hostname string) types.Node {
|
||||
|
||||
@@ -316,6 +316,74 @@ func TestPersistEmptyEndpoints(t *testing.T) {
|
||||
"after restart, NodeStore should reflect the cleared endpoints")
|
||||
}
|
||||
|
||||
func TestSetLastControlAddressPersists(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
addr netip.Addr
|
||||
}{
|
||||
{name: "IPv4", addr: netip.MustParseAddr("203.0.113.10")},
|
||||
{name: "IPv6", addr: netip.MustParseAddr("2001:db8::10")},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
dbPath, s, nodeID := persistTestSetup(t)
|
||||
|
||||
require.NoError(t, s.db.DB.Exec(`
|
||||
CREATE TABLE last_control_address_writes(count integer);
|
||||
CREATE TRIGGER count_last_control_address_writes
|
||||
AFTER UPDATE OF last_control_address ON nodes
|
||||
BEGIN
|
||||
INSERT INTO last_control_address_writes VALUES(1);
|
||||
END;
|
||||
`).Error)
|
||||
|
||||
changed, err := s.SetLastControlAddress(nodeID, test.addr)
|
||||
require.NoError(t, err)
|
||||
require.True(t, changed)
|
||||
|
||||
var writes int64
|
||||
require.NoError(t, s.db.DB.Model(&struct{ Count int }{}).
|
||||
Table("last_control_address_writes").Count(&writes).Error)
|
||||
require.Equal(t, int64(1), writes)
|
||||
|
||||
changed, err = s.SetLastControlAddress(nodeID, test.addr)
|
||||
require.NoError(t, err)
|
||||
assert.False(t, changed, "the same address must be a no-op")
|
||||
|
||||
require.NoError(t, s.db.DB.Model(&struct{ Count int }{}).
|
||||
Table("last_control_address_writes").Count(&writes).Error)
|
||||
assert.Equal(t, int64(1), writes,
|
||||
"the same address must not issue another database update")
|
||||
require.NoError(t, s.db.DB.Exec(`
|
||||
DROP TRIGGER count_last_control_address_writes;
|
||||
DROP TABLE last_control_address_writes;
|
||||
`).Error)
|
||||
|
||||
nv, ok := s.GetNodeByID(nodeID)
|
||||
require.True(t, ok)
|
||||
|
||||
_, err = s.UpdateNodeFromMapRequest(nodeID, tailcfg.MapRequest{
|
||||
NodeKey: nv.NodeKey(),
|
||||
Hostinfo: &tailcfg.Hostinfo{Hostname: "updated-after-control-address"},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
stored, err := s.DB().GetNodeByID(nodeID)
|
||||
require.NoError(t, err)
|
||||
require.NotNil(t, stored.LastControlAddress)
|
||||
assert.Equal(t, test.addr, *stored.LastControlAddress,
|
||||
"an unrelated node update must preserve the address")
|
||||
|
||||
require.NoError(t, s.Close())
|
||||
s2 := persistTestReopen(t, dbPath)
|
||||
|
||||
reloaded, ok := s2.GetNodeByID(nodeID)
|
||||
require.True(t, ok)
|
||||
require.True(t, reloaded.LastControlAddress().Valid())
|
||||
assert.Equal(t, test.addr, reloaded.LastControlAddress().Get())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegistrationRejectsNodeKeyClaimedByAnotherMachine proves a new
|
||||
// registration cannot claim a NodeKey already bound to a different machine.
|
||||
// NodeKeys are public (peers learn them from the netmap), so without this
|
||||
|
||||
@@ -89,6 +89,9 @@ var ErrNodeNotFound = errors.New("node not found")
|
||||
// ErrInvalidNodeView is returned when an invalid node view is provided.
|
||||
var ErrInvalidNodeView = errors.New("invalid node view provided")
|
||||
|
||||
// ErrInvalidLastControlAddress is returned for a non-IP control address.
|
||||
var ErrInvalidLastControlAddress = errors.New("invalid last control address")
|
||||
|
||||
// ErrNodeNotInNodeStore is returned when a node no longer exists in the [NodeStore].
|
||||
var ErrNodeNotInNodeStore = errors.New("node no longer exists in NodeStore")
|
||||
|
||||
@@ -115,6 +118,7 @@ var nodeUpdateColumns = []string{
|
||||
"Hostinfo",
|
||||
"IPv4",
|
||||
"IPv6",
|
||||
"LastControlAddress",
|
||||
"Hostname",
|
||||
"GivenName",
|
||||
"UserID",
|
||||
@@ -128,6 +132,58 @@ var nodeUpdateColumns = []string{
|
||||
"UpdatedAt",
|
||||
}
|
||||
|
||||
// SetLastControlAddress stores the source IP most recently observed on an
|
||||
// authenticated control connection. The update is deliberately metadata-only:
|
||||
// it does not rescan policy or emit a peer-map change. Repeated observations of
|
||||
// the same address do not touch either the NodeStore or database.
|
||||
func (s *State) SetLastControlAddress(id types.NodeID, addr netip.Addr) (bool, error) {
|
||||
if !addr.IsValid() {
|
||||
return false, ErrInvalidLastControlAddress
|
||||
}
|
||||
|
||||
addr = addr.Unmap()
|
||||
|
||||
s.persistMu.Lock()
|
||||
defer s.persistMu.Unlock()
|
||||
|
||||
current, ok := s.nodeStore.GetNode(id)
|
||||
if !ok {
|
||||
return false, fmt.Errorf("%w: %d", ErrNodeNotInNodeStore, id)
|
||||
}
|
||||
|
||||
previous := current.LastControlAddress()
|
||||
if previous.Valid() && previous.Get() == addr {
|
||||
return false, nil
|
||||
}
|
||||
|
||||
_, ok = s.nodeStore.UpdateNode(id, func(n *types.Node) {
|
||||
n.LastControlAddress = &addr
|
||||
})
|
||||
if !ok {
|
||||
return false, fmt.Errorf("%w: %d", ErrNodeNotInNodeStore, id)
|
||||
}
|
||||
|
||||
err := s.db.SetLastControlAddress(id, addr)
|
||||
if err != nil {
|
||||
// Keep the in-memory source of truth aligned with the failed database
|
||||
// write so a later observation of the same address retries persistence.
|
||||
var old *netip.Addr
|
||||
|
||||
if previous.Valid() {
|
||||
addr := previous.Get()
|
||||
old = &addr
|
||||
}
|
||||
|
||||
s.nodeStore.UpdateNode(id, func(n *types.Node) {
|
||||
n.LastControlAddress = old
|
||||
})
|
||||
|
||||
return false, fmt.Errorf("persisting last control address: %w", err)
|
||||
}
|
||||
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// ErrRegistrationExpired is returned when a registration has expired.
|
||||
var ErrRegistrationExpired = errors.New("registration expired")
|
||||
|
||||
|
||||
@@ -143,6 +143,10 @@ type Node struct {
|
||||
IPv4 *netip.Addr `gorm:"column:ipv4;serializer:text"`
|
||||
IPv6 *netip.Addr `gorm:"column:ipv6;serializer:text"`
|
||||
|
||||
// LastControlAddress is the source IP most recently observed on an
|
||||
// authenticated control connection from this node.
|
||||
LastControlAddress *netip.Addr `gorm:"column:last_control_address;serializer:text"`
|
||||
|
||||
// Hostname represents the name given by the Tailscale
|
||||
// client during registration
|
||||
Hostname string
|
||||
|
||||
@@ -53,6 +53,9 @@ func (src *Node) Clone() *Node {
|
||||
if dst.IPv6 != nil {
|
||||
dst.IPv6 = new(*src.IPv6)
|
||||
}
|
||||
if dst.LastControlAddress != nil {
|
||||
dst.LastControlAddress = new(*src.LastControlAddress)
|
||||
}
|
||||
if dst.UserID != nil {
|
||||
dst.UserID = new(*src.UserID)
|
||||
}
|
||||
@@ -91,6 +94,7 @@ var _NodeCloneNeedsRegeneration = Node(struct {
|
||||
Hostinfo *tailcfg.Hostinfo
|
||||
IPv4 *netip.Addr
|
||||
IPv6 *netip.Addr
|
||||
LastControlAddress *netip.Addr
|
||||
Hostname string
|
||||
GivenName string
|
||||
UserID *uint
|
||||
|
||||
@@ -205,6 +205,12 @@ func (v NodeView) IPv4() views.ValuePointer[netip.Addr] { return views.ValuePo
|
||||
|
||||
func (v NodeView) IPv6() views.ValuePointer[netip.Addr] { return views.ValuePointerOf(v.ж.IPv6) }
|
||||
|
||||
// LastControlAddress is the source IP most recently observed on an
|
||||
// authenticated control connection from this node.
|
||||
func (v NodeView) LastControlAddress() views.ValuePointer[netip.Addr] {
|
||||
return views.ValuePointerOf(v.ж.LastControlAddress)
|
||||
}
|
||||
|
||||
// Hostname represents the name given by the Tailscale
|
||||
// client during registration
|
||||
func (v NodeView) Hostname() string { return v.ж.Hostname }
|
||||
@@ -311,6 +317,7 @@ var _NodeViewNeedsRegeneration = Node(struct {
|
||||
Hostinfo *tailcfg.Hostinfo
|
||||
IPv4 *netip.Addr
|
||||
IPv6 *netip.Addr
|
||||
LastControlAddress *netip.Addr
|
||||
Hostname string
|
||||
GivenName string
|
||||
UserID *uint
|
||||
|
||||
Reference in new issue
Block a user