Extend linter rules (#1300)

- dupword checks for duplicate words in the source code
- durationcheck checks for two durations multiplied together
- forbidigo forbids identifiers
- mirror reports wrong mirror patterns of bytes/strings usage
- misspell finds commonly misspelled English words in comments
- predeclared finds code that shadows one of Go's predeclared identifiers
- thelper detects Go test helpers without t.Helper() call and checks the consistency of test helpers
This commit is contained in:
Yury Gargay 2023-11-10 16:33:13 +01:00 committed by GitHub
parent a40261ff7e
commit 9e8725618e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
37 changed files with 90 additions and 37 deletions

View File

@ -32,9 +32,16 @@ linters:
- unused # checks for unused constants, variables, functions and types - unused # checks for unused constants, variables, functions and types
## disable by default but the have interesting results so lets add them ## disable by default but the have interesting results so lets add them
- bodyclose # checks whether HTTP response body is closed successfully - bodyclose # checks whether HTTP response body is closed successfully
- dupword # dupword checks for duplicate words in the source code
- durationcheck # durationcheck checks for two durations multiplied together
- forbidigo # forbidigo forbids identifiers
- mirror # mirror reports wrong mirror patterns of bytes/strings usage
- misspell # misspess finds commonly misspelled English words in comments
- nilerr # finds the code that returns nil even if it checks that the error is not nil - nilerr # finds the code that returns nil even if it checks that the error is not nil
- nilnil # checks that there is no simultaneous return of nil error and an invalid value - nilnil # checks that there is no simultaneous return of nil error and an invalid value
- predeclared # predeclared finds code that shadows one of Go's predeclared identifiers
- sqlclosecheck # checks that sql.Rows and sql.Stmt are closed - sqlclosecheck # checks that sql.Rows and sql.Stmt are closed
- thelper # thelper detects Go test helpers without t.Helper() call and checks the consistency of test helpers.
- wastedassign # wastedassign finds wasted assignment statements - wastedassign # wastedassign finds wasted assignment statements
issues: issues:
# Maximum count of issues with the same text. # Maximum count of issues with the same text.
@ -43,12 +50,20 @@ issues:
max-same-issues: 5 max-same-issues: 5
exclude-rules: exclude-rules:
# allow fmt
- path: management/cmd/root.go
linters: forbidigo
- path: signal/cmd/root.go
linters: forbidigo
- path: sharedsock/filter.go - path: sharedsock/filter.go
linters: linters:
- unused - unused
- path: client/firewall/iptables/rule.go - path: client/firewall/iptables/rule.go
linters: linters:
- unused - unused
- path: test.go
linters:
- mirror
- path: mock.go - path: mock.go
linters: linters:
- nilnil - nilnil

View File

@ -205,8 +205,8 @@ func (a *Auth) foregroundGetTokenInfo(urlOpener URLOpener) (*auth.TokenInfo, err
go urlOpener.Open(flowInfo.VerificationURIComplete) go urlOpener.Open(flowInfo.VerificationURIComplete)
waitTimeout := time.Duration(flowInfo.ExpiresIn) waitTimeout := time.Duration(flowInfo.ExpiresIn) * time.Second
waitCTX, cancel := context.WithTimeout(a.ctx, waitTimeout*time.Second) waitCTX, cancel := context.WithTimeout(a.ctx, waitTimeout)
defer cancel() defer cancel()
tokenInfo, err := oAuthFlow.WaitToken(waitCTX, flowInfo) tokenInfo, err := oAuthFlow.WaitToken(waitCTX, flowInfo)
if err != nil { if err != nil {

View File

@ -177,8 +177,8 @@ func foregroundGetTokenInfo(ctx context.Context, cmd *cobra.Command, config *int
openURL(cmd, flowInfo.VerificationURIComplete, flowInfo.UserCode) openURL(cmd, flowInfo.VerificationURIComplete, flowInfo.UserCode)
waitTimeout := time.Duration(flowInfo.ExpiresIn) waitTimeout := time.Duration(flowInfo.ExpiresIn) * time.Second
waitCTX, c := context.WithTimeout(context.TODO(), waitTimeout*time.Second) waitCTX, c := context.WithTimeout(context.TODO(), waitTimeout)
defer c() defer c()
tokenInfo, err := oAuthFlow.WaitToken(waitCTX, flowInfo) tokenInfo, err := oAuthFlow.WaitToken(waitCTX, flowInfo)

View File

@ -92,7 +92,7 @@ func init() {
rootCmd.PersistentFlags().StringVar(&adminURL, "admin-url", "", fmt.Sprintf("Admin Panel URL [http|https]://[host]:[port] (default \"%s\")", internal.DefaultAdminURL)) rootCmd.PersistentFlags().StringVar(&adminURL, "admin-url", "", fmt.Sprintf("Admin Panel URL [http|https]://[host]:[port] (default \"%s\")", internal.DefaultAdminURL))
rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", defaultConfigPath, "Netbird config file location") rootCmd.PersistentFlags().StringVarP(&configPath, "config", "c", defaultConfigPath, "Netbird config file location")
rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "l", "info", "sets Netbird log level") rootCmd.PersistentFlags().StringVarP(&logLevel, "log-level", "l", "info", "sets Netbird log level")
rootCmd.PersistentFlags().StringVar(&logFile, "log-file", defaultLogFile, "sets Netbird log path. If console is specified the the log will be output to stdout") rootCmd.PersistentFlags().StringVar(&logFile, "log-file", defaultLogFile, "sets Netbird log path. If console is specified the log will be output to stdout")
rootCmd.PersistentFlags().StringVarP(&setupKey, "setup-key", "k", "", "Setup key obtained from the Management Service Dashboard (used to register peer)") rootCmd.PersistentFlags().StringVarP(&setupKey, "setup-key", "k", "", "Setup key obtained from the Management Service Dashboard (used to register peer)")
rootCmd.PersistentFlags().StringVar(&preSharedKey, "preshared-key", "", "Sets Wireguard PreSharedKey property. If set, then only peers that have the same key can communicate.") rootCmd.PersistentFlags().StringVar(&preSharedKey, "preshared-key", "", "Sets Wireguard PreSharedKey property. If set, then only peers that have the same key can communicate.")
rootCmd.PersistentFlags().StringVarP(&hostName, "hostname", "n", "", "Sets a custom hostname for the device") rootCmd.PersistentFlags().StringVarP(&hostName, "hostname", "n", "", "Sets a custom hostname for the device")

View File

@ -22,6 +22,7 @@ import (
) )
func startTestingServices(t *testing.T) string { func startTestingServices(t *testing.T) string {
t.Helper()
config := &mgmt.Config{} config := &mgmt.Config{}
_, err := util.ReadJson("../testdata/management.json", config) _, err := util.ReadJson("../testdata/management.json", config)
if err != nil { if err != nil {
@ -44,6 +45,7 @@ func startTestingServices(t *testing.T) string {
} }
func startSignal(t *testing.T) (*grpc.Server, net.Listener) { func startSignal(t *testing.T) (*grpc.Server, net.Listener) {
t.Helper()
lis, err := net.Listen("tcp", ":0") lis, err := net.Listen("tcp", ":0")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -60,6 +62,7 @@ func startSignal(t *testing.T) (*grpc.Server, net.Listener) {
} }
func startManagement(t *testing.T, config *mgmt.Config) (*grpc.Server, net.Listener) { func startManagement(t *testing.T, config *mgmt.Config) (*grpc.Server, net.Listener) {
t.Helper()
lis, err := net.Listen("tcp", ":0") lis, err := net.Listen("tcp", ":0")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -98,6 +101,7 @@ func startManagement(t *testing.T, config *mgmt.Config) (*grpc.Server, net.Liste
func startClientDaemon( func startClientDaemon(
t *testing.T, ctx context.Context, managementURL, configPath string, t *testing.T, ctx context.Context, managementURL, configPath string,
) (*grpc.Server, net.Listener) { ) (*grpc.Server, net.Listener) {
t.Helper()
lis, err := net.Listen("tcp", "127.0.0.1:0") lis, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)

View File

@ -206,6 +206,7 @@ func TestIptablesManagerIPSet(t *testing.T) {
} }
func checkRuleSpecs(t *testing.T, ipv4Client *iptables.IPTables, chainName string, mustExists bool, rulespec ...string) { func checkRuleSpecs(t *testing.T, ipv4Client *iptables.IPTables, chainName string, mustExists bool, rulespec ...string) {
t.Helper()
exists, err := ipv4Client.Exists("filter", chainName, rulespec...) exists, err := ipv4Client.Exists("filter", chainName, rulespec...)
require.NoError(t, err, "failed to check rule") require.NoError(t, err, "failed to check rule")
require.Falsef(t, !exists && mustExists, "rule '%v' does not exist", rulespec) require.Falsef(t, !exists && mustExists, "rule '%v' does not exist", rulespec)

View File

@ -771,6 +771,7 @@ func TestDNSPermanent_matchOnly(t *testing.T) {
} }
func createWgInterfaceWithBind(t *testing.T) (*iface.WGIface, error) { func createWgInterfaceWithBind(t *testing.T) (*iface.WGIface, error) {
t.Helper()
ov := os.Getenv("NB_WG_KERNEL_DISABLED") ov := os.Getenv("NB_WG_KERNEL_DISABLED")
defer os.Setenv("NB_WG_KERNEL_DISABLED", ov) defer os.Setenv("NB_WG_KERNEL_DISABLED", ov)

View File

@ -640,7 +640,7 @@ func (e *Engine) updateNetworkMap(networkMap *mgmProto.NetworkMap) error {
if config.GetSshConfig() != nil && config.GetSshConfig().GetSshPubKey() != nil { if config.GetSshConfig() != nil && config.GetSshConfig().GetSshPubKey() != nil {
err := e.sshServer.AddAuthorizedKey(config.WgPubKey, string(config.GetSshConfig().GetSshPubKey())) err := e.sshServer.AddAuthorizedKey(config.WgPubKey, string(config.GetSshConfig().GetSshPubKey()))
if err != nil { if err != nil {
log.Warnf("failed adding authroized key to SSH DefaultServer %v", err) log.Warnf("failed adding authorized key to SSH DefaultServer %v", err)
} }
} }
} }

View File

@ -174,13 +174,13 @@ func (d *Status) UpdatePeerState(receivedState State) error {
return nil return nil
} }
func shouldSkipNotify(new, curr State) bool { func shouldSkipNotify(received, curr State) bool {
switch { switch {
case new.ConnStatus == StatusConnecting: case received.ConnStatus == StatusConnecting:
return true return true
case new.ConnStatus == StatusDisconnected && curr.ConnStatus == StatusConnecting: case received.ConnStatus == StatusDisconnected && curr.ConnStatus == StatusConnecting:
return true return true
case new.ConnStatus == StatusDisconnected && curr.ConnStatus == StatusDisconnected: case received.ConnStatus == StatusDisconnected && curr.ConnStatus == StatusDisconnected:
return curr.IP != "" return curr.IP != ""
default: default:
return false return false

View File

@ -123,7 +123,7 @@ func TestGetExistingRIBRouteGateway(t *testing.T) {
func TestAddExistAndRemoveRouteNonAndroid(t *testing.T) { func TestAddExistAndRemoveRouteNonAndroid(t *testing.T) {
defaultGateway, err := getExistingRIBRouteGateway(netip.MustParsePrefix("0.0.0.0/0")) defaultGateway, err := getExistingRIBRouteGateway(netip.MustParsePrefix("0.0.0.0/0"))
fmt.Println("defaultGateway: ", defaultGateway) t.Log("defaultGateway: ", defaultGateway)
if err != nil { if err != nil {
t.Fatal("shouldn't return error when fetching the gateway: ", err) t.Fatal("shouldn't return error when fetching the gateway: ", err)
} }
@ -207,7 +207,7 @@ func TestAddExistAndRemoveRouteNonAndroid(t *testing.T) {
// route should either not have been added or should have been removed // route should either not have been added or should have been removed
// In case of already existing route, it should not have been added (but still exist) // In case of already existing route, it should not have been added (but still exist)
ok, err := existsInRouteTable(testCase.prefix) ok, err := existsInRouteTable(testCase.prefix)
fmt.Println("Buffer string: ", buf.String()) t.Log("Buffer string: ", buf.String())
require.NoError(t, err, "should not return err") require.NoError(t, err, "should not return err")
if !strings.Contains(buf.String(), "because it already exists") { if !strings.Contains(buf.String(), "because it already exists") {
require.False(t, ok, "route should not exist") require.False(t, ok, "route should not exist")

View File

@ -3,7 +3,6 @@ package system
import ( import (
"bytes" "bytes"
"context" "context"
"fmt"
"os" "os"
"os/exec" "os/exec"
"runtime" "runtime"
@ -21,7 +20,7 @@ func GetInfo(ctx context.Context) *Info {
utsname := unix.Utsname{} utsname := unix.Utsname{}
err := unix.Uname(&utsname) err := unix.Uname(&utsname)
if err != nil { if err != nil {
fmt.Println("getInfo:", err) log.Warnf("getInfo: %s", err)
} }
sysName := string(bytes.Split(utsname.Sysname[:], []byte{0})[0]) sysName := string(bytes.Split(utsname.Sysname[:], []byte{0})[0])
machine := string(bytes.Split(utsname.Machine[:], []byte{0})[0]) machine := string(bytes.Split(utsname.Machine[:], []byte{0})[0])

View File

@ -6,13 +6,14 @@ package system
import ( import (
"bytes" "bytes"
"context" "context"
"fmt"
"os" "os"
"os/exec" "os/exec"
"runtime" "runtime"
"strings" "strings"
"time" "time"
log "github.com/sirupsen/logrus"
"github.com/netbirdio/netbird/version" "github.com/netbirdio/netbird/version"
) )
@ -67,7 +68,7 @@ func _getInfo() string {
cmd.Stderr = &stderr cmd.Stderr = &stderr
err := cmd.Run() err := cmd.Run()
if err != nil { if err != nil {
fmt.Println("getInfo:", err) log.Warnf("getInfo: %s", err)
} }
return out.String() return out.String()
} }
@ -81,7 +82,7 @@ func _getReleaseInfo() string {
cmd.Stderr = &stderr cmd.Stderr = &stderr
err := cmd.Run() err := cmd.Run()
if err != nil { if err != nil {
fmt.Println("getReleaseInfo:", err) log.Warnf("geucwReleaseInfo: %s", err)
} }
return out.String() return out.String()
} }

View File

@ -69,7 +69,7 @@ func main() {
a.Run() a.Run()
} else { } else {
if err := checkPIDFile(); err != nil { if err := checkPIDFile(); err != nil {
fmt.Println(err) log.Errorf("check PID file: %v", err)
return return
} }
systray.Run(client.onTrayReady, client.onTrayExit) systray.Run(client.onTrayReady, client.onTrayExit)

View File

@ -132,6 +132,7 @@ func resetGlobals() {
} }
func createFiles(t *testing.T) (string, []module) { func createFiles(t *testing.T) (string, []module) {
t.Helper()
writeFile := func(path, text string) { writeFile := func(path, text string) {
if err := os.WriteFile(path, []byte(text), 0644); err != nil { if err := os.WriteFile(path, []byte(text), 0644); err != nil {
t.Fatal(err) t.Fatal(err)
@ -167,6 +168,7 @@ func createFiles(t *testing.T) (string, []module) {
} }
func getRandomLoadedModule(t *testing.T) (string, error) { func getRandomLoadedModule(t *testing.T) (string, error) {
t.Helper()
f, err := os.Open("/proc/modules") f, err := os.Open("/proc/modules")
if err != nil { if err != nil {
return "", err return "", err

View File

@ -31,6 +31,7 @@ import (
const ValidKey = "A2C8E62B-38F5-4553-B31E-DD66C696CEBB" const ValidKey = "A2C8E62B-38F5-4553-B31E-DD66C696CEBB"
func startManagement(t *testing.T) (*grpc.Server, net.Listener) { func startManagement(t *testing.T) (*grpc.Server, net.Listener) {
t.Helper()
level, _ := log.ParseLevel("debug") level, _ := log.ParseLevel("debug")
log.SetLevel(level) log.SetLevel(level)
@ -81,6 +82,7 @@ func startManagement(t *testing.T) (*grpc.Server, net.Listener) {
} }
func startMockManagement(t *testing.T) (*grpc.Server, net.Listener, *mock_server.ManagementServiceServerMock, wgtypes.Key) { func startMockManagement(t *testing.T) (*grpc.Server, net.Listener, *mock_server.ManagementServiceServerMock, wgtypes.Key) {
t.Helper()
lis, err := net.Listen("tcp", ":0") lis, err := net.Listen("tcp", ":0")
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
@ -168,7 +170,7 @@ func TestClient_LoginUnregistered_ShouldThrow_401(t *testing.T) {
t.Error("expecting err on unregistered login, got nil") t.Error("expecting err on unregistered login, got nil")
} }
if s, ok := status.FromError(err); !ok || s.Code() != codes.PermissionDenied { if s, ok := status.FromError(err); !ok || s.Code() != codes.PermissionDenied {
t.Errorf("expecting err code %d denied on on unregistered login got %d", codes.PermissionDenied, s.Code()) t.Errorf("expecting err code %d denied on unregistered login got %d", codes.PermissionDenied, s.Code())
} }
} }

View File

@ -67,7 +67,7 @@ func init() {
rootCmd.MarkFlagRequired("config") //nolint rootCmd.MarkFlagRequired("config") //nolint
rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "info", "") rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "info", "")
rootCmd.PersistentFlags().StringVar(&logFile, "log-file", defaultLogFile, "sets Netbird log path. If console is specified the the log will be output to stdout") rootCmd.PersistentFlags().StringVar(&logFile, "log-file", defaultLogFile, "sets Netbird log path. If console is specified the log will be output to stdout")
rootCmd.AddCommand(mgmtCmd) rootCmd.AddCommand(mgmtCmd)
migrationCmd.PersistentFlags().StringVar(&mgmtDataDir, "datadir", defaultMgmtDataDir, "server data directory location") migrationCmd.PersistentFlags().StringVar(&mgmtDataDir, "datadir", defaultMgmtDataDir, "server data directory location")

View File

@ -1574,7 +1574,7 @@ func (am *DefaultAccountManager) GetAllConnectedPeers() (map[string]struct{}, er
func isDomainValid(domain string) bool { func isDomainValid(domain string) bool {
re := regexp.MustCompile(`^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$`) re := regexp.MustCompile(`^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$`)
return re.Match([]byte(domain)) return re.MatchString(domain)
} }
// GetDNSDomain returns the configured dnsDomain // GetDNSDomain returns the configured dnsDomain

View File

@ -25,6 +25,7 @@ import (
) )
func verifyCanAddPeerToAccount(t *testing.T, manager AccountManager, account *Account, userID string) { func verifyCanAddPeerToAccount(t *testing.T, manager AccountManager, account *Account, userID string) {
t.Helper()
peer := &Peer{ peer := &Peer{
Key: "BhRPtynAAYRDy08+q4HTMsos8fs4plTP4NOSh7C1ry8=", Key: "BhRPtynAAYRDy08+q4HTMsos8fs4plTP4NOSh7C1ry8=",
Name: "test-host@netbird.io", Name: "test-host@netbird.io",
@ -52,6 +53,7 @@ func verifyCanAddPeerToAccount(t *testing.T, manager AccountManager, account *Ac
} }
func verifyNewAccountHasDefaultFields(t *testing.T, account *Account, createdBy string, domain string, expectedUsers []string) { func verifyNewAccountHasDefaultFields(t *testing.T, account *Account, createdBy string, domain string, expectedUsers []string) {
t.Helper()
if len(account.Peers) != 0 { if len(account.Peers) != 0 {
t.Errorf("expected account to have len(Peers) = %v, got %v", 0, len(account.Peers)) t.Errorf("expected account to have len(Peers) = %v, got %v", 0, len(account.Peers))
} }
@ -1131,6 +1133,7 @@ func TestAccountManager_DeletePeer(t *testing.T) {
} }
func getEvent(t *testing.T, accountID string, manager AccountManager, eventType activity.Activity) *activity.Event { func getEvent(t *testing.T, accountID string, manager AccountManager, eventType activity.Activity) *activity.Event {
t.Helper()
for { for {
select { select {
case <-time.After(time.Second): case <-time.After(time.Second):
@ -2038,6 +2041,7 @@ func TestAccount_UserGroupsRemoveFromPeers(t *testing.T) {
} }
func createManager(t *testing.T) (*DefaultAccountManager, error) { func createManager(t *testing.T) (*DefaultAccountManager, error) {
t.Helper()
store, err := createStore(t) store, err := createStore(t)
if err != nil { if err != nil {
return nil, err return nil, err
@ -2047,6 +2051,7 @@ func createManager(t *testing.T) (*DefaultAccountManager, error) {
} }
func createStore(t *testing.T) (Store, error) { func createStore(t *testing.T) (Store, error) {
t.Helper()
dataDir := t.TempDir() dataDir := t.TempDir()
store, err := NewStoreFromJson(dataDir, nil) store, err := NewStoreFromJson(dataDir, nil)
if err != nil { if err != nil {

View File

@ -186,6 +186,7 @@ func TestGetNetworkMap_DNSConfigSync(t *testing.T) {
} }
func createDNSManager(t *testing.T) (*DefaultAccountManager, error) { func createDNSManager(t *testing.T) (*DefaultAccountManager, error) {
t.Helper()
store, err := createDNSStore(t) store, err := createDNSStore(t)
if err != nil { if err != nil {
return nil, err return nil, err
@ -195,6 +196,7 @@ func createDNSManager(t *testing.T) (*DefaultAccountManager, error) {
} }
func createDNSStore(t *testing.T) (Store, error) { func createDNSStore(t *testing.T) (Store, error) {
t.Helper()
dataDir := t.TempDir() dataDir := t.TempDir()
store, err := NewStoreFromJson(dataDir, nil) store, err := NewStoreFromJson(dataDir, nil)
if err != nil { if err != nil {
@ -205,6 +207,7 @@ func createDNSStore(t *testing.T) (Store, error) {
} }
func initTestDNSAccount(t *testing.T, am *DefaultAccountManager) (*Account, error) { func initTestDNSAccount(t *testing.T, am *DefaultAccountManager) (*Account, error) {
t.Helper()
peer1 := &Peer{ peer1 := &Peer{
Key: dnsPeer1Key, Key: dnsPeer1Key,
Name: "test-host1@netbird.io", Name: "test-host1@netbird.io",

View File

@ -11,6 +11,7 @@ import (
func generateAndStoreEvents(t *testing.T, manager *DefaultAccountManager, typ activity.Activity, initiatorID, targetID, func generateAndStoreEvents(t *testing.T, manager *DefaultAccountManager, typ activity.Activity, initiatorID, targetID,
accountID string, count int) { accountID string, count int) {
t.Helper()
for i := 0; i < count; i++ { for i := 0; i < count; i++ {
_, err := manager.eventStore.Save(&activity.Event{ _, err := manager.eventStore.Save(&activity.Event{
Timestamp: time.Now().UTC(), Timestamp: time.Now().UTC(),

View File

@ -580,6 +580,7 @@ func TestFileStore_SavePeerStatus(t *testing.T) {
} }
func newStore(t *testing.T) *FileStore { func newStore(t *testing.T) *FileStore {
t.Helper()
store, err := NewFileStore(t.TempDir(), nil) store, err := NewFileStore(t.TempDir(), nil)
if err != nil { if err != nil {
t.Errorf("failed creating a new store") t.Errorf("failed creating a new store")

View File

@ -230,7 +230,7 @@ func TestWriteGroup(t *testing.T) {
expectedBody: false, expectedBody: false,
}, },
{ {
name: "Write Group PUT not not change Issue", name: "Write Group PUT not change Issue",
requestType: http.MethodPut, requestType: http.MethodPut,
requestPath: "/api/groups/id-jwt-group", requestPath: "/api/groups/id-jwt-group",
requestBody: bytes.NewBuffer( requestBody: bytes.NewBuffer(

View File

@ -3,7 +3,6 @@ package http
import ( import (
"bytes" "bytes"
"encoding/json" "encoding/json"
"fmt"
"io" "io"
"net" "net"
"net/http" "net/http"
@ -232,7 +231,7 @@ func TestGetPeers(t *testing.T) {
} }
} }
fmt.Println(got) t.Log(got)
assert.Equal(t, got.Name, tc.expectedPeer.Name) assert.Equal(t, got.Name, tc.expectedPeer.Name)
assert.Equal(t, got.Version, tc.expectedPeer.Meta.WtVersion) assert.Equal(t, got.Version, tc.expectedPeer.Meta.WtVersion)

View File

@ -220,6 +220,7 @@ func TestSetupKeysHandlers(t *testing.T) {
} }
func assertKeys(t *testing.T, got *api.SetupKey, expected *api.SetupKey) { func assertKeys(t *testing.T, got *api.SetupKey, expected *api.SetupKey) {
t.Helper()
// this comparison is done manually because when converting to JSON dates formatted differently // this comparison is done manually because when converting to JSON dates formatted differently
// assert.Equal(t, got.UpdatedAt, tc.expectedSetupKey.UpdatedAt) //doesn't work // assert.Equal(t, got.UpdatedAt, tc.expectedSetupKey.UpdatedAt) //doesn't work
assert.WithinDurationf(t, got.UpdatedAt, expected.UpdatedAt, 0, "") assert.WithinDurationf(t, got.UpdatedAt, expected.UpdatedAt, 0, "")

View File

@ -65,6 +65,7 @@ func (mc *mockAuth0Credentials) Authenticate() (JWTToken, error) {
} }
func newTestJWT(t *testing.T, expInt int) string { func newTestJWT(t *testing.T, expInt int) string {
t.Helper()
now := time.Now() now := time.Now()
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"iat": now.Unix(), "iat": now.Unix(),

View File

@ -256,7 +256,6 @@ func (om *OktaManager) InviteUserByID(_ string) error {
func (om *OktaManager) DeleteUser(userID string) error { func (om *OktaManager) DeleteUser(userID string) error {
resp, err := om.client.User.DeactivateOrDeleteUser(context.Background(), userID, nil) resp, err := om.client.User.DeactivateOrDeleteUser(context.Background(), userID, nil)
if err != nil { if err != nil {
fmt.Println(err.Error())
return err return err
} }

View File

@ -11,6 +11,7 @@ import (
) )
func newTestRequestWithJWT(t *testing.T, claims AuthorizationClaims, audience string) *http.Request { func newTestRequestWithJWT(t *testing.T, claims AuthorizationClaims, audience string) *http.Request {
t.Helper()
const layout = "2006-01-02T15:04:05.999Z" const layout = "2006-01-02T15:04:05.999Z"
claimMaps := jwt.MapClaims{} claimMaps := jwt.MapClaims{}
@ -143,6 +144,7 @@ func TestExtractClaimsFromRequestContext(t *testing.T) {
} }
func TestExtractClaimsSetOptions(t *testing.T) { func TestExtractClaimsSetOptions(t *testing.T) {
t.Helper()
type test struct { type test struct {
name string name string
extractor *ClaimsExtractor extractor *ClaimsExtractor
@ -153,6 +155,7 @@ func TestExtractClaimsSetOptions(t *testing.T) {
name: "No custom options", name: "No custom options",
extractor: NewClaimsExtractor(), extractor: NewClaimsExtractor(),
check: func(t *testing.T, c test) { check: func(t *testing.T, c test) {
t.Helper()
if c.extractor.authAudience != "" { if c.extractor.authAudience != "" {
t.Error("audience should be empty") t.Error("audience should be empty")
return return
@ -172,6 +175,7 @@ func TestExtractClaimsSetOptions(t *testing.T) {
name: "Custom audience", name: "Custom audience",
extractor: NewClaimsExtractor(WithAudience("https://login/")), extractor: NewClaimsExtractor(WithAudience("https://login/")),
check: func(t *testing.T, c test) { check: func(t *testing.T, c test) {
t.Helper()
if c.extractor.authAudience != "https://login/" { if c.extractor.authAudience != "https://login/" {
t.Errorf("audience expected %s, got %s", "https://login/", c.extractor.authAudience) t.Errorf("audience expected %s, got %s", "https://login/", c.extractor.authAudience)
return return
@ -183,6 +187,7 @@ func TestExtractClaimsSetOptions(t *testing.T) {
name: "Custom user id claim", name: "Custom user id claim",
extractor: NewClaimsExtractor(WithUserIDClaim("customUserId")), extractor: NewClaimsExtractor(WithUserIDClaim("customUserId")),
check: func(t *testing.T, c test) { check: func(t *testing.T, c test) {
t.Helper()
if c.extractor.userIDClaim != "customUserId" { if c.extractor.userIDClaim != "customUserId" {
t.Errorf("user id claim expected %s, got %s", "customUserId", c.extractor.userIDClaim) t.Errorf("user id claim expected %s, got %s", "customUserId", c.extractor.userIDClaim)
return return
@ -199,6 +204,7 @@ func TestExtractClaimsSetOptions(t *testing.T) {
} }
})), })),
check: func(t *testing.T, c test) { check: func(t *testing.T, c test) {
t.Helper()
claims := c.extractor.FromRequestContext(&http.Request{}) claims := c.extractor.FromRequestContext(&http.Request{})
if claims.UserId != "testCustomRequest" { if claims.UserId != "testCustomRequest" {
t.Errorf("user id claim expected %s, got %s", "testCustomRequest", claims.UserId) t.Errorf("user id claim expected %s, got %s", "testCustomRequest", claims.UserId)

View File

@ -400,6 +400,7 @@ func TestServer_GetDeviceAuthorizationFlow(t *testing.T) {
} }
func startManagement(t *testing.T, config *Config) (*grpc.Server, string, error) { func startManagement(t *testing.T, config *Config) (*grpc.Server, string, error) {
t.Helper()
lis, err := net.Listen("tcp", "localhost:0") lis, err := net.Listen("tcp", "localhost:0")
if err != nil { if err != nil {
return nil, "", err return nil, "", err

View File

@ -355,7 +355,7 @@ func (am *MockAccountManager) UpdatePeerSSHKey(peerID string, sshKey string) err
if am.UpdatePeerSSHKeyFunc != nil { if am.UpdatePeerSSHKeyFunc != nil {
return am.UpdatePeerSSHKeyFunc(peerID, sshKey) return am.UpdatePeerSSHKeyFunc(peerID, sshKey)
} }
return status.Errorf(codes.Unimplemented, "method UpdatePeerSSHKey is is not implemented") return status.Errorf(codes.Unimplemented, "method UpdatePeerSSHKey is not implemented")
} }
// UpdatePeer mocks UpdatePeerFunc function of the account manager // UpdatePeer mocks UpdatePeerFunc function of the account manager
@ -363,7 +363,7 @@ func (am *MockAccountManager) UpdatePeer(accountID, userID string, peer *server.
if am.UpdatePeerFunc != nil { if am.UpdatePeerFunc != nil {
return am.UpdatePeerFunc(accountID, userID, peer) return am.UpdatePeerFunc(accountID, userID, peer)
} }
return nil, status.Errorf(codes.Unimplemented, "method UpdatePeerFunc is is not implemented") return nil, status.Errorf(codes.Unimplemented, "method UpdatePeerFunc is not implemented")
} }
// CreateRoute mock implementation of CreateRoute from server.AccountManager interface // CreateRoute mock implementation of CreateRoute from server.AccountManager interface

View File

@ -741,6 +741,7 @@ func TestGetNameServerGroup(t *testing.T) {
} }
func createNSManager(t *testing.T) (*DefaultAccountManager, error) { func createNSManager(t *testing.T) (*DefaultAccountManager, error) {
t.Helper()
store, err := createNSStore(t) store, err := createNSStore(t)
if err != nil { if err != nil {
return nil, err return nil, err
@ -750,6 +751,7 @@ func createNSManager(t *testing.T) (*DefaultAccountManager, error) {
} }
func createNSStore(t *testing.T) (Store, error) { func createNSStore(t *testing.T) (Store, error) {
t.Helper()
dataDir := t.TempDir() dataDir := t.TempDir()
store, err := NewStoreFromJson(dataDir, nil) store, err := NewStoreFromJson(dataDir, nil)
if err != nil { if err != nil {
@ -760,6 +762,7 @@ func createNSStore(t *testing.T) (Store, error) {
} }
func initTestNSAccount(t *testing.T, am *DefaultAccountManager) (*Account, error) { func initTestNSAccount(t *testing.T, am *DefaultAccountManager) (*Account, error) {
t.Helper()
peer1 := &Peer{ peer1 := &Peer{
Key: nsGroupPeer1Key, Key: nsGroupPeer1Key,
Name: "test-host1@netbird.io", Name: "test-host1@netbird.io",

View File

@ -1007,6 +1007,7 @@ func TestGetNetworkMap_RouteSync(t *testing.T) {
} }
func createRouterManager(t *testing.T) (*DefaultAccountManager, error) { func createRouterManager(t *testing.T) (*DefaultAccountManager, error) {
t.Helper()
store, err := createRouterStore(t) store, err := createRouterStore(t)
if err != nil { if err != nil {
return nil, err return nil, err
@ -1016,6 +1017,7 @@ func createRouterManager(t *testing.T) (*DefaultAccountManager, error) {
} }
func createRouterStore(t *testing.T) (Store, error) { func createRouterStore(t *testing.T) (Store, error) {
t.Helper()
dataDir := t.TempDir() dataDir := t.TempDir()
store, err := NewStoreFromJson(dataDir, nil) store, err := NewStoreFromJson(dataDir, nil)
if err != nil { if err != nil {

View File

@ -237,6 +237,7 @@ func TestSetupKey_IsValid(t *testing.T) {
func assertKey(t *testing.T, key *SetupKey, expectedName string, expectedRevoke bool, expectedType string, func assertKey(t *testing.T, key *SetupKey, expectedName string, expectedRevoke bool, expectedType string,
expectedUsedTimes int, expectedCreatedAt time.Time, expectedExpiresAt time.Time, expectedID string, expectedUsedTimes int, expectedCreatedAt time.Time, expectedExpiresAt time.Time, expectedID string,
expectedUpdatedAt time.Time, expectedAutoGroups []string) { expectedUpdatedAt time.Time, expectedAutoGroups []string) {
t.Helper()
if key.Name != expectedName { if key.Name != expectedName {
t.Errorf("expected setup key to have Name %v, got %v", expectedName, key.Name) t.Errorf("expected setup key to have Name %v, got %v", expectedName, key.Name)
} }

View File

@ -14,11 +14,13 @@ type benchCase struct {
} }
var newFs = func(b *testing.B) Store { var newFs = func(b *testing.B) Store {
b.Helper()
store, _ := NewFileStore(b.TempDir(), nil) store, _ := NewFileStore(b.TempDir(), nil)
return store return store
} }
var newSqlite = func(b *testing.B) Store { var newSqlite = func(b *testing.B) Store {
b.Helper()
store, _ := NewSqliteStore(b.TempDir(), nil) store, _ := NewSqliteStore(b.TempDir(), nil)
return store return store
} }

View File

@ -116,6 +116,6 @@ func (grpcMetrics *GRPCMetrics) RegisterConnectedStreams(producer func() int64)
} }
// UpdateChannelQueueLength update the histogram that keep distribution of the update messages channel queue // UpdateChannelQueueLength update the histogram that keep distribution of the update messages channel queue
func (metrics *GRPCMetrics) UpdateChannelQueueLength(len int) { func (metrics *GRPCMetrics) UpdateChannelQueueLength(length int) {
metrics.channelQueueLength.Record(metrics.ctx, int64(len)) metrics.channelQueueLength.Record(metrics.ctx, int64(length))
} }

View File

@ -4,9 +4,10 @@ import (
"crypto/hmac" "crypto/hmac"
"crypto/sha1" "crypto/sha1"
"encoding/base64" "encoding/base64"
"github.com/netbirdio/netbird/util"
"testing" "testing"
"time" "time"
"github.com/netbirdio/netbird/util"
) )
var TurnTestHost = &Host{ var TurnTestHost = &Host{
@ -36,7 +37,7 @@ func TestTimeBasedAuthSecretsManager_GenerateCredentials(t *testing.T) {
t.Errorf("expected generated TURN password not to be empty, got empty") t.Errorf("expected generated TURN password not to be empty, got empty")
} }
validateMAC(credentials.Username, credentials.Password, []byte(secret), t) validateMAC(t, credentials.Username, credentials.Password, []byte(secret))
} }
@ -112,7 +113,8 @@ func TestTimeBasedAuthSecretsManager_CancelRefresh(t *testing.T) {
} }
} }
func validateMAC(username string, actualMAC string, key []byte, t *testing.T) { func validateMAC(t *testing.T, username string, actualMAC string, key []byte) {
t.Helper()
mac := hmac.New(sha1.New, key) mac := hmac.New(sha1.New, key)
_, err := mac.Write([]byte(username)) _, err := mac.Write([]byte(username))

View File

@ -2,10 +2,11 @@ package main
import ( import (
"context" "context"
"github.com/netbirdio/netbird/sharedsock"
log "github.com/sirupsen/logrus"
"os" "os"
"os/signal" "os/signal"
"github.com/netbirdio/netbird/sharedsock"
log "github.com/sirupsen/logrus"
) )
func main() { func main() {
@ -16,7 +17,7 @@ func main() {
panic(err) panic(err)
} }
log.Infof("attached to to the raw socket on port %d", port) log.Infof("attached to the raw socket on port %d", port)
ctx, cancel := context.WithCancel(context.Background()) ctx, cancel := context.WithCancel(context.Background())
// read packets // read packets

View File

@ -47,7 +47,7 @@ func init() {
} }
rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "info", "") rootCmd.PersistentFlags().StringVar(&logLevel, "log-level", "info", "")
rootCmd.PersistentFlags().StringVar(&logFile, "log-file", defaultLogFile, "sets Netbird log path. If console is specified the the log will be output to stdout") rootCmd.PersistentFlags().StringVar(&logFile, "log-file", defaultLogFile, "sets Netbird log path. If console is specified the log will be output to stdout")
rootCmd.AddCommand(runCmd) rootCmd.AddCommand(runCmd)
} }