Compare commits

...

4 Commits

Author SHA1 Message Date
copilot-swe-agent[bot]
1f4b645d5b Refactor: Extract route filtering logic into helper function
Addressed code review feedback:
- Extracted duplicated exit route filtering logic into buildRouteFilterFunc
- Reused exitNode lookup in integration test to avoid duplication
- Added missing matcher package import

This improves code maintainability while preserving the same functionality.

Co-authored-by: kradalby <98431+kradalby@users.noreply.github.com>
2025-11-01 09:05:37 +00:00
copilot-swe-agent[bot]
4fa1f4baa3 Add integration test for exit node ACL visibility (issue #2788)
Added TestExitNodeVisibilityWithACL to verify that exit nodes are only
visible to nodes that have permission according to ACL policy. The test:
- Creates 3 nodes: mobile, server, and exit-owner
- Sets up ACL allowing only mobile->server:80 (no autogroup:internet)
- Advertises and approves exit routes on exit-owner node
- Verifies mobile and server do NOT see exit node in peer list

This is a regression test for issue #2788 where exit nodes were visible
to all nodes regardless of ACL policy.

Co-authored-by: kradalby <98431+kradalby@users.noreply.github.com>
2025-11-01 08:54:29 +00:00
copilot-swe-agent[bot]
e0107024e8 Filter exit routes through ACL policy to fix issue #2788
Exit nodes are now only visible to nodes that have permission to use them
according to ACL policy. Previously, exit routes (0.0.0.0/0 and ::/0) were
unconditionally added to the AllowedIPs field in the network map, making
exit nodes visible to all peers regardless of policy.

Changes:
- Modified buildTailPeers and WithSelfNode in builder.go to filter exit
  routes through policy.ReduceRoutes, same as primary routes
- Removed unconditional addition of exit routes in tail.go tailNode function
- Updated tail_test.go to reflect new behavior where exit routes are filtered

The fix ensures that exit nodes are only visible when a node has
autogroup:internet in their ACL destination rules.

Co-authored-by: kradalby <98431+kradalby@users.noreply.github.com>
2025-11-01 08:52:29 +00:00
copilot-swe-agent[bot]
a55cdc2636 Initial plan 2025-11-01 08:27:52 +00:00
4 changed files with 182 additions and 9 deletions

View File

@@ -7,6 +7,7 @@ import (
"time"
"github.com/juanfont/headscale/hscontrol/policy"
"github.com/juanfont/headscale/hscontrol/policy/matcher"
"github.com/juanfont/headscale/hscontrol/types"
"tailscale.com/tailcfg"
"tailscale.com/types/views"
@@ -67,6 +68,33 @@ func (b *MapResponseBuilder) WithCapabilityVersion(capVer tailcfg.CapabilityVers
return b
}
// buildRouteFilterFunc creates a route filter function that includes both primary and exit routes.
// It filters routes based on ACL policy to ensure only authorized routes are visible.
func (b *MapResponseBuilder) buildRouteFilterFunc(
viewingNode types.NodeView,
matchers []matcher.Match,
) routeFilterFunc {
return func(id types.NodeID) []netip.Prefix {
// Get the peer node to check for exit routes
peer, ok := b.mapper.state.GetNodeByID(id)
if !ok {
return nil
}
// Start with primary routes (subnet routes, but not exit routes)
routes := policy.ReduceRoutes(viewingNode, b.mapper.state.GetNodePrimaryRoutes(id), matchers)
// Also filter exit routes through policy
// Only add exit routes if the viewing node has permission to use them
if exitRoutes := peer.ExitRoutes(); len(exitRoutes) > 0 {
filteredExitRoutes := policy.ReduceRoutes(viewingNode, exitRoutes, matchers)
routes = append(routes, filteredExitRoutes...)
}
return routes
}
}
// WithSelfNode adds the requesting node to the response.
func (b *MapResponseBuilder) WithSelfNode() *MapResponseBuilder {
nv, ok := b.mapper.state.GetNodeByID(b.nodeID)
@@ -78,9 +106,7 @@ func (b *MapResponseBuilder) WithSelfNode() *MapResponseBuilder {
_, matchers := b.mapper.state.Filter()
tailnode, err := tailNode(
nv, b.capVer, b.mapper.state,
func(id types.NodeID) []netip.Prefix {
return policy.ReduceRoutes(nv, b.mapper.state.GetNodePrimaryRoutes(id), matchers)
},
b.buildRouteFilterFunc(nv, matchers),
b.mapper.cfg)
if err != nil {
b.addError(err)
@@ -253,9 +279,7 @@ func (b *MapResponseBuilder) buildTailPeers(peers views.Slice[types.NodeView]) (
tailPeers, err := tailNodes(
changedViews, b.capVer, b.mapper.state,
func(id types.NodeID) []netip.Prefix {
return policy.ReduceRoutes(node, b.mapper.state.GetNodePrimaryRoutes(id), matchers)
},
b.buildRouteFilterFunc(node, matchers),
b.mapper.cfg)
if err != nil {
return nil, err

View File

@@ -88,9 +88,9 @@ func tailNode(
}
tags = lo.Uniq(tags)
// Get filtered routes (includes both primary routes and exit routes if allowed by policy)
routes := primaryRouteFunc(node.ID())
allowed := append(addrs, routes...)
allowed = append(allowed, node.ExitRoutes()...)
tsaddr.SortPrefixes(allowed)
tNode := tailcfg.Node{

View File

@@ -137,10 +137,8 @@ func TestTailNode(t *testing.T) {
),
Addresses: []netip.Prefix{netip.MustParsePrefix("100.64.0.1/32")},
AllowedIPs: []netip.Prefix{
tsaddr.AllIPv4(),
netip.MustParsePrefix("192.168.0.0/24"),
netip.MustParsePrefix("100.64.0.1/32"),
tsaddr.AllIPv6(),
},
PrimaryRoutes: []netip.Prefix{
netip.MustParsePrefix("192.168.0.0/24"),

View File

@@ -3042,3 +3042,154 @@ func TestSubnetRouteACLFiltering(t *testing.T) {
assertTracerouteViaIPWithCollect(c, tr, ip)
}, 20*time.Second, 200*time.Millisecond, "Verifying traceroute goes through router")
}
// TestExitNodeVisibilityWithACL tests that exit nodes are only visible
// to nodes that have permission to use them according to ACL policy.
// This is a regression test for issue #2788.
func TestExitNodeVisibilityWithACL(t *testing.T) {
IntegrationSkip(t)
spec := ScenarioSpec{
NodesPerUser: 1,
Users: []string{"mobile", "server", "exit-owner"},
}
scenario, err := NewScenario(spec)
require.NoErrorf(t, err, "failed to create scenario: %s", err)
defer scenario.ShutdownAssertNoPanics(t)
// Policy that allows:
// - mobile can communicate with server on port 80
// - mobile does NOT have autogroup:internet, so should NOT see exit node
policy := `
{
"hosts": {
"mobile": "100.64.0.1/32",
"server": "100.64.0.2/32",
"exit": "100.64.0.3/32"
},
"acls": [
{
"action": "accept",
"src": ["mobile"],
"dst": ["server:80"]
}
]
}
`
err = scenario.CreateHeadscaleEnv(
[]tsic.Option{},
hsic.WithTestName("exitnodeacl"),
hsic.WithConfigEnv(map[string]string{
"HEADSCALE_POLICY_MODE": "file",
"HEADSCALE_POLICY_PATH": "/etc/headscale/policy.json",
}),
hsic.WithFileInContainer("/etc/headscale/policy.json", []byte(policy)),
)
requireNoErrHeadscaleEnv(t, err)
allClients, err := scenario.ListTailscaleClients()
requireNoErrListClients(t, err)
require.Len(t, allClients, 3)
err = scenario.WaitForTailscaleSync()
requireNoErrSync(t, err)
headscale, err := scenario.Headscale()
requireNoErrGetHeadscale(t, err)
// Find the clients
var mobileClient, serverClient, exitClient TailscaleClient
for _, client := range allClients {
status := client.MustStatus()
switch status.User[status.Self.UserID].LoginName {
case "mobile@test.no":
mobileClient = client
case "server@test.no":
serverClient = client
case "exit-owner@test.no":
exitClient = client
}
}
require.NotNil(t, mobileClient, "mobile client not found")
require.NotNil(t, serverClient, "server client not found")
require.NotNil(t, exitClient, "exit client not found")
// Advertise exit node from the exit-owner node
_, _, err = exitClient.Execute([]string{
"tailscale",
"set",
"--advertise-exit-node",
})
require.NoErrorf(t, err, "failed to advertise exit node: %s", err)
// Wait for the exit node to be registered
var nodes []*v1.Node
var exitNode *v1.Node
exitStatus := exitClient.MustStatus()
assert.EventuallyWithT(t, func(c *assert.CollectT) {
nodes, err = headscale.ListNodes()
assert.NoError(c, err)
assert.Len(c, nodes, 3)
// Find the exit node
exitNode = nil
for _, node := range nodes {
if node.GetName() == exitStatus.Self.HostName {
exitNode = node
break
}
}
assert.NotNil(c, exitNode, "exit node not found")
if exitNode != nil {
// Exit node should have 2 available routes (0.0.0.0/0 and ::/0)
assert.Len(c, exitNode.GetAvailableRoutes(), 2, "exit node should advertise 2 routes")
}
}, 10*time.Second, 500*time.Millisecond, "waiting for exit node advertisement")
// Approve the exit routes
require.NotNil(t, exitNode, "exit node not found after advertisement")
_, err = headscale.ApproveRoutes(exitNode.GetId(), []netip.Prefix{tsaddr.AllIPv4(), tsaddr.AllIPv6()})
require.NoError(t, err, "failed to approve exit routes")
// Wait for routes to be approved in the database
assert.EventuallyWithT(t, func(c *assert.CollectT) {
nodes, err = headscale.ListNodes()
assert.NoError(c, err)
for _, node := range nodes {
if node.GetName() == exitStatus.Self.HostName {
assert.Len(c, node.GetApprovedRoutes(), 2, "exit node should have 2 approved routes")
assert.Len(c, node.GetSubnetRoutes(), 2, "exit node should have 2 subnet routes")
}
}
}, 10*time.Second, 500*time.Millisecond, "waiting for route approval")
// The key test: mobile client should NOT see the exit node in their peer list
// because they don't have autogroup:internet in their ACL
assert.EventuallyWithT(t, func(c *assert.CollectT) {
status, err := mobileClient.Status()
assert.NoError(c, err)
// Mobile should see server as a peer (allowed by ACL)
serverStatus := serverClient.MustStatus()
_, hasPeer := status.Peer[serverStatus.Self.PublicKey]
assert.True(c, hasPeer, "mobile should see server as peer")
// Mobile should NOT see exit node in peer list at all since no ACL allows access
_, hasExitPeer := status.Peer[exitStatus.Self.PublicKey]
assert.False(c, hasExitPeer, "mobile should NOT see exit node as peer without autogroup:internet in ACL")
}, 10*time.Second, 500*time.Millisecond, "verifying mobile cannot see exit node")
// Server should also not see the exit node (no ACL rule allowing it)
assert.EventuallyWithT(t, func(c *assert.CollectT) {
status, err := serverClient.Status()
assert.NoError(c, err)
_, hasExitPeer := status.Peer[exitStatus.Self.PublicKey]
assert.False(c, hasExitPeer, "server should NOT see exit node as peer without autogroup:internet in ACL")
}, 10*time.Second, 500*time.Millisecond, "verifying server cannot see exit node")
}