all: fix golangci-lint issues (#3064)

This commit is contained in:
Kristoffer Dalby 2026-02-06 21:45:32 +01:00 committed by GitHub
parent bfb6fd80df
commit ce580f8245
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
131 changed files with 3131 additions and 1560 deletions

View file

@ -96,7 +96,7 @@ type User struct {
type Scenario struct {
// TODO(kradalby): support multiple headcales for later, currently only
// use one.
controlServers *xsync.MapOf[string, ControlServer]
controlServers *xsync.Map[string, ControlServer]
derpServers []*dsic.DERPServerInContainer
users map[string]*User
@ -169,8 +169,8 @@ func NewScenario(spec ScenarioSpec) (*Scenario, error) {
// Opportunity to clean up unreferenced networks.
// This might be a no op, but it is worth a try as we sometime
// dont clean up nicely after ourselves.
dockertestutil.CleanUnreferencedNetworks(pool)
dockertestutil.CleanImagesInCI(pool)
_ = dockertestutil.CleanUnreferencedNetworks(pool)
_ = dockertestutil.CleanImagesInCI(pool)
if spec.MaxWait == 0 {
pool.MaxWait = dockertestMaxWait()
@ -180,7 +180,7 @@ func NewScenario(spec ScenarioSpec) (*Scenario, error) {
testHashPrefix := "hs-" + util.MustGenerateRandomStringDNSSafe(scenarioHashLength)
s := &Scenario{
controlServers: xsync.NewMapOf[string, ControlServer](),
controlServers: xsync.NewMap[string, ControlServer](),
users: make(map[string]*User),
pool: pool,
@ -191,9 +191,11 @@ func NewScenario(spec ScenarioSpec) (*Scenario, error) {
}
var userToNetwork map[string]*dockertest.Network
if spec.Networks != nil || len(spec.Networks) != 0 {
for name, users := range s.spec.Networks {
networkName := testHashPrefix + "-" + name
network, err := s.AddNetwork(networkName)
if err != nil {
return nil, err
@ -201,8 +203,9 @@ func NewScenario(spec ScenarioSpec) (*Scenario, error) {
for _, user := range users {
if n2, ok := userToNetwork[user]; ok {
return nil, fmt.Errorf("users can only have nodes placed in one network: %s into %s but already in %s", user, network.Network.Name, n2.Network.Name)
return nil, fmt.Errorf("users can only have nodes placed in one network: %s into %s but already in %s", user, network.Network.Name, n2.Network.Name) //nolint:err113
}
mak.Set(&userToNetwork, user, network)
}
}
@ -219,6 +222,7 @@ func NewScenario(spec ScenarioSpec) (*Scenario, error) {
if err != nil {
return nil, err
}
mak.Set(&s.extraServices, s.prefixedNetworkName(network), append(s.extraServices[s.prefixedNetworkName(network)], svc))
}
}
@ -230,6 +234,7 @@ func NewScenario(spec ScenarioSpec) (*Scenario, error) {
if spec.OIDCAccessTTL != 0 {
ttl = spec.OIDCAccessTTL
}
err = s.runMockOIDC(ttl, spec.OIDCUsers)
if err != nil {
return nil, err
@ -268,13 +273,14 @@ func (s *Scenario) Networks() []*dockertest.Network {
if len(s.networks) == 0 {
panic("Scenario.Networks called with empty network list")
}
return xmaps.Values(s.networks)
}
func (s *Scenario) Network(name string) (*dockertest.Network, error) {
net, ok := s.networks[s.prefixedNetworkName(name)]
if !ok {
return nil, fmt.Errorf("no network named: %s", name)
return nil, fmt.Errorf("no network named: %s", name) //nolint:err113
}
return net, nil
@ -283,11 +289,11 @@ func (s *Scenario) Network(name string) (*dockertest.Network, error) {
func (s *Scenario) SubnetOfNetwork(name string) (*netip.Prefix, error) {
net, ok := s.networks[s.prefixedNetworkName(name)]
if !ok {
return nil, fmt.Errorf("no network named: %s", name)
return nil, fmt.Errorf("no network named: %s", name) //nolint:err113
}
if len(net.Network.IPAM.Config) == 0 {
return nil, fmt.Errorf("no IPAM config found in network: %s", name)
return nil, fmt.Errorf("no IPAM config found in network: %s", name) //nolint:err113
}
pref, err := netip.ParsePrefix(net.Network.IPAM.Config[0].Subnet)
@ -301,15 +307,17 @@ func (s *Scenario) SubnetOfNetwork(name string) (*netip.Prefix, error) {
func (s *Scenario) Services(name string) ([]*dockertest.Resource, error) {
res, ok := s.extraServices[s.prefixedNetworkName(name)]
if !ok {
return nil, fmt.Errorf("no network named: %s", name)
return nil, fmt.Errorf("no network named: %s", name) //nolint:err113
}
return res, nil
}
func (s *Scenario) ShutdownAssertNoPanics(t *testing.T) {
defer dockertestutil.CleanUnreferencedNetworks(s.pool)
defer dockertestutil.CleanImagesInCI(s.pool)
t.Helper()
defer func() { _ = dockertestutil.CleanUnreferencedNetworks(s.pool) }()
defer func() { _ = dockertestutil.CleanImagesInCI(s.pool) }()
s.controlServers.Range(func(_ string, control ControlServer) bool {
stdoutPath, stderrPath, err := control.Shutdown()
@ -334,9 +342,11 @@ func (s *Scenario) ShutdownAssertNoPanics(t *testing.T) {
})
s.mu.Lock()
for userName, user := range s.users {
for _, client := range user.Clients {
log.Printf("removing client %s in user %s", client.Hostname(), userName)
stdoutPath, stderrPath, err := client.Shutdown()
if err != nil {
log.Printf("tearing down client: %s", err)
@ -353,6 +363,7 @@ func (s *Scenario) ShutdownAssertNoPanics(t *testing.T) {
}
}
}
s.mu.Unlock()
for _, derp := range s.derpServers {
@ -373,13 +384,16 @@ func (s *Scenario) ShutdownAssertNoPanics(t *testing.T) {
if s.mockOIDC.r != nil {
s.mockOIDC.r.Close()
if err := s.mockOIDC.r.Close(); err != nil {
err := s.mockOIDC.r.Close()
if err != nil {
log.Printf("tearing down oidc server: %s", err)
}
}
for _, network := range s.networks {
if err := network.Close(); err != nil {
err := network.Close()
if err != nil {
log.Printf("tearing down network: %s", err)
}
}
@ -395,7 +409,7 @@ func (s *Scenario) Shutdown() {
// Users returns the name of all users associated with the Scenario.
func (s *Scenario) Users() []string {
users := make([]string, 0)
users := make([]string, 0, len(s.users))
for user := range s.users {
users = append(users, user)
}
@ -466,7 +480,7 @@ func (s *Scenario) CreatePreAuthKey(
reusable bool,
ephemeral bool,
) (*v1.PreAuthKey, error) {
if headscale, err := s.Headscale(); err == nil {
if headscale, err := s.Headscale(); err == nil { //nolint:noinlineerr
key, err := headscale.CreateAuthKey(user, reusable, ephemeral)
if err != nil {
return nil, fmt.Errorf("creating user: %w", err)
@ -518,7 +532,7 @@ func (s *Scenario) CreatePreAuthKeyWithTags(
// CreateUser creates a User to be created in the
// Headscale instance on behalf of the Scenario.
func (s *Scenario) CreateUser(user string) (*v1.User, error) {
if headscale, err := s.Headscale(); err == nil {
if headscale, err := s.Headscale(); err == nil { //nolint:noinlineerr
u, err := headscale.CreateUser(user)
if err != nil {
return nil, fmt.Errorf("creating user: %w", err)
@ -552,6 +566,7 @@ func (s *Scenario) CreateTailscaleNode(
s.mu.Lock()
defer s.mu.Unlock()
opts = append(opts,
tsic.WithCACert(cert),
tsic.WithHeadscaleName(hostname),
@ -591,6 +606,7 @@ func (s *Scenario) CreateTailscaleNodesInUser(
) error {
if user, ok := s.users[userStr]; ok {
var versions []string
for i := range count {
version := requestedVersion
if requestedVersion == "all" {
@ -600,6 +616,7 @@ func (s *Scenario) CreateTailscaleNodesInUser(
version = MustTestVersions[i%len(MustTestVersions)]
}
}
versions = append(versions, version)
headscale, err := s.Headscale()
@ -623,6 +640,7 @@ func (s *Scenario) CreateTailscaleNodesInUser(
extraHosts := []string{hostname + ":" + headscaleIP}
s.mu.Lock()
opts = append(opts,
tsic.WithCACert(cert),
tsic.WithHeadscaleName(hostname),
@ -639,6 +657,7 @@ func (s *Scenario) CreateTailscaleNodesInUser(
opts...,
)
s.mu.Unlock()
if err != nil {
return fmt.Errorf(
"creating tailscale node: %w",
@ -656,13 +675,17 @@ func (s *Scenario) CreateTailscaleNodesInUser(
}
s.mu.Lock()
user.Clients[tsClient.Hostname()] = tsClient
s.mu.Unlock()
return nil
})
}
if err := user.createWaitGroup.Wait(); err != nil {
err := user.createWaitGroup.Wait()
if err != nil {
return err
}
@ -682,12 +705,14 @@ func (s *Scenario) RunTailscaleUp(
if user, ok := s.users[userStr]; ok {
for _, client := range user.Clients {
c := client
user.joinWaitGroup.Go(func() error {
return c.Login(loginServer, authKey)
})
}
if err := user.joinWaitGroup.Wait(); err != nil {
err := user.joinWaitGroup.Wait()
if err != nil {
return err
}
@ -749,11 +774,14 @@ func (s *Scenario) WaitForTailscaleSyncPerUser(timeout, retryInterval time.Durat
for _, client := range user.Clients {
c := client
expectedCount := expectedPeers
user.syncWaitGroup.Go(func() error {
return c.WaitForPeers(expectedCount, timeout, retryInterval)
})
}
if err := user.syncWaitGroup.Wait(); err != nil {
err := user.syncWaitGroup.Wait()
if err != nil {
allErrors = append(allErrors, err)
}
}
@ -773,11 +801,14 @@ func (s *Scenario) WaitForTailscaleSyncWithPeerCount(peerCount int, timeout, ret
for _, user := range s.users {
for _, client := range user.Clients {
c := client
user.syncWaitGroup.Go(func() error {
return c.WaitForPeers(peerCount, timeout, retryInterval)
})
}
if err := user.syncWaitGroup.Wait(); err != nil {
err := user.syncWaitGroup.Wait()
if err != nil {
allErrors = append(allErrors, err)
}
}
@ -871,6 +902,7 @@ func (s *Scenario) createHeadscaleEnvWithTags(
} else {
key, err = s.CreatePreAuthKey(u.GetId(), true, false)
}
if err != nil {
return err
}
@ -887,9 +919,11 @@ func (s *Scenario) createHeadscaleEnvWithTags(
func (s *Scenario) RunTailscaleUpWithURL(userStr, loginServer string) error {
log.Printf("running tailscale up for user %s", userStr)
if user, ok := s.users[userStr]; ok {
for _, client := range user.Clients {
tsc := client
user.joinWaitGroup.Go(func() error {
loginURL, err := tsc.LoginWithURL(loginServer)
if err != nil {
@ -904,7 +938,7 @@ func (s *Scenario) RunTailscaleUpWithURL(userStr, loginServer string) error {
// If the URL is not a OIDC URL, then we need to
// run the register command to fully log in the client.
if !strings.Contains(loginURL.String(), "/oidc/") {
s.runHeadscaleRegister(userStr, body)
_ = s.runHeadscaleRegister(userStr, body)
}
return nil
@ -913,7 +947,8 @@ func (s *Scenario) RunTailscaleUpWithURL(userStr, loginServer string) error {
log.Printf("client %s is ready", client.Hostname())
}
if err := user.joinWaitGroup.Wait(); err != nil {
err := user.joinWaitGroup.Wait()
if err != nil {
return err
}
@ -945,6 +980,7 @@ func newDebugJar() (*debugJar, error) {
if err != nil {
return nil, err
}
return &debugJar{
inner: jar,
store: make(map[string]map[string]map[string]*http.Cookie),
@ -961,20 +997,25 @@ func (j *debugJar) SetCookies(u *url.URL, cookies []*http.Cookie) {
if c == nil || c.Name == "" {
continue
}
domain := c.Domain
if domain == "" {
domain = u.Hostname()
}
path := c.Path
if path == "" {
path = "/"
}
if _, ok := j.store[domain]; !ok {
j.store[domain] = make(map[string]map[string]*http.Cookie)
}
if _, ok := j.store[domain][path]; !ok {
j.store[domain][path] = make(map[string]*http.Cookie)
}
j.store[domain][path][c.Name] = copyCookie(c)
}
}
@ -989,8 +1030,10 @@ func (j *debugJar) Dump(w io.Writer) {
for domain, paths := range j.store {
fmt.Fprintf(w, "Domain: %s\n", domain)
for path, byName := range paths {
fmt.Fprintf(w, " Path: %s\n", path)
for _, c := range byName {
fmt.Fprintf(
w, " %s=%s; Expires=%v; Secure=%v; HttpOnly=%v; SameSite=%v\n",
@ -1046,15 +1089,17 @@ func doLoginURLWithClient(hostname string, loginURL *url.URL, hc *http.Client, f
error,
) {
if hc == nil {
return "", nil, fmt.Errorf("%s http client is nil", hostname)
return "", nil, fmt.Errorf("%s http client is nil", hostname) //nolint:err113
}
if loginURL == nil {
return "", nil, fmt.Errorf("%s login url is nil", hostname)
return "", nil, fmt.Errorf("%s login url is nil", hostname) //nolint:err113
}
log.Printf("%s logging in with url: %s", hostname, loginURL.String())
ctx := context.Background()
req, err := http.NewRequestWithContext(ctx, http.MethodGet, loginURL.String(), nil)
if err != nil {
return "", nil, fmt.Errorf("%s creating http request: %w", hostname, err)
@ -1066,6 +1111,7 @@ func doLoginURLWithClient(hostname string, loginURL *url.URL, hc *http.Client, f
return http.ErrUseLastResponse
}
}
defer func() {
hc.CheckRedirect = originalRedirect
}()
@ -1080,6 +1126,7 @@ func doLoginURLWithClient(hostname string, loginURL *url.URL, hc *http.Client, f
if err != nil {
return "", nil, fmt.Errorf("%s reading response body: %w", hostname, err)
}
body := string(bodyBytes)
var redirectURL *url.URL
@ -1093,13 +1140,13 @@ func doLoginURLWithClient(hostname string, loginURL *url.URL, hc *http.Client, f
if followRedirects && resp.StatusCode != http.StatusOK {
log.Printf("body: %s", body)
return body, redirectURL, fmt.Errorf("%s unexpected status code %d", hostname, resp.StatusCode)
return body, redirectURL, fmt.Errorf("%s unexpected status code %d", hostname, resp.StatusCode) //nolint:err113
}
if resp.StatusCode >= http.StatusBadRequest {
log.Printf("body: %s", body)
return body, redirectURL, fmt.Errorf("%s unexpected status code %d", hostname, resp.StatusCode)
return body, redirectURL, fmt.Errorf("%s unexpected status code %d", hostname, resp.StatusCode) //nolint:err113
}
if hc.Jar != nil {
@ -1117,7 +1164,7 @@ var errParseAuthPage = errors.New("parsing auth page")
func (s *Scenario) runHeadscaleRegister(userStr string, body string) error {
// see api.go HTML template
codeSep := strings.Split(string(body), "</code>")
codeSep := strings.Split(body, "</code>")
if len(codeSep) != 2 {
return errParseAuthPage
}
@ -1126,11 +1173,12 @@ func (s *Scenario) runHeadscaleRegister(userStr string, body string) error {
if len(keySep) != 2 {
return errParseAuthPage
}
key := keySep[1]
key = strings.SplitN(key, " ", 2)[0]
log.Printf("registering node %s", key)
if headscale, err := s.Headscale(); err == nil {
if headscale, err := s.Headscale(); err == nil { //nolint:noinlineerr
_, err = headscale.Execute(
[]string{"headscale", "nodes", "register", "--user", userStr, "--key", key},
)
@ -1154,6 +1202,7 @@ func (t LoggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error
noTls := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true}, // nolint
}
resp, err := noTls.RoundTrip(req)
if err != nil {
return nil, err
@ -1173,12 +1222,14 @@ func (t LoggingRoundTripper) RoundTrip(req *http.Request) (*http.Response, error
// in a Scenario.
func (s *Scenario) GetIPs(user string) ([]netip.Addr, error) {
var ips []netip.Addr
if ns, ok := s.users[user]; ok {
for _, client := range ns.Clients {
clientIps, err := client.IPs()
if err != nil {
return ips, fmt.Errorf("getting IPs: %w", err)
}
ips = append(ips, clientIps...)
}
@ -1191,6 +1242,7 @@ func (s *Scenario) GetIPs(user string) ([]netip.Addr, error) {
// GetClients returns all TailscaleClients associated with a User in a Scenario.
func (s *Scenario) GetClients(user string) ([]TailscaleClient, error) {
var clients []TailscaleClient
if ns, ok := s.users[user]; ok {
for _, client := range ns.Clients {
clients = append(clients, client)
@ -1290,11 +1342,14 @@ func (s *Scenario) WaitForTailscaleLogout() error {
for _, user := range s.users {
for _, client := range user.Clients {
c := client
user.syncWaitGroup.Go(func() error {
return c.WaitForNeedsLogin(integrationutil.PeerSyncTimeout())
})
}
if err := user.syncWaitGroup.Wait(); err != nil {
err := user.syncWaitGroup.Wait()
if err != nil {
return err
}
}
@ -1361,6 +1416,7 @@ func (s *Scenario) runMockOIDC(accessTTL time.Duration, users []mockoidc.MockUse
if err != nil {
log.Fatalf("finding open port: %s", err)
}
portNotation := fmt.Sprintf("%d/tcp", port)
hash, _ := util.GenerateRandomStringDNSSafe(hsicOIDCMockHashLength)
@ -1405,7 +1461,7 @@ func (s *Scenario) runMockOIDC(accessTTL time.Duration, users []mockoidc.MockUse
// Add integration test labels if running under hi tool
dockertestutil.DockerAddIntegrationLabels(mockOidcOptions, "oidc")
if pmockoidc, err := s.pool.BuildAndRunWithBuildOptions(
if pmockoidc, err := s.pool.BuildAndRunWithBuildOptions( //nolint:noinlineerr
headscaleBuildOptions,
mockOidcOptions,
dockertestutil.DockerRestartPolicy); err == nil {
@ -1421,9 +1477,10 @@ func (s *Scenario) runMockOIDC(accessTTL time.Duration, users []mockoidc.MockUse
ipAddr := s.mockOIDC.r.GetIPInNetwork(network)
log.Println("Waiting for headscale mock oidc to be ready for tests")
hostEndpoint := net.JoinHostPort(ipAddr, strconv.Itoa(port))
if err := s.pool.Retry(func() error {
if err := s.pool.Retry(func() error { //nolint:noinlineerr
oidcConfigURL := fmt.Sprintf("http://%s/oidc/.well-known/openid-configuration", hostEndpoint)
httpClient := &http.Client{}
ctx := context.Background()
@ -1468,14 +1525,13 @@ func Webservice(s *Scenario, networkName string) (*dockertest.Resource, error) {
// log.Fatalf("finding open port: %s", err)
// }
// portNotation := fmt.Sprintf("%d/tcp", port)
hash := util.MustGenerateRandomStringDNSSafe(hsicOIDCMockHashLength)
hostname := "hs-webservice-" + hash
network, ok := s.networks[s.prefixedNetworkName(networkName)]
if !ok {
return nil, fmt.Errorf("network does not exist: %s", networkName)
return nil, fmt.Errorf("network does not exist: %s", networkName) //nolint:err113
}
webOpts := &dockertest.RunOptions{