Skip to content

Commit

Permalink
resolve golint issue
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffhuang4704 committed Oct 14, 2024
1 parent 7fd295f commit 68e58ec
Show file tree
Hide file tree
Showing 35 changed files with 363 additions and 265 deletions.
2 changes: 1 addition & 1 deletion controller/access/access.go
Original file line number Diff line number Diff line change
Expand Up @@ -1357,7 +1357,7 @@ type AccessOP string

const (
AccessOPRead AccessOP = "read"
AccessOPWrite = "write"
AccessOPWrite AccessOP = "write"
)

const AccessDomainGlobal = ""
Expand Down
20 changes: 10 additions & 10 deletions controller/common/marshal_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,15 +48,15 @@ func TestMask(t *testing.T) {

var user maskUser
body, _ := m.Marshal(&u1)
json.Unmarshal(body, &user)
_ = json.Unmarshal(body, &user)
if user.Password != api.RESTMaskedValue || *user.Secret != api.RESTMaskedValue {
t.Errorf("Incorrect mask marshal: %s", string(body[:]))
}

var pair maskUserPair
p := maskUserPair{User1: u1, User2: &u2}
body, _ = m.Marshal(&p)
json.Unmarshal(body, &pair)
_ = json.Unmarshal(body, &pair)
if pair.User1.Password != api.RESTMaskedValue || *pair.User1.Secret != api.RESTMaskedValue ||
pair.User2.Password != api.RESTMaskedValue || *pair.User2.Secret != api.RESTMaskedValue {
t.Errorf("Incorrect mask marshal: %s", string(body[:]))
Expand All @@ -65,7 +65,7 @@ func TestMask(t *testing.T) {
var list maskUserList
l := maskUserList{Users: []*maskUser{&u1, &u2}}
body, _ = m.Marshal(&l)
json.Unmarshal(body, &list)
_ = json.Unmarshal(body, &list)
if list.Users[0].Password != api.RESTMaskedValue || *list.Users[0].Secret != api.RESTMaskedValue ||
list.Users[1].Password != api.RESTMaskedValue || *list.Users[1].Secret != api.RESTMaskedValue {
t.Errorf("Incorrect mask marshal: %s", string(body[:]))
Expand All @@ -78,14 +78,14 @@ func TestMaskEmpty(t *testing.T) {

d1 := maskEmpty{Map: make(map[string]int), List: make([]int, 0)}
body, _ := m.Marshal(&d1)
json.Unmarshal(body, &d)
_ = json.Unmarshal(body, &d)
if d.Map == nil || d.List == nil {
t.Errorf("Incorrect mask marshal: %s", string(body[:]))
}

d1 = maskEmpty{}
body, _ = m.Marshal(&d1)
json.Unmarshal(body, &d)
_ = json.Unmarshal(body, &d)
if d.Map != nil || d.List != nil {
t.Errorf("Incorrect mask marshal: %s", string(body[:]))
}
Expand All @@ -101,7 +101,7 @@ func TestEncrypt(t *testing.T) {

var user maskUser
body, _ := enc.Marshal(&u1)
dec.Unmarshal(body, &user)
_ = dec.Unmarshal(body, &user)
if !reflect.DeepEqual(user, u1) {
t.Errorf("Incorrect mask marshal: marshal=%s", string(body[:]))
body, _ = json.Marshal(&user)
Expand All @@ -111,7 +111,7 @@ func TestEncrypt(t *testing.T) {
var pair maskUserPair
p := maskUserPair{User1: u1, User2: &u2}
body, _ = enc.Marshal(&p)
dec.Unmarshal(body, &pair)
_ = dec.Unmarshal(body, &pair)
if !reflect.DeepEqual(pair.User1, u1) || !reflect.DeepEqual(*pair.User2, u2) {
t.Errorf("Incorrect mask marshal: marshal=%s", string(body[:]))
body, _ = json.Marshal(&pair)
Expand All @@ -135,7 +135,7 @@ func TestSpecialType(t *testing.T) {
IPs: []net.IP{net.IPv4(1, 2, 3, 4), net.IPv4(9, 8, 7, 6)},
}
body, _ := enc.Marshal(&a)
dec.Unmarshal(body, &b)
_ = dec.Unmarshal(body, &b)
if !reflect.DeepEqual(a, b) {
t.Errorf("Incorrect mask marshal: marshal=%s", string(body[:]))
}
Expand All @@ -145,13 +145,13 @@ func TestAuthServer(t *testing.T) {
body := "{\"config\":{\"ldap\":{\"base_dn\":\"abc\",\"bind_dn\":\"abc\",\"bind_password\":\"very sensitive\",\"directory\":\"OpenLDAP\",\"enable\":true,\"hostname\":\"1.2.3.4\",\"role_groups\":{\"admin\":[],\"reader\":[]}},\"name\":\"ldap1\"}}"

var rconf api.RESTServerConfigData
json.Unmarshal([]byte(body), &rconf)
_ = json.Unmarshal([]byte(body), &rconf)

var m MaskMarshaller
masked, _ := m.Marshal(&rconf)

var maskedConf api.RESTServerConfigData
json.Unmarshal(masked, &maskedConf)
_ = json.Unmarshal(masked, &maskedConf)

if *maskedConf.Config.LDAP.BindPasswd != api.RESTMaskedValue {
t.Errorf("Incorrect mask marshal: marshal=%s", string(masked[:]))
Expand Down
24 changes: 4 additions & 20 deletions controller/rest/admission.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ func applyTransact(w http.ResponseWriter, txn *cluster.ClusterTransact) error {
if w != nil {
restRespErrorMessage(w, http.StatusInternalServerError, api.RESTErrFailWriteCluster, e)
}
return fmt.Errorf(e)
return fmt.Errorf("%s", e)
}
return nil
}
Expand Down Expand Up @@ -475,22 +475,6 @@ func handlerPatchAdmissionState(w http.ResponseWriter, r *http.Request, ps httpr
log.Error("Request contains invalid data")
restRespError(w, http.StatusBadRequest, api.RESTErrInvalidRequest)
return
} else if state.FailurePolicy != nil {
/* do not allow admission control webhook's FailurePolicy to be configurable yet
invalidFailurePolicy := false
if admission.IsNsSelectorSupported() {
if *state.FailurePolicy != resource.IgnoreLower && *state.FailurePolicy != resource.FailLower {
invalidFailurePolicy = true
}
} else if state.FailurePolicy != nil && *state.FailurePolicy != *currState.FailurePolicy {
invalidFailurePolicy = true
}
if invalidFailurePolicy {
e := fmt.Errorf("Request contains invalid FailurePolicy: %s", *state.FailurePolicy)
log.Error(e)
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrInvalidRequest, e.Error())
}
*/
}
if state.Mode != nil && *state.Mode == share.AdmCtrlModeProtect {
if !licenseAllowEnforce() {
Expand Down Expand Up @@ -1505,7 +1489,7 @@ func importAdmCtrl(scope string, loginDomainRoles access.DomainRole, importTask
if err := json.Unmarshal(json_data, &secRule); err != nil || secRule.APIVersion != "neuvector.com/v1" || secRule.Kind != resource.NvAdmCtrlSecurityRuleKind {
msg := "Invalid security rule(s)"
log.WithFields(log.Fields{"error": err}).Error(msg)
postImportOp(fmt.Errorf(msg), importTask, loginDomainRoles, "", share.IMPORT_TYPE_ADMCTRL)
postImportOp(fmt.Errorf("%s", msg), importTask, loginDomainRoles, "", share.IMPORT_TYPE_ADMCTRL)
return nil
}

Expand All @@ -1528,7 +1512,7 @@ func importAdmCtrl(scope string, loginDomainRoles access.DomainRole, importTask
// [1] parse security rule in the yaml file
parsedCfg, errCount, errMsg, _ := crdHandler.parseCurCrdAdmCtrlContent(&secRule, share.ReviewTypeImportAdmCtrl, share.ReviewTypeDisplayAdmission)
if errCount > 0 {
err = fmt.Errorf(errMsg)
err = fmt.Errorf("%s", errMsg)
} else {
progress += inc
importTask.Percentage = int(progress)
Expand All @@ -1540,7 +1524,7 @@ func importAdmCtrl(scope string, loginDomainRoles access.DomainRole, importTask
var currState *api.RESTAdmissionState
if currState, err = cacher.GetAdmissionState(acc); err == nil {
if currState.CfgType == api.CfgTypeGround {
err = fmt.Errorf(restErrMessage[api.RESTErrOpNotAllowed])
err = fmt.Errorf("%s", restErrMessage[api.RESTErrOpNotAllowed])
} else {
err = crdHandler.crdHandleAdmCtrlConfig(scope, parsedCfg.AdmCtrlCfg, nil, share.ReviewTypeImportAdmCtrl)
}
Expand Down
14 changes: 9 additions & 5 deletions controller/rest/admwebhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -1141,11 +1141,13 @@ func (whsvr *WebhookServer) validate(ar *admissionv1beta1.AdmissionReview, globa
totalContainers := 0
{
reqImages := make([]string, 0, len(admResObject.AllContainers))
for _, containers := range admResObject.AllContainers {
for _, c := range containers {
reqImages = append(reqImages, c.Image)
if admResObject != nil {
for _, containers := range admResObject.AllContainers {
for _, c := range containers {
reqImages = append(reqImages, c.Image)
}
totalContainers += len(containers)
}
totalContainers += len(containers)
}
stamps.Images = strings.Join(reqImages, ",")
}
Expand Down Expand Up @@ -1356,7 +1358,9 @@ func (whsvr *WebhookServer) serveK8s(w http.ResponseWriter, r *http.Request, adm

if admType == admission.NvAdmValidateType {
admissionResponse, _, ignoredReq = whsvr.validate(&ar, globalMode, defaultAction, stamps, false)
admissionResponse.UID = ar.Request.UID
if admissionResponse != nil {
admissionResponse.UID = ar.Request.UID
}
} else {
log.WithFields(log.Fields{"path": r.URL.Path}).Debug("unsupported path")
http.Error(w, "unsupported", http.StatusNotImplemented)
Expand Down
9 changes: 5 additions & 4 deletions controller/rest/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -1192,11 +1192,12 @@ func ResetLoginTokenTimer(tokenInfo *share.CLUSLoginTokenInfo) {
login.timer.Reset(getUserTimeout(login.timeout))
login.lastAt = time.Now()
}
} else {
// if this controller doesn't know this token yet, it's fine.
// later when a resp api request reaches this controller, if the token is still not in kv,
// this controller will accept it and start a new timer for this token
}
// else {
// // if this controller doesn't know this token yet, it's fine.
// // later when a resp api request reaches this controller, if the token is still not in kv,
// // this controller will accept it and start a new timer for this token
// }
}
}

Expand Down
26 changes: 13 additions & 13 deletions controller/rest/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,14 +104,14 @@ func makeLocalUserWithRole(username, password, role string, roleDomains map[stri

func getLoginToken(w *mockResponseWriter) string {
var data api.RESTTokenData
json.Unmarshal(w.body, &data)
_ = json.Unmarshal(w.body, &data)
return data.Token.Token
}

func checkUserAttrs(w *mockResponseWriter, server, user, role string, tmo uint32) error {
// Check returned User attributes
var data api.RESTTokenData
json.Unmarshal(w.body, &data)
_ = json.Unmarshal(w.body, &data)
if data.Token.Server != server || data.Token.Username != user || data.Token.Role != role {
return fmt.Errorf("Error in user attributes: %+v", *data.Token)
}
Expand All @@ -138,7 +138,7 @@ func TestLocalLogin(t *testing.T) {
clusHelper = &mockCluster

user := makeLocalUser("user", "pass", api.UserRoleReader)
clusHelper.CreateUser(user)
_ = clusHelper.CreateUser(user)

cacher = &mockCache{}

Expand Down Expand Up @@ -184,7 +184,7 @@ func TestLDAPLogin(t *testing.T) {
},
},
}
clusHelper.PutServerRev(&ldap, 0)
_ = clusHelper.PutServerRev(&ldap, 0)

mockAuther := mockRemoteAuth{users: make(map[string]*passwordUser)}
// User group membership doesn't match role group mapping
Expand Down Expand Up @@ -219,7 +219,7 @@ func TestLDAPLogin(t *testing.T) {
// Revert user group membership, add default role to server
mockAuther.addPasswordUser("user", "pass", []string{"group2"})
ldap.LDAP.DefaultRole = api.UserRoleAdmin
clusHelper.PutServerRev(&ldap, 0)
_ = clusHelper.PutServerRev(&ldap, 0)

w = login("user", "pass")
if w.status != http.StatusOK {
Expand Down Expand Up @@ -383,7 +383,7 @@ func TestLocalLoginServer(t *testing.T) {
clusHelper = &mockCluster

user := makeLocalUser("user", "pass", api.UserRoleAdmin)
clusHelper.CreateUser(user)
_ = clusHelper.CreateUser(user)

cacher = &mockCache{}

Expand Down Expand Up @@ -436,7 +436,7 @@ func TestLDAPLoginServer(t *testing.T) {
},
},
}
clusHelper.PutServerRev(&ldap, 0)
_ = clusHelper.PutServerRev(&ldap, 0)

mockAuther := mockRemoteAuth{users: make(map[string]*passwordUser)}
// User group membership doesn't match role group mapping
Expand Down Expand Up @@ -485,7 +485,7 @@ func TestSAMLLogin(t *testing.T) {
},
},
}
clusHelper.PutServerRev(&ldap, 0)
_ = clusHelper.PutServerRev(&ldap, 0)

// Not enabled
saml := share.CLUSServer{
Expand All @@ -505,7 +505,7 @@ func TestSAMLLogin(t *testing.T) {
X509Cert: "cert",
},
}
clusHelper.PutServerRev(&saml, 0)
_ = clusHelper.PutServerRev(&saml, 0)

mockAuther := mockRemoteAuth{samlUsers: make(map[string]*samlUser)}
mockAuther.addSAMLUser("token", map[string][]string{"Email": {"[email protected]"}})
Expand Down Expand Up @@ -570,7 +570,7 @@ func TestSAMLLoginShadowUser(t *testing.T) {
X509Cert: "cert",
},
}
clusHelper.PutServerRev(&saml, 0)
_ = clusHelper.PutServerRev(&saml, 0)

username := "joe"
mockAuther := mockRemoteAuth{samlUsers: make(map[string]*samlUser)}
Expand Down Expand Up @@ -612,7 +612,7 @@ func TestSAMLLoginShadowUser(t *testing.T) {

// Modify user's timeout and role by admin
admin := makeLocalUser("admin", "admin", api.UserRoleAdmin)
clusHelper.CreateUser(admin)
_ = clusHelper.CreateUser(admin)
w = login("admin", "admin")
tokenAdmin := getLoginToken(w)

Expand Down Expand Up @@ -828,7 +828,7 @@ func TestOIDCLogin(t *testing.T) {
},
},
}
clusHelper.PutServerRev(&ldap, 0)
_ = clusHelper.PutServerRev(&ldap, 0)

// Not enabled
oidc := share.CLUSServer{
Expand All @@ -846,7 +846,7 @@ func TestOIDCLogin(t *testing.T) {
Issuer: "issuer",
},
}
clusHelper.PutServerRev(&oidc, 0)
_ = clusHelper.PutServerRev(&oidc, 0)

mockAuther := mockRemoteAuth{oidcUsers: make(map[string]*oidcUser)}
mockAuther.addOIDCUser("token", map[string]interface{}{oidcPreferredNameKey: "[email protected]"})
Expand Down
1 change: 1 addition & 0 deletions controller/rest/bench.go
Original file line number Diff line number Diff line change
Expand Up @@ -752,6 +752,7 @@ func getKubeCISReportFromCluster(id string, cpf *complianceProfileFilter, acc *a
rpt1, code, _ := getCISReportFromCluster(share.BenchKubeMaster, id, cpf, acc)
if code != 0 {
// Ignore the error in the master node as some nodes are not master. (BenchStatusNotSupport)
log.WithFields(log.Fields{"code": code}).Debug("Ignore the error in the master node as some nodes are not master")
}
rpt2, code, errMsg := getCISReportFromCluster(share.BenchKubeWorker, id, cpf, acc)
if code != 0 {
Expand Down
4 changes: 2 additions & 2 deletions controller/rest/compliance.go
Original file line number Diff line number Diff line change
Expand Up @@ -592,7 +592,7 @@ func importCompProfile(scope string, loginDomainRoles access.DomainRole, importT
if invalidCrdKind || len(secRules) == 0 {
msg := "Invalid security rule(s)"
log.WithFields(log.Fields{"error": err}).Error(msg)
postImportOp(fmt.Errorf(msg), importTask, loginDomainRoles, "", share.IMPORT_TYPE_COMP_PROFILE)
postImportOp(fmt.Errorf("%s", msg), importTask, loginDomainRoles, "", share.IMPORT_TYPE_COMP_PROFILE)
return nil
}

Expand All @@ -615,7 +615,7 @@ func importCompProfile(scope string, loginDomainRoles access.DomainRole, importT
// [1]: parse all security rules in the yaml file
for _, secRule := range secRules {
if cpCfgRet, errCount, errMsg, _ := crdHandler.parseCurCrdCompProfileContent(&secRule, share.ReviewTypeImportCompProfile, share.ReviewTypeDisplayCompProfile); errCount > 0 {
err = fmt.Errorf(errMsg)
err = fmt.Errorf("%s", errMsg)
break
} else {
cmpProfilesCfg = append(cmpProfilesCfg, cpCfgRet)
Expand Down
6 changes: 3 additions & 3 deletions controller/rest/configmap_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,7 +352,7 @@ func TestUserCfg(t *testing.T) {
mockCluster.SetCacheMockCallback(share.CLUSConfigUserRoleStore, cache.MockUserRoleConfigUpdate)

defProfile := mockCacheInstance.pwdProfiles[share.CLUSDefPwdProfileName]
clusHelper.PutPwdProfileRev(defProfile, 0)
_ = clusHelper.PutPwdProfileRev(defProfile, 0)

var context configMapHandlerContext
// test variation of white space before/after value etc
Expand All @@ -372,7 +372,7 @@ func TestUserCfg(t *testing.T) {
`
// create referenced custom role first
yaml_byte0 := []byte(yaml_data0)
handlecustomrolecfg(yaml_byte0, true, &skip, &context)
_ = handlecustomrolecfg(yaml_byte0, true, &skip, &context)
if s1, _, _ := clusHelper.GetCustomRoleRev("testRole123", accAdmin); s1 == nil {
t.Errorf("Fail to get testRole123 config\n")
}
Expand Down Expand Up @@ -477,7 +477,7 @@ func TestUserCfgNegative(t *testing.T) {

cacher = mockCacheInstance
defProfile := mockCacheInstance.pwdProfiles[share.CLUSDefPwdProfileName]
clusHelper.PutPwdProfileRev(defProfile, 0)
_ = clusHelper.PutPwdProfileRev(defProfile, 0)

// negative test about user assigned a non-existing custom role

Expand Down
6 changes: 3 additions & 3 deletions controller/rest/crdsecurityrule.go
Original file line number Diff line number Diff line change
Expand Up @@ -1368,7 +1368,7 @@ func (h *nvCrdHandler) crdHandleAdmCtrlConfig(scope string, crdConfig *resource.
failurePolicy := resource.IgnoreLower
status, code, origConf, cconf := setAdmCtrlStateInCluster(&crdConfig.Enable, &crdConfig.Mode, &defaultAction, &crdConfig.AdmClientMode, &failurePolicy, cfgType)
if status != http.StatusOK {
return fmt.Errorf(restErrMessage[code])
return fmt.Errorf("%s", restErrMessage[code])
}
time.Sleep(time.Second)

Expand Down Expand Up @@ -1630,7 +1630,7 @@ func (h *nvCrdHandler) crdHandleVulnProfile(vulnProfileCfg *resource.NvCrdVulnPr
}
} else if cvp != nil && cvp.CfgType != cfgType && cvp.CfgType == share.GroundCfg {
log.WithFields(log.Fields{"name": vulnProfileCfg.Profile.Name}).Error("profile is managed by CRD")
return fmt.Errorf(restErrMessage[api.RESTErrOpNotAllowed])
return fmt.Errorf("%s", restErrMessage[api.RESTErrOpNotAllowed])
}
if cvp, err = configVulnerabilityProfile(vulnProfileCfg.Profile, option, cfgType, cvp); err == nil {
if err = clusHelper.PutVulnerabilityProfile(cvp, nil); err == nil && cacheRecord != nil {
Expand All @@ -1655,7 +1655,7 @@ func (h *nvCrdHandler) crdHandleCompProfile(compProfileCfg *resource.NvCrdCompPr
ccp, _, _ := clusHelper.GetComplianceProfile(compProfileCfg.Templates.Name, h.acc)
if ccp != nil && ccp.CfgType != cfgType && ccp.CfgType == share.GroundCfg {
log.WithFields(log.Fields{"name": compProfileCfg.Templates.Name}).Error("profile is managed by CRD")
return fmt.Errorf(restErrMessage[api.RESTErrOpNotAllowed])
return fmt.Errorf("%s", restErrMessage[api.RESTErrOpNotAllowed])
}
ccp = &share.CLUSComplianceProfile{
Name: compProfileCfg.Templates.Name,
Expand Down
Loading

0 comments on commit 68e58ec

Please sign in to comment.