Files
netbird/sharedsock/sock_linux_test.go
Zoltan Papp 2d7b309004 [client] Categorize privileged tests behind a build tag and run them in Docker (#6425)
* [client] categorize root/system-mutating tests behind a privileged build tag

Tests that need root or mutate host state (nftables/iptables/DNS, TUN/WireGuard
interfaces, routes, eBPF, SSH/service install) are now gated behind a
//go:build privileged tag. The default `go test ./client/...` runs as a non-root
user with no sudo and leaves host networking untouched; mixed files were split so
pure-logic tests stay in the default suite.

A self-hosting ory/dockertest/v4 harness (client/testutil/privileged) runs the
privileged suite inside a --privileged --cap-add=NET_ADMIN container via
`make test-privileged`; a DOCKER_CI=true guard skips the spawn when already inside
the container. Added `make test-unit` for the host-safe run.

* [client] add PRIV_RUN/PRIV_PKGS filters to the privileged test harness

The dockertest harness now reads two optional env vars when building the
in-container `go test` command: PRIV_RUN adds a -run test-name filter and
PRIV_PKGS overrides the package list. Both empty reproduce the full privileged
suite, so CI and `make test-privileged` behave as before. Lets a developer run a
single privileged test in the container, e.g.:

  PRIV_RUN=TestNftablesManager PRIV_PKGS=./client/firewall/nftables/... make test-privileged

* [client] fix unused-helper lint after the privileged test split

Splitting privileged tests into *_privileged_test.go left their shared helpers in
the untagged files, so in the default (no-tag) build they had no callers and
golangci-lint flagged them as unused.

Moved the privileged-only helpers into the privileged files next to their callers
(generateDummyHandler; createEngine/startSignal/startManagement/getConnectedPeers/
getPeers + kaep/kasp; (*mockDaemon).setJWTToken). Annotated the shared routing-test
fixtures that must stay untagged for cross-platform compilation with //nolint:unused
(systemops_bsd expected* vars, ensureIPv6DefaultRoute on bsd/windows,
loopbackIfaceWindows), matching the existing linux variant.

* [client] fix privileged test CI failures and run the harness on macOS

The host-safe unit run dropped sudo but two privileged test groups were
never tagged, and the Docker privileged job silently never ran the suite:

- Gate the ssh/server PrivilegeDropper command-construction tests behind
  the privileged tag (they require root to target a different UID); split
  them into executor_unix_privileged_test.go.
- Tag sharedsock raw-socket tests privileged (need CAP_NET_RAW).
- Fix the Docker job command: nested single quotes around the build tags
  closed the sh -c wrapper early, dropping the go list package set and the
  privileged tag, so go test ran on the empty repo root. Use double quotes.

Make the self-hosting harness usable from a dev Mac:

- Build it on darwin as well as linux; it only drives Docker.
- Resolve the active docker context endpoint into DOCKER_HOST when the
  default /var/run/docker.sock is absent (Docker Desktop, Colima, OrbStack).
- Rename the misspelled containerGoModache constant to containerGoModCache.

* Update client/internal/engine_privileged_test.go

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update client/internal/routemanager/systemops/systemops_linux_test.go

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update client/internal/routemanager/systemops/systemops_windows_test.go

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update client/server/server_privileged_test.go

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* [ci] Run privileged-tagged tests on darwin, windows and freebsd

The privileged build tag split moved root/system-mutating tests behind
//go:build privileged, but only the linux docker job was given the tag.
The native darwin (sudo), windows (PsExec64 -s) and freebsd VM runners
already have the required privileges, so add the privileged tag there too
to keep CI running the same set of tests as before the split.

* [ci] Exclude dockertest harness from the darwin privileged run

The privileged tag now compiles client/testutil/privileged on darwin, whose
TestRunPrivilegedSuiteInDocker spawns a container the macOS runner has no
Docker for. Exclude the harness package from the darwin list, matching the
linux job, so the privileged tests run in place without a container spawn.

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-06-28 16:15:54 +02:00

165 lines
5.1 KiB
Go

//go:build privileged
package sharedsock
import (
"context"
"errors"
"fmt"
"net"
"net/netip"
"os"
"sync"
"testing"
"time"
"github.com/pion/stun/v2"
log "github.com/sirupsen/logrus"
"github.com/stretchr/testify/require"
"golang.org/x/sync/errgroup"
)
func TestShouldReadSTUNOnReadFrom(t *testing.T) {
// create raw socket on a port
testingPort := 51821
rawSock, err := Listen(testingPort, NewIncomingSTUNFilter(), 1280)
require.NoError(t, err, "received an error while creating STUN listener, error: %s", err)
err = rawSock.SetReadDeadline(time.Now().Add(3 * time.Second))
require.NoError(t, err, "unable to set deadline, error: %s", err)
wg := sync.WaitGroup{}
wg.Add(1)
// when reading from the raw socket
buf := make([]byte, 1500)
rcvMSG := &stun.Message{
Raw: buf,
}
ctx, cancel := context.WithTimeout(context.TODO(), 10*time.Second)
defer cancel()
go func() {
select {
case <-ctx.Done():
return
default:
_, _, err := rawSock.ReadFrom(buf)
if err != nil {
log.Errorf("error while reading packet %s", err)
return
}
err = rcvMSG.Decode()
if err != nil {
log.Warnf("error while parsing STUN message. The packet doesn't seem to be a STUN packet: %s", err)
return
}
wg.Done()
}
}()
// and sending STUN packet to the shared port, the packet has to be handled
udpListener, err := net.ListenUDP("udp", &net.UDPAddr{Port: 12345, IP: net.ParseIP("127.0.0.1")})
require.NoError(t, err, "received an error while creating regular listener, error: %s", err)
defer udpListener.Close()
stunMSG, err := stun.Build(stun.NewType(stun.MethodBinding, stun.ClassRequest), stun.TransactionID,
stun.Fingerprint,
)
require.NoError(t, err, "unable to build stun msg, error: %s", err)
_, err = udpListener.WriteTo(stunMSG.Raw, net.UDPAddrFromAddrPort(netip.MustParseAddrPort(fmt.Sprintf("127.0.0.1:%d", testingPort))))
require.NoError(t, err, "received an error while writing the stun listener, error: %s", err)
// the packet has to be handled and be a STUN packet
wg.Wait()
require.EqualValues(t, stunMSG.TransactionID, rcvMSG.TransactionID, "transaction id values did't match")
}
func TestShouldNotReadNonSTUNPackets(t *testing.T) {
testingPort := 39439
rawSock, err := Listen(testingPort, NewIncomingSTUNFilter(), 1280)
require.NoError(t, err, "received an error while creating STUN listener, error: %s", err)
defer rawSock.Close()
buf := make([]byte, 1500)
err = rawSock.SetReadDeadline(time.Now().Add(time.Second))
require.NoError(t, err, "unable to set deadline, error: %s", err)
errGrp := errgroup.Group{}
errGrp.Go(func() error {
_, _, err := rawSock.ReadFrom(buf)
return err
})
nonStun := []byte("netbird")
udpListener, err := net.ListenUDP("udp", &net.UDPAddr{Port: 0, IP: net.ParseIP("127.0.0.1")})
require.NoError(t, err, "received an error while creating regular listener, error: %s", err)
defer udpListener.Close()
remote := net.UDPAddrFromAddrPort(netip.MustParseAddrPort(fmt.Sprintf("127.0.0.1:%d", testingPort)))
_, err = udpListener.WriteTo(nonStun, remote)
require.NoError(t, err, "received an error while writing the stun listener, error: %s", err)
err = errGrp.Wait()
require.Error(t, err, "should receive an error")
if !errors.Is(err, os.ErrDeadlineExceeded) {
t.Errorf("error should be I/O timeout, got: %s", err)
}
}
func TestWriteTo(t *testing.T) {
udpListener, err := net.ListenUDP("udp4", &net.UDPAddr{Port: 0, IP: net.ParseIP("127.0.0.1")})
require.NoError(t, err, "received an error while creating regular listener, error: %s", err)
defer udpListener.Close()
testingPort := 39440
rawSock, err := Listen(testingPort, NewIncomingSTUNFilter(), 1280)
require.NoError(t, err, "received an error while creating STUN listener, error: %s", err)
defer rawSock.Close()
buf := make([]byte, 1500)
err = udpListener.SetReadDeadline(time.Now().Add(3 * time.Second))
require.NoError(t, err, "unable to set deadline, error: %s", err)
errGrp := errgroup.Group{}
var remoteAdr net.Addr
var rcvBytes int
errGrp.Go(func() error {
n, a, err := udpListener.ReadFrom(buf)
remoteAdr = a
rcvBytes = n
return err
})
msg := []byte("netbird")
_, err = rawSock.WriteTo(msg, udpListener.LocalAddr())
require.NoError(t, err, "received an error while writing the stun listener, error: %s", err)
err = errGrp.Wait()
require.NoError(t, err, "received an error while reading the packet, error: %s", err)
require.EqualValues(t, string(msg), string(buf[:rcvBytes]), "received message should match")
udpRcv, ok := remoteAdr.(*net.UDPAddr)
require.True(t, ok, "udp address conversion didn't work")
require.EqualValues(t, testingPort, udpRcv.Port, "received address port didn't match")
}
func TestSharedSocket_Close(t *testing.T) {
rawSock, err := Listen(39440, NewIncomingSTUNFilter(), 1280)
require.NoError(t, err, "received an error while creating STUN listener, error: %s", err)
errGrp := errgroup.Group{}
errGrp.Go(func() error {
buf := make([]byte, 1500)
_, _, err := rawSock.ReadFrom(buf)
return err
})
_ = rawSock.Close()
err = errGrp.Wait()
if err != ErrSharedSockStopped {
t.Errorf("invalid error response: %s", err)
}
}