Add gocritic linter (#1324)

* Add gocritic linter

`gocritic` provides diagnostics that check for bugs, performance, and style issues

We disable the following checks:

- commentFormatting
- captLocal
- deprecatedComment

This PR contains many `//nolint:gocritic` to disable `appendAssign`.
This commit is contained in:
Yury Gargay 2023-11-27 16:40:02 +01:00 committed by GitHub
parent 63d211c698
commit d1a323fa9d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
31 changed files with 110 additions and 101 deletions

View File

@ -12,6 +12,12 @@ linters-settings:
# Default: false # Default: false
check-type-assertions: false check-type-assertions: false
gocritic:
disabled-checks:
- commentFormatting
- captLocal
- deprecatedComment
govet: govet:
# Enable all analyzers. # Enable all analyzers.
# Default: false # Default: false
@ -42,6 +48,7 @@ linters:
- dupword # dupword checks for duplicate words in the source code - dupword # dupword checks for duplicate words in the source code
- durationcheck # durationcheck checks for two durations multiplied together - durationcheck # durationcheck checks for two durations multiplied together
- forbidigo # forbidigo forbids identifiers - forbidigo # forbidigo forbids identifiers
- gocritic # provides diagnostics that check for bugs, performance and style issues
- mirror # mirror reports wrong mirror patterns of bytes/strings usage - mirror # mirror reports wrong mirror patterns of bytes/strings usage
- misspell # misspess finds commonly misspelled English words in comments - 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

View File

@ -234,7 +234,7 @@ func mapPeers(peers []*proto.PeerState) peersStateOutput {
continue continue
} }
if isPeerConnected { if isPeerConnected {
peersConnected = peersConnected + 1 peersConnected++
localICE = pbPeerState.GetLocalIceCandidateType() localICE = pbPeerState.GetLocalIceCandidateType()
remoteICE = pbPeerState.GetRemoteIceCandidateType() remoteICE = pbPeerState.GetRemoteIceCandidateType()
@ -407,7 +407,7 @@ func parsePeers(peers peersStateOutput) string {
peerState.LastStatusUpdate.Format("2006-01-02 15:04:05"), peerState.LastStatusUpdate.Format("2006-01-02 15:04:05"),
) )
peersString = peersString + peerString peersString += peerString
} }
return peersString return peersString
} }

View File

@ -463,14 +463,16 @@ func (m *Manager) actionToStr(action fw.Action) string {
} }
func (m *Manager) transformIPsetName(ipsetName string, sPort, dPort string) string { func (m *Manager) transformIPsetName(ipsetName string, sPort, dPort string) string {
if ipsetName == "" { switch {
case ipsetName == "":
return "" return ""
} else if sPort != "" && dPort != "" { case sPort != "" && dPort != "":
return ipsetName + "-sport-dport" return ipsetName + "-sport-dport"
} else if sPort != "" { case sPort != "":
return ipsetName + "-sport" return ipsetName + "-sport"
} else if dPort != "" { case dPort != "":
return ipsetName + "-dport" return ipsetName + "-dport"
default:
return ipsetName
} }
return ipsetName
} }

View File

@ -791,7 +791,7 @@ func (m *Manager) flushWithBackoff() (err error) {
return err return err
} }
time.Sleep(backoffTime) time.Sleep(backoffTime)
backoffTime = backoffTime * 2 backoffTime *= 2
continue continue
} }
break break

View File

@ -189,31 +189,33 @@ func TestDefaultManagerSquashRules(t *testing.T) {
} }
r := rules[0] r := rules[0]
if r.PeerIP != "0.0.0.0" { switch {
case r.PeerIP != "0.0.0.0":
t.Errorf("IP should be 0.0.0.0, got: %v", r.PeerIP) t.Errorf("IP should be 0.0.0.0, got: %v", r.PeerIP)
return return
} else if r.Direction != mgmProto.FirewallRule_IN { case r.Direction != mgmProto.FirewallRule_IN:
t.Errorf("direction should be IN, got: %v", r.Direction) t.Errorf("direction should be IN, got: %v", r.Direction)
return return
} else if r.Protocol != mgmProto.FirewallRule_ALL { case r.Protocol != mgmProto.FirewallRule_ALL:
t.Errorf("protocol should be ALL, got: %v", r.Protocol) t.Errorf("protocol should be ALL, got: %v", r.Protocol)
return return
} else if r.Action != mgmProto.FirewallRule_ACCEPT { case r.Action != mgmProto.FirewallRule_ACCEPT:
t.Errorf("action should be ACCEPT, got: %v", r.Action) t.Errorf("action should be ACCEPT, got: %v", r.Action)
return return
} }
r = rules[1] r = rules[1]
if r.PeerIP != "0.0.0.0" { switch {
case r.PeerIP != "0.0.0.0":
t.Errorf("IP should be 0.0.0.0, got: %v", r.PeerIP) t.Errorf("IP should be 0.0.0.0, got: %v", r.PeerIP)
return return
} else if r.Direction != mgmProto.FirewallRule_OUT { case r.Direction != mgmProto.FirewallRule_OUT:
t.Errorf("direction should be OUT, got: %v", r.Direction) t.Errorf("direction should be OUT, got: %v", r.Direction)
return return
} else if r.Protocol != mgmProto.FirewallRule_ALL { case r.Protocol != mgmProto.FirewallRule_ALL:
t.Errorf("protocol should be ALL, got: %v", r.Protocol) t.Errorf("protocol should be ALL, got: %v", r.Protocol)
return return
} else if r.Action != mgmProto.FirewallRule_ACCEPT { case r.Action != mgmProto.FirewallRule_ACCEPT:
t.Errorf("action should be ACCEPT, got: %v", r.Action) t.Errorf("action should be ACCEPT, got: %v", r.Action)
return return
} }

View File

@ -4,12 +4,13 @@ import (
"context" "context"
"encoding/json" "encoding/json"
"fmt" "fmt"
"github.com/netbirdio/netbird/client/internal"
"io" "io"
"net/http" "net/http"
"net/url" "net/url"
"strings" "strings"
"time" "time"
"github.com/netbirdio/netbird/client/internal"
) )
// HostedGrantType grant type for device flow on Hosted // HostedGrantType grant type for device flow on Hosted
@ -174,7 +175,7 @@ func (d *DeviceAuthorizationFlow) WaitToken(ctx context.Context, info AuthFlowIn
if tokenResponse.Error == "authorization_pending" { if tokenResponse.Error == "authorization_pending" {
continue continue
} else if tokenResponse.Error == "slow_down" { } else if tokenResponse.Error == "slow_down" {
interval = interval + (3 * time.Second) interval += (3 * time.Second)
ticker.Reset(interval) ticker.Reset(interval)
continue continue
} }

View File

@ -92,15 +92,15 @@ func authenticateWithPKCEFlow(ctx context.Context, config *internal.Config) (OAu
func authenticateWithDeviceCodeFlow(ctx context.Context, config *internal.Config) (OAuthFlow, error) { func authenticateWithDeviceCodeFlow(ctx context.Context, config *internal.Config) (OAuthFlow, error) {
deviceFlowInfo, err := internal.GetDeviceAuthorizationFlowInfo(ctx, config.PrivateKey, config.ManagementURL) deviceFlowInfo, err := internal.GetDeviceAuthorizationFlowInfo(ctx, config.PrivateKey, config.ManagementURL)
if err != nil { if err != nil {
s, ok := gstatus.FromError(err) switch s, ok := gstatus.FromError(err); {
if ok && s.Code() == codes.NotFound { case ok && s.Code() == codes.NotFound:
return nil, fmt.Errorf("no SSO provider returned from management. " + return nil, fmt.Errorf("no SSO provider returned from management. " +
"Please proceed with setting up this device using setup keys " + "Please proceed with setting up this device using setup keys " +
"https://docs.netbird.io/how-to/register-machines-using-setup-keys") "https://docs.netbird.io/how-to/register-machines-using-setup-keys")
} else if ok && s.Code() == codes.Unimplemented { case ok && s.Code() == codes.Unimplemented:
return nil, fmt.Errorf("the management server, %s, does not support SSO providers, "+ return nil, fmt.Errorf("the management server, %s, does not support SSO providers, "+
"please update your server or use Setup Keys to login", config.ManagementURL) "please update your server or use Setup Keys to login", config.ManagementURL)
} else { default:
return nil, fmt.Errorf("getting device authorization flow info failed with error: %v", err) return nil, fmt.Errorf("getting device authorization flow info failed with error: %v", err)
} }
} }

View File

@ -273,9 +273,9 @@ func parseURL(serviceName, serviceURL string) (*url.URL, error) {
if parsedMgmtURL.Port() == "" { if parsedMgmtURL.Port() == "" {
switch parsedMgmtURL.Scheme { switch parsedMgmtURL.Scheme {
case "https": case "https":
parsedMgmtURL.Host = parsedMgmtURL.Host + ":443" parsedMgmtURL.Host += ":443"
case "http": case "http":
parsedMgmtURL.Host = parsedMgmtURL.Host + ":80" parsedMgmtURL.Host += ":80"
default: default:
log.Infof("unable to determine a default port for schema %s in URL %s", parsedMgmtURL.Scheme, serviceURL) log.Infof("unable to determine a default port for schema %s in URL %s", parsedMgmtURL.Scheme, serviceURL)
} }

View File

@ -122,7 +122,7 @@ func (n *networkManagerDbusConfigurator) applyDNSConfig(config hostDNSConfig) er
searchDomains = append(searchDomains, dns.Fqdn(dConf.domain)) searchDomains = append(searchDomains, dns.Fqdn(dConf.domain))
} }
newDomainList := append(searchDomains, matchDomains...) newDomainList := append(searchDomains, matchDomains...) //nolint:gocritic
priority := networkManagerDbusSearchDomainOnlyPriority priority := networkManagerDbusSearchDomainOnlyPriority
switch { switch {

View File

@ -252,7 +252,7 @@ func (s *DefaultServer) applyConfiguration(update nbdns.Config) error {
if err != nil { if err != nil {
return fmt.Errorf("not applying dns update, error: %v", err) return fmt.Errorf("not applying dns update, error: %v", err)
} }
muxUpdates := append(localMuxUpdates, upstreamMuxUpdates...) muxUpdates := append(localMuxUpdates, upstreamMuxUpdates...) //nolint:gocritic
s.updateMux(muxUpdates) s.updateMux(muxUpdates)
s.updateLocalResolver(localRecords) s.updateLocalResolver(localRecords)

View File

@ -50,7 +50,7 @@ func GetEbpfManagerInstance() manager.Manager {
} }
func (tf *GeneralManager) setFeatureFlag(feature uint16) { func (tf *GeneralManager) setFeatureFlag(feature uint16) {
tf.featureFlags = tf.featureFlags | feature tf.featureFlags |= feature
} }
func (tf *GeneralManager) loadXdp() error { func (tf *GeneralManager) loadXdp() error {

View File

@ -204,14 +204,12 @@ func (e *Engine) Start() error {
e.dnsServer = dns.NewDefaultServerPermanentUpstream(e.ctx, e.wgInterface, e.mobileDep.HostDNSAddresses, *dnsConfig, e.mobileDep.NetworkChangeListener) e.dnsServer = dns.NewDefaultServerPermanentUpstream(e.ctx, e.wgInterface, e.mobileDep.HostDNSAddresses, *dnsConfig, e.mobileDep.NetworkChangeListener)
go e.mobileDep.DnsReadyListener.OnReady() go e.mobileDep.DnsReadyListener.OnReady()
} }
} else { } else if e.dnsServer == nil {
// todo fix custom address // todo fix custom address
if e.dnsServer == nil { e.dnsServer, err = dns.NewDefaultServer(e.ctx, e.wgInterface, e.config.CustomDNSAddress)
e.dnsServer, err = dns.NewDefaultServer(e.ctx, e.wgInterface, e.config.CustomDNSAddress) if err != nil {
if err != nil { e.close()
e.close() return err
return err
}
} }
} }
@ -490,15 +488,13 @@ func (e *Engine) updateSSH(sshConf *mgmProto.SSHConfig) error {
} else { } else {
log.Debugf("SSH server is already running") log.Debugf("SSH server is already running")
} }
} else { } else if !isNil(e.sshServer) {
// Disable SSH server request, so stop it if it was running // Disable SSH server request, so stop it if it was running
if !isNil(e.sshServer) { err := e.sshServer.Stop()
err := e.sshServer.Stop() if err != nil {
if err != nil { log.Warnf("failed to stop SSH server %v", err)
log.Warnf("failed to stop SSH server %v", err)
}
e.sshServer = nil
} }
e.sshServer = nil
} }
return nil return nil
} }

View File

@ -869,7 +869,7 @@ loop:
case <-ticker.C: case <-ticker.C:
totalConnected := 0 totalConnected := 0
for _, engine := range engines { for _, engine := range engines {
totalConnected = totalConnected + getConnectedPeers(engine) totalConnected += getConnectedPeers(engine)
} }
if totalConnected == expectedConnected { if totalConnected == expectedConnected {
log.Infof("total connected=%d", totalConnected) log.Infof("total connected=%d", totalConnected)

View File

@ -173,7 +173,7 @@ func (i *iptablesManager) addJumpRules() error {
return err return err
} }
if i.ipv4Client != nil { if i.ipv4Client != nil {
rule := append(iptablesDefaultForwardingRule, ipv4Forwarding) rule := append(iptablesDefaultForwardingRule, ipv4Forwarding) //nolint:gocritic
err = i.ipv4Client.Insert(iptablesFilterTable, iptablesForwardChain, 1, rule...) err = i.ipv4Client.Insert(iptablesFilterTable, iptablesForwardChain, 1, rule...)
if err != nil { if err != nil {
@ -181,7 +181,7 @@ func (i *iptablesManager) addJumpRules() error {
} }
i.rules[ipv4][ipv4Forwarding] = rule i.rules[ipv4][ipv4Forwarding] = rule
rule = append(iptablesDefaultNatRule, ipv4Nat) rule = append(iptablesDefaultNatRule, ipv4Nat) //nolint:gocritic
err = i.ipv4Client.Insert(iptablesNatTable, iptablesPostRoutingChain, 1, rule...) err = i.ipv4Client.Insert(iptablesNatTable, iptablesPostRoutingChain, 1, rule...)
if err != nil { if err != nil {
return err return err
@ -190,14 +190,14 @@ func (i *iptablesManager) addJumpRules() error {
} }
if i.ipv6Client != nil { if i.ipv6Client != nil {
rule := append(iptablesDefaultForwardingRule, ipv6Forwarding) rule := append(iptablesDefaultForwardingRule, ipv6Forwarding) //nolint:gocritic
err = i.ipv6Client.Insert(iptablesFilterTable, iptablesForwardChain, 1, rule...) err = i.ipv6Client.Insert(iptablesFilterTable, iptablesForwardChain, 1, rule...)
if err != nil { if err != nil {
return err return err
} }
i.rules[ipv6][ipv6Forwarding] = rule i.rules[ipv6][ipv6Forwarding] = rule
rule = append(iptablesDefaultNatRule, ipv6Nat) rule = append(iptablesDefaultNatRule, ipv6Nat) //nolint:gocritic
err = i.ipv6Client.Insert(iptablesNatTable, iptablesPostRoutingChain, 1, rule...) err = i.ipv6Client.Insert(iptablesNatTable, iptablesPostRoutingChain, 1, rule...)
if err != nil { if err != nil {
return err return err

View File

@ -300,7 +300,7 @@ func (n *nftablesManager) acceptForwardRule(sourceNetwork string) error {
dst := generateCIDRMatcherExpressions("destination", "0.0.0.0/0") dst := generateCIDRMatcherExpressions("destination", "0.0.0.0/0")
var exprs []expr.Any var exprs []expr.Any
exprs = append(src, append(dst, &expr.Verdict{ exprs = append(src, append(dst, &expr.Verdict{ //nolint:gocritic
Kind: expr.VerdictAccept, Kind: expr.VerdictAccept,
})...) })...)
@ -322,7 +322,7 @@ func (n *nftablesManager) acceptForwardRule(sourceNetwork string) error {
src = generateCIDRMatcherExpressions("source", "0.0.0.0/0") src = generateCIDRMatcherExpressions("source", "0.0.0.0/0")
dst = generateCIDRMatcherExpressions("destination", sourceNetwork) dst = generateCIDRMatcherExpressions("destination", sourceNetwork)
exprs = append(src, append(dst, &expr.Verdict{ exprs = append(src, append(dst, &expr.Verdict{ //nolint:gocritic
Kind: expr.VerdictAccept, Kind: expr.VerdictAccept,
})...) })...)
@ -421,9 +421,9 @@ func (n *nftablesManager) insertRoutingRule(format, chain string, pair routerPai
var expression []expr.Any var expression []expr.Any
if isNat { if isNat {
expression = append(sourceExp, append(destExp, &expr.Counter{}, &expr.Masq{})...) expression = append(sourceExp, append(destExp, &expr.Counter{}, &expr.Masq{})...) //nolint:gocritic
} else { } else {
expression = append(sourceExp, append(destExp, exprCounterAccept...)...) expression = append(sourceExp, append(destExp, exprCounterAccept...)...) //nolint:gocritic
} }
ruleKey := genKey(format, pair.ID) ruleKey := genKey(format, pair.ID)

View File

@ -44,7 +44,7 @@ func TestNftablesManager_RestoreOrCreateContainers(t *testing.T) {
sourceExp := generateCIDRMatcherExpressions("source", pair.source) sourceExp := generateCIDRMatcherExpressions("source", pair.source)
destExp := generateCIDRMatcherExpressions("destination", pair.destination) destExp := generateCIDRMatcherExpressions("destination", pair.destination)
forward4Exp := append(sourceExp, append(destExp, exprCounterAccept...)...) forward4Exp := append(sourceExp, append(destExp, exprCounterAccept...)...) //nolint:gocritic
forward4RuleKey := genKey(forwardingFormat, pair.ID) forward4RuleKey := genKey(forwardingFormat, pair.ID)
inserted4Forwarding := nftablesTestingClient.InsertRule(&nftables.Rule{ inserted4Forwarding := nftablesTestingClient.InsertRule(&nftables.Rule{
Table: manager.tableIPv4, Table: manager.tableIPv4,
@ -53,7 +53,7 @@ func TestNftablesManager_RestoreOrCreateContainers(t *testing.T) {
UserData: []byte(forward4RuleKey), UserData: []byte(forward4RuleKey),
}) })
nat4Exp := append(sourceExp, append(destExp, &expr.Counter{}, &expr.Masq{})...) nat4Exp := append(sourceExp, append(destExp, &expr.Counter{}, &expr.Masq{})...) //nolint:gocritic
nat4RuleKey := genKey(natFormat, pair.ID) nat4RuleKey := genKey(natFormat, pair.ID)
inserted4Nat := nftablesTestingClient.InsertRule(&nftables.Rule{ inserted4Nat := nftablesTestingClient.InsertRule(&nftables.Rule{
@ -76,7 +76,7 @@ func TestNftablesManager_RestoreOrCreateContainers(t *testing.T) {
sourceExp = generateCIDRMatcherExpressions("source", pair.source) sourceExp = generateCIDRMatcherExpressions("source", pair.source)
destExp = generateCIDRMatcherExpressions("destination", pair.destination) destExp = generateCIDRMatcherExpressions("destination", pair.destination)
forward6Exp := append(sourceExp, append(destExp, exprCounterAccept...)...) forward6Exp := append(sourceExp, append(destExp, exprCounterAccept...)...) //nolint:gocritic
forward6RuleKey := genKey(forwardingFormat, pair.ID) forward6RuleKey := genKey(forwardingFormat, pair.ID)
inserted6Forwarding := nftablesTestingClient.InsertRule(&nftables.Rule{ inserted6Forwarding := nftablesTestingClient.InsertRule(&nftables.Rule{
Table: manager.tableIPv6, Table: manager.tableIPv6,
@ -85,7 +85,7 @@ func TestNftablesManager_RestoreOrCreateContainers(t *testing.T) {
UserData: []byte(forward6RuleKey), UserData: []byte(forward6RuleKey),
}) })
nat6Exp := append(sourceExp, append(destExp, &expr.Counter{}, &expr.Masq{})...) nat6Exp := append(sourceExp, append(destExp, &expr.Counter{}, &expr.Masq{})...) //nolint:gocritic
nat6RuleKey := genKey(natFormat, pair.ID) nat6RuleKey := genKey(natFormat, pair.ID)
inserted6Nat := nftablesTestingClient.InsertRule(&nftables.Rule{ inserted6Nat := nftablesTestingClient.InsertRule(&nftables.Rule{
@ -149,7 +149,7 @@ func TestNftablesManager_InsertRoutingRules(t *testing.T) {
sourceExp := generateCIDRMatcherExpressions("source", testCase.inputPair.source) sourceExp := generateCIDRMatcherExpressions("source", testCase.inputPair.source)
destExp := generateCIDRMatcherExpressions("destination", testCase.inputPair.destination) destExp := generateCIDRMatcherExpressions("destination", testCase.inputPair.destination)
testingExpression := append(sourceExp, destExp...) testingExpression := append(sourceExp, destExp...) //nolint:gocritic
fwdRuleKey := genKey(forwardingFormat, testCase.inputPair.ID) fwdRuleKey := genKey(forwardingFormat, testCase.inputPair.ID)
found := 0 found := 0
@ -188,7 +188,7 @@ func TestNftablesManager_InsertRoutingRules(t *testing.T) {
sourceExp = generateCIDRMatcherExpressions("source", getInPair(testCase.inputPair).source) sourceExp = generateCIDRMatcherExpressions("source", getInPair(testCase.inputPair).source)
destExp = generateCIDRMatcherExpressions("destination", getInPair(testCase.inputPair).destination) destExp = generateCIDRMatcherExpressions("destination", getInPair(testCase.inputPair).destination)
testingExpression = append(sourceExp, destExp...) testingExpression = append(sourceExp, destExp...) //nolint:gocritic
inFwdRuleKey := genKey(inForwardingFormat, testCase.inputPair.ID) inFwdRuleKey := genKey(inForwardingFormat, testCase.inputPair.ID)
found = 0 found = 0
@ -252,7 +252,7 @@ func TestNftablesManager_RemoveRoutingRules(t *testing.T) {
sourceExp := generateCIDRMatcherExpressions("source", testCase.inputPair.source) sourceExp := generateCIDRMatcherExpressions("source", testCase.inputPair.source)
destExp := generateCIDRMatcherExpressions("destination", testCase.inputPair.destination) destExp := generateCIDRMatcherExpressions("destination", testCase.inputPair.destination)
forwardExp := append(sourceExp, append(destExp, exprCounterAccept...)...) forwardExp := append(sourceExp, append(destExp, exprCounterAccept...)...) //nolint:gocritic
forwardRuleKey := genKey(forwardingFormat, testCase.inputPair.ID) forwardRuleKey := genKey(forwardingFormat, testCase.inputPair.ID)
insertedForwarding := nftablesTestingClient.InsertRule(&nftables.Rule{ insertedForwarding := nftablesTestingClient.InsertRule(&nftables.Rule{
Table: table, Table: table,
@ -261,7 +261,7 @@ func TestNftablesManager_RemoveRoutingRules(t *testing.T) {
UserData: []byte(forwardRuleKey), UserData: []byte(forwardRuleKey),
}) })
natExp := append(sourceExp, append(destExp, &expr.Counter{}, &expr.Masq{})...) natExp := append(sourceExp, append(destExp, &expr.Counter{}, &expr.Masq{})...) //nolint:gocritic
natRuleKey := genKey(natFormat, testCase.inputPair.ID) natRuleKey := genKey(natFormat, testCase.inputPair.ID)
insertedNat := nftablesTestingClient.InsertRule(&nftables.Rule{ insertedNat := nftablesTestingClient.InsertRule(&nftables.Rule{
@ -274,7 +274,7 @@ func TestNftablesManager_RemoveRoutingRules(t *testing.T) {
sourceExp = generateCIDRMatcherExpressions("source", getInPair(testCase.inputPair).source) sourceExp = generateCIDRMatcherExpressions("source", getInPair(testCase.inputPair).source)
destExp = generateCIDRMatcherExpressions("destination", getInPair(testCase.inputPair).destination) destExp = generateCIDRMatcherExpressions("destination", getInPair(testCase.inputPair).destination)
forwardExp = append(sourceExp, append(destExp, exprCounterAccept...)...) forwardExp = append(sourceExp, append(destExp, exprCounterAccept...)...) //nolint:gocritic
inForwardRuleKey := genKey(inForwardingFormat, testCase.inputPair.ID) inForwardRuleKey := genKey(inForwardingFormat, testCase.inputPair.ID)
insertedInForwarding := nftablesTestingClient.InsertRule(&nftables.Rule{ insertedInForwarding := nftablesTestingClient.InsertRule(&nftables.Rule{
Table: table, Table: table,
@ -283,7 +283,7 @@ func TestNftablesManager_RemoveRoutingRules(t *testing.T) {
UserData: []byte(inForwardRuleKey), UserData: []byte(inForwardRuleKey),
}) })
natExp = append(sourceExp, append(destExp, &expr.Counter{}, &expr.Masq{})...) natExp = append(sourceExp, append(destExp, &expr.Counter{}, &expr.Masq{})...) //nolint:gocritic
inNatRuleKey := genKey(inNatFormat, testCase.inputPair.ID) inNatRuleKey := genKey(inNatFormat, testCase.inputPair.ID)
insertedInNat := nftablesTestingClient.InsertRule(&nftables.Rule{ insertedInNat := nftablesTestingClient.InsertRule(&nftables.Rule{

View File

@ -2,11 +2,12 @@ package ssh
import ( import (
"fmt" "fmt"
"golang.org/x/crypto/ssh"
"golang.org/x/term"
"net" "net"
"os" "os"
"time" "time"
"golang.org/x/crypto/ssh"
"golang.org/x/term"
) )
// Client wraps crypto/ssh Client to simplify usage // Client wraps crypto/ssh Client to simplify usage
@ -73,8 +74,7 @@ func (c *Client) OpenTerminal() error {
if err := session.Wait(); err != nil { if err := session.Wait(); err != nil {
if e, ok := err.(*ssh.ExitError); ok { if e, ok := err.(*ssh.ExitError); ok {
switch e.ExitStatus() { if e.ExitStatus() == 130 {
case 130:
return nil return nil
} }
} }

View File

@ -44,8 +44,8 @@ func GetInfo(ctx context.Context) *Info {
} }
} }
osStr := strings.Replace(info, "\n", "", -1) osStr := strings.ReplaceAll(info, "\n", "")
osStr = strings.Replace(osStr, "\r\n", "", -1) osStr = strings.ReplaceAll(osStr, "\r\n", "")
osInfo := strings.Split(osStr, " ") osInfo := strings.Split(osStr, " ")
if osName == "" { if osName == "" {
osName = osInfo[3] osName = osInfo[3]

View File

@ -141,7 +141,7 @@ func (c *wGConfigurer) removeAllowedIP(peerKey string, allowedIP string) error {
for i, existingAllowedIP := range existingPeer.AllowedIPs { for i, existingAllowedIP := range existingPeer.AllowedIPs {
if existingAllowedIP.String() == ipNet.String() { if existingAllowedIP.String() == ipNet.String() {
newAllowedIPs = append(existingPeer.AllowedIPs[:i], existingPeer.AllowedIPs[i+1:]...) newAllowedIPs = append(existingPeer.AllowedIPs[:i], existingPeer.AllowedIPs[i+1:]...) //nolint:gocritic
break break
} }
} }

View File

@ -285,7 +285,7 @@ func Test_SystemMetaDataFromClient(t *testing.T) {
testKey, err := wgtypes.GenerateKey() testKey, err := wgtypes.GenerateKey()
if err != nil { if err != nil {
log.Fatal(err) t.Fatal(err)
} }
serverAddr := lis.Addr().String() serverAddr := lis.Addr().String()
@ -293,12 +293,12 @@ func Test_SystemMetaDataFromClient(t *testing.T) {
testClient, err := NewClient(ctx, serverAddr, testKey, false) testClient, err := NewClient(ctx, serverAddr, testKey, false)
if err != nil { if err != nil {
log.Fatalf("error while creating testClient: %v", err) t.Fatalf("error while creating testClient: %v", err)
} }
key, err := testClient.GetServerPublicKey() key, err := testClient.GetServerPublicKey()
if err != nil { if err != nil {
log.Fatalf("error while getting server public key from testclient, %v", err) t.Fatalf("error while getting server public key from testclient, %v", err)
} }
var actualMeta *mgmtProto.PeerSystemMeta var actualMeta *mgmtProto.PeerSystemMeta
@ -364,7 +364,7 @@ func Test_GetDeviceAuthorizationFlow(t *testing.T) {
testKey, err := wgtypes.GenerateKey() testKey, err := wgtypes.GenerateKey()
if err != nil { if err != nil {
log.Fatal(err) t.Fatal(err)
} }
serverAddr := lis.Addr().String() serverAddr := lis.Addr().String()
@ -372,7 +372,7 @@ func Test_GetDeviceAuthorizationFlow(t *testing.T) {
client, err := NewClient(ctx, serverAddr, testKey, false) client, err := NewClient(ctx, serverAddr, testKey, false)
if err != nil { if err != nil {
log.Fatalf("error while creating testClient: %v", err) t.Fatalf("error while creating testClient: %v", err)
} }
expectedFlowInfo := &mgmtProto.DeviceAuthorizationFlow{ expectedFlowInfo := &mgmtProto.DeviceAuthorizationFlow{
@ -408,7 +408,7 @@ func Test_GetPKCEAuthorizationFlow(t *testing.T) {
testKey, err := wgtypes.GenerateKey() testKey, err := wgtypes.GenerateKey()
if err != nil { if err != nil {
log.Fatal(err) t.Fatal(err)
} }
serverAddr := lis.Addr().String() serverAddr := lis.Addr().String()
@ -416,7 +416,7 @@ func Test_GetPKCEAuthorizationFlow(t *testing.T) {
client, err := NewClient(ctx, serverAddr, testKey, false) client, err := NewClient(ctx, serverAddr, testKey, false)
if err != nil { if err != nil {
log.Fatalf("error while creating testClient: %v", err) t.Fatalf("error while creating testClient: %v", err)
} }
expectedFlowInfo := &mgmtProto.PKCEAuthorizationFlow{ expectedFlowInfo := &mgmtProto.PKCEAuthorizationFlow{

View File

@ -950,14 +950,15 @@ func (am *DefaultAccountManager) newAccount(userID, domain string) (*Account, er
_, err := am.Store.GetAccount(accountId) _, err := am.Store.GetAccount(accountId)
statusErr, _ := status.FromError(err) statusErr, _ := status.FromError(err)
if err == nil { switch {
case err == nil:
log.Warnf("an account with ID already exists, retrying...") log.Warnf("an account with ID already exists, retrying...")
continue continue
} else if statusErr.Type() == status.NotFound { case statusErr.Type() == status.NotFound:
newAccount := newAccountWithId(accountId, userID, domain) newAccount := newAccountWithId(accountId, userID, domain)
am.StoreEvent(userID, newAccount.Id, accountId, activity.AccountCreated, nil) am.StoreEvent(userID, newAccount.Id, accountId, activity.AccountCreated, nil)
return newAccount, nil return newAccount, nil
} else { default:
return nil, err return nil, err
} }
} }

View File

@ -300,7 +300,7 @@ func toPolicyResponse(account *server.Account, policy *server.Policy) *api.Polic
Action: api.PolicyRuleAction(r.Action), Action: api.PolicyRuleAction(r.Action),
} }
if len(r.Ports) != 0 { if len(r.Ports) != 0 {
portsCopy := r.Ports[:] portsCopy := r.Ports
rule.Ports = &portsCopy rule.Ports = &portsCopy
} }
for _, gid := range r.Sources { for _, gid := range r.Sources {

View File

@ -192,13 +192,14 @@ func writeSuccess(w http.ResponseWriter, key *server.SetupKey) {
func toResponseBody(key *server.SetupKey) *api.SetupKey { func toResponseBody(key *server.SetupKey) *api.SetupKey {
var state string var state string
if key.IsExpired() { switch {
case key.IsExpired():
state = "expired" state = "expired"
} else if key.IsRevoked() { case key.IsRevoked():
state = "revoked" state = "revoked"
} else if key.IsOverUsed() { case key.IsOverUsed():
state = "overused" state = "overused"
} else { default:
state = "valid" state = "valid"
} }

View File

@ -463,11 +463,9 @@ func (zp zitadelProfile) userData() *UserData {
if zp.Human != nil { if zp.Human != nil {
email = zp.Human.Email.Email email = zp.Human.Email.Email
name = zp.Human.Profile.DisplayName name = zp.Human.Profile.DisplayName
} else { } else if len(zp.LoginNames) > 0 {
if len(zp.LoginNames) > 0 { email = zp.LoginNames[0]
email = zp.LoginNames[0] name = zp.LoginNames[0]
name = zp.LoginNames[0]
}
} }
return &UserData{ return &UserData{

View File

@ -200,14 +200,14 @@ func (w *Worker) generateProperties() properties {
expirationEnabled++ expirationEnabled++
} }
groups = groups + len(account.Groups) groups += len(account.Groups)
routes = routes + len(account.Routes) routes += len(account.Routes)
for _, route := range account.Routes { for _, route := range account.Routes {
if len(route.PeerGroups) > 0 { if len(route.PeerGroups) > 0 {
routesWithRGGroups++ routesWithRGGroups++
} }
} }
nameservers = nameservers + len(account.NameServerGroups) nameservers += len(account.NameServerGroups)
for _, policy := range account.Policies { for _, policy := range account.Policies {
for _, rule := range policy.Rules { for _, rule := range policy.Rules {
@ -231,10 +231,10 @@ func (w *Worker) generateProperties() properties {
} }
for _, key := range account.SetupKeys { for _, key := range account.SetupKeys {
setupKeysUsage = setupKeysUsage + key.UsedTimes setupKeysUsage += key.UsedTimes
if key.Ephemeral { if key.Ephemeral {
ephemeralPeersSKs++ ephemeralPeersSKs++
ephemeralPeersSKUsage = ephemeralPeersSKUsage + key.UsedTimes ephemeralPeersSKUsage += key.UsedTimes
} }
} }

View File

@ -66,7 +66,7 @@ func NewNetwork() *Network {
func (n *Network) IncSerial() { func (n *Network) IncSerial() {
n.mu.Lock() n.mu.Lock()
defer n.mu.Unlock() defer n.mu.Unlock()
n.Serial = n.Serial + 1 n.Serial++
} }
// CurrentSerial returns the Network.Serial of the network (latest state id) // CurrentSerial returns the Network.Serial of the network (latest state id)

View File

@ -406,7 +406,7 @@ func (am *DefaultAccountManager) ListPolicies(accountID, userID string) ([]*Poli
return nil, status.Errorf(status.PermissionDenied, "Only Administrators can view policies") return nil, status.Errorf(status.PermissionDenied, "Only Administrators can view policies")
} }
return account.Policies[:], nil return account.Policies, nil
} }
func (am *DefaultAccountManager) deletePolicy(account *Account, policyID string) (*Policy, error) { func (am *DefaultAccountManager) deletePolicy(account *Account, policyID string) (*Policy, error) {

View File

@ -137,7 +137,7 @@ func (key *SetupKey) HiddenCopy(length int) *SetupKey {
// IncrementUsage makes a copy of a key, increments the UsedTimes by 1 and sets LastUsed to now // IncrementUsage makes a copy of a key, increments the UsedTimes by 1 and sets LastUsed to now
func (key *SetupKey) IncrementUsage() *SetupKey { func (key *SetupKey) IncrementUsage() *SetupKey {
c := key.Copy() c := key.Copy()
c.UsedTimes = c.UsedTimes + 1 c.UsedTimes++
c.LastUsed = time.Now().UTC() c.LastUsed = time.Now().UTC()
return c return c
} }

View File

@ -248,7 +248,7 @@ func (s *SharedSocket) ReadFrom(b []byte) (n int, addr net.Addr, err error) {
decodedLayers := make([]gopacket.LayerType, 0, 3) decodedLayers := make([]gopacket.LayerType, 0, 3)
err = parser.DecodeLayers(pkt.buf[:], &decodedLayers) err = parser.DecodeLayers(pkt.buf, &decodedLayers)
if err != nil { if err != nil {
return 0, nil, err return 0, nil, err
} }

View File

@ -354,16 +354,17 @@ func (c *GrpcClient) receive(stream proto.SignalExchange_ConnectStreamClient,
for { for {
msg, err := stream.Recv() msg, err := stream.Recv()
if s, ok := status.FromError(err); ok && s.Code() == codes.Canceled { switch s, ok := status.FromError(err); {
case ok && s.Code() == codes.Canceled:
log.Debugf("stream canceled (usually indicates shutdown)") log.Debugf("stream canceled (usually indicates shutdown)")
return err return err
} else if s.Code() == codes.Unavailable { case s.Code() == codes.Unavailable:
log.Debugf("Signal Service is unavailable") log.Debugf("Signal Service is unavailable")
return err return err
} else if err == io.EOF { case err == io.EOF:
log.Debugf("Signal Service stream closed by server") log.Debugf("Signal Service stream closed by server")
return err return err
} else if err != nil { case err != nil:
return err return err
} }
log.Tracef("received a new message from Peer [fingerprint: %s]", msg.Key) log.Tracef("received a new message from Peer [fingerprint: %s]", msg.Key)

View File

@ -15,7 +15,7 @@ func Retry(attempts int, sleep time.Duration, toExec func() error, onError func(
if attempts--; attempts > 0 { if attempts--; attempts > 0 {
jitter := time.Duration(rand.Int63n(int64(sleep))) jitter := time.Duration(rand.Int63n(int64(sleep)))
sleep = sleep + jitter/2 sleep += jitter / 2
onError(err) onError(err)
time.Sleep(sleep) time.Sleep(sleep)