Skip to content

Commit

Permalink
fix golang lint issues
Browse files Browse the repository at this point in the history
  • Loading branch information
jeffhuang4704 committed Oct 13, 2024
1 parent 308e57b commit 11c75d4
Show file tree
Hide file tree
Showing 25 changed files with 55 additions and 104 deletions.
4 changes: 2 additions & 2 deletions controller/controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -1094,8 +1094,8 @@ func amendStubRtInfo() error {
}

func amendNotPrivilegedMode() error {
podname, _ := Ctrler.Labels["io.kubernetes.pod.name"]
domain, _ := Ctrler.Labels["io.kubernetes.pod.namespace"]
podname := Ctrler.Labels["io.kubernetes.pod.name"]
domain := Ctrler.Labels["io.kubernetes.pod.namespace"]
if o, err := global.ORCH.GetResource(resource.RscTypePod, domain, podname); err != nil {
return fmt.Errorf("can not found: err = %v, %v, %v", domain, podname, err)
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -773,10 +773,8 @@ func TestAdmWebhookConnection(svcname string) (int, error) {
}
tag := fmt.Sprintf("%d", time.Now().Unix())
svc.Labels[keys.TagKey] = tag
if _, ok := svc.Labels[keys.EchoKey]; ok {
delete(svc.Labels, keys.EchoKey)
// we need adm webhook server to add 'echo' label later
}
delete(svc.Labels, keys.EchoKey)
// we need adm webhook server to add 'echo' label later
err = global.ORCH.UpdateResource(resource.RscTypeService, svc)
if err != nil {
log.WithFields(log.Fields{"service": svcname, "svc": svc, "err": err}).Error("update resource failed")
Expand Down
1 change: 0 additions & 1 deletion controller/orch.go
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,6 @@ func (c *orchConn) cbWatcherState(state string, err error) {
log.WithFields(log.Fields{"error": err}).Error()
}
}
return
}

func (c *orchConn) cbResourceWatcher(rt string, event string, res interface{}, old interface{}) {
Expand Down
2 changes: 1 addition & 1 deletion controller/resource/csp_billing_adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ func GetCspConfig() api.RESTFedCspSupportResp {
if cm, ok := obj.(*corev1.ConfigMap); cm == nil || !ok {
err = fmt.Errorf("Error: Unknown type")
} else if cm.Data != nil {
resp.MeteringArchiveData, _ = cm.Data["archive"]
resp.MeteringArchiveData = cm.Data["archive"]
}
}

Expand Down
4 changes: 1 addition & 3 deletions controller/resource/kubernetes_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,9 +246,7 @@ func (d *kubernetes) GetPlatformUserGroups(token string) ([]string, error) {
}

log.WithFields(log.Fields{"url": url, "user": user}).Debug("getPlatformUserGroups")
for _, group := range user.Groups {
groups = append(groups, group)
}
groups = append(groups, user.Groups...)

return groups, nil
}
Expand Down
23 changes: 9 additions & 14 deletions controller/resource/kubernetes_rbac.go
Original file line number Diff line number Diff line change
Expand Up @@ -474,9 +474,7 @@ func k8s2NVRolePermits(k8sFlavor, rbacRoleName string, rscs, readVerbs, writeVer
nvRole = api.UserRoleReader
}
} else {
if strings.HasPrefix(rsc, nvPermRscPrefix) {
rsc = rsc[len(nvPermRscPrefix):]
}
rsc = strings.TrimPrefix(rsc, nvPermRscPrefix)
if v, ok := nvPermitsValueSSO[rsc]; ok {
if verbs.Contains("*") || writeVerbs.Intersect(verbs).Cardinality() == writeVerbs.Cardinality() {
nvPermits.Union(v)
Expand Down Expand Up @@ -615,7 +613,6 @@ func deduceRoleRules(k8sFlavor, rbacRoleName, rbacRoleDomain string, objs interf
case api.UserRoleFedAdmin:
nvRole = api.UserRoleFedAdmin
nvPermits.Reset()
break
case api.UserRoleFedReader:
if nvRole == api.UserRoleReader || nvRole == api.UserRoleNone {
nvRole = api.UserRoleFedReader
Expand Down Expand Up @@ -1363,7 +1360,7 @@ func RemoveRedundant(allDomainRoles map[string]share.NvReservedUserRole, domainP
if nvRoles&share.UserRoleFedReader != 0 && fedRole == api.FedRoleMaster {
if d == access.AccessDomainGlobal {
// move fedReader to permissions
nvPermits, _ := domainPermits[access.AccessDomainGlobal]
nvPermits := domainPermits[access.AccessDomainGlobal]
nvPermits.Local.ReadValue = share.PERMS_FED_READ
nvPermits.Remote.ReadValue = share.PERMS_CLUSTER_READ
if nvPermits.Local.WriteValue&share.PERM_FED == 0 {
Expand Down Expand Up @@ -1433,7 +1430,7 @@ func RemoveRedundant(allDomainRoles map[string]share.NvReservedUserRole, domainP
nvGlobalRolePermits.Local.ReadValue = share.PERMS_CLUSTER_READ
}

nvGlobalPermits, _ := domainPermits[access.AccessDomainGlobal] // extra permissions on global domain
nvGlobalPermits := domainPermits[access.AccessDomainGlobal] // extra permissions on global domain
nvGlobalPermits.Local.FilterPermits("", "local", fedRole)
nvGlobalPermits.Local.ResetIfSubsetOf(nvGlobalRolePermits.Local)
nvGlobalPermits.Remote.FilterPermits("", "remote", fedRole)
Expand Down Expand Up @@ -1521,7 +1518,7 @@ func (d *kubernetes) rbacEvaluateUser(user k8sSubjectObjRef) {
for r := range roleRefs.Iter() {
var nvPermits share.NvFedPermissions
roleRef := r.(k8sRoleRef)
nvRole, _ := d.roleCache[roleRef.role] // d.roleCache : k8s (cluster)role -> nv reserved role
nvRole := d.roleCache[roleRef.role] // d.roleCache : k8s (cluster)role -> nv reserved role
// This k8s (cluster)role is in roleCache (i.e. it has a mpped nv reserved role).
// In k8s2NVRolePermits() we cannot tell a k8s clusterrole is for Rancher Cluster Role or Project Role.
// It's possible that nvRole is fedAdmin/fedReader even it's Rancher Project Role which is not allowed.
Expand All @@ -1537,7 +1534,7 @@ func (d *kubernetes) rbacEvaluateUser(user k8sSubjectObjRef) {
allDomainRoles[roleRef.domain] = allDomainRoles[roleRef.domain] | reservedRoleMapping[nvRole]
}

k8sRolePermits, _ := d.permitsCache[roleRef.role] // d.permitsCache : k8s (cluster)role -> nv permissions
k8sRolePermits := d.permitsCache[roleRef.role] // d.permitsCache : k8s (cluster)role -> nv permissions
// Merge this k8s role's local/remote nv permissions into this domain's local/remote nv permissions
// In k8s2NVRolePermits() we cannot tell a k8s clusterrole is for Rancher Cluster Role or Project Role.
// It's possible that k8sRolePermits contains PERM_FED even it's Rancher Project Role which is not allowed.
Expand All @@ -1550,7 +1547,7 @@ func (d *kubernetes) rbacEvaluateUser(user k8sSubjectObjRef) {
nvPermits.Remote.WriteValue = k8sRolePermits.WriteValue & noPermitFed
}
if !nvPermits.IsEmpty() {
p, _ := domainPermits[roleRef.domain]
p := domainPermits[roleRef.domain]
p.Local.Union(nvPermits.Local)
p.Remote.Union(nvPermits.Remote)
domainPermits[roleRef.domain] = p
Expand All @@ -1559,8 +1556,8 @@ func (d *kubernetes) rbacEvaluateUser(user k8sSubjectObjRef) {

domainRole, domainPermits = RemoveRedundant(allDomainRoles, domainPermits, api.FedRoleMaster) // assuming it's master cluster for now

oldDomainRole, _ := d.rbacCache[subj]
oldDomainPermits, _ := d.permitsRbacCache[subj]
oldDomainRole := d.rbacCache[subj]
oldDomainPermits := d.permitsRbacCache[subj]

// callback
if len(domainPermits) > 0 || len(domainRole) > 0 || len(oldDomainPermits) > 0 || len(oldDomainRole) > 0 { // only for reducing debug logs
Expand Down Expand Up @@ -1685,7 +1682,7 @@ func (d *kubernetes) ListUsers() []orchAPI.UserRBAC {
}
}
if len(domainPermits) > 0 {
if userRBAC, _ := allUsers[userRef]; rbac != nil {
if userRBAC := allUsers[userRef]; rbac != nil {
userRBAC.RBAC2 = domainPermits
} else {
allUsers[userRef] = &orchAPI.UserRBAC{Name: userRef.name, Domain: userRef.domain, RBAC2: domainPermits}
Expand Down Expand Up @@ -1952,8 +1949,6 @@ func GetNvCtrlerServiceAccount(objFunc common.CacheEventFunc) {
getNeuvectorSvcAccount()

log.WithFields(log.Fields{"nvControllerSA": ctrlerSubjectWanted}).Info()

return
}

func getSubjectsString(ns string, subjects []string) string {
Expand Down
4 changes: 2 additions & 2 deletions controller/resource/kubernetes_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -586,7 +586,7 @@ func (r *tRbacRancherSSO) verifyNvRolePermits(actualDomainRoles, expectDomainRol
actualDomainPerms, expectDomainPerms map[string]share.NvFedPermissions) {

for d, expectedRole := range expectDomainRoles {
if actualRole, _ := actualDomainRoles[d]; expectedRole != actualRole {
if actualRole := actualDomainRoles[d]; expectedRole != actualRole {
r.t.Logf("<< %s >>\n", r.caseName)
var dDisplay string
if d == "" {
Expand All @@ -600,7 +600,7 @@ func (r *tRbacRancherSSO) verifyNvRolePermits(actualDomainRoles, expectDomainRol
}
}
for d, expectedPermits := range expectDomainPerms {
if actualPermits, _ := actualDomainPerms[d]; expectedPermits != actualPermits {
if actualPermits := actualDomainPerms[d]; expectedPermits != actualPermits {
r.t.Logf("<< %s >>\n", r.caseName)
var dDisplay string
if d == "" {
Expand Down
6 changes: 1 addition & 5 deletions controller/rest/admission.go
Original file line number Diff line number Diff line change
Expand Up @@ -1123,9 +1123,7 @@ func handlerAddAdmissionRule(w http.ResponseWriter, r *http.Request, ps httprout
}
if ruleCfg.Criteria != nil {
resp.Rule.Criteria = make([]*api.RESTAdmRuleCriterion, len(ruleCfg.Criteria))
for idx, c := range ruleCfg.Criteria {
resp.Rule.Criteria[idx] = c
}
copy(resp.Rule.Criteria, ruleCfg.Criteria)
}

opa.ConvertToRegoRule(clusConf)
Expand Down Expand Up @@ -1702,8 +1700,6 @@ func handlerPromoteAdmissionRules(w http.ResponseWriter, r *http.Request, ps htt
}
}
restRespErrorMessage(w, http.StatusInternalServerError, api.RESTErrPromoteFail, errMsg)

return
}

func validateCustomPathCriteria(crt *share.CLUSAdmRuleCriterion) (bool, bool) {
Expand Down
2 changes: 1 addition & 1 deletion controller/rest/admwebhook.go
Original file line number Diff line number Diff line change
Expand Up @@ -1464,7 +1464,7 @@ func (whsvr *WebhookServer) serve(w http.ResponseWriter, r *http.Request) {

stamps.Start = time.Now()
whsvr.serveWithTimeStamps(w, r, &stamps)
diff := time.Now().Sub(stamps.Start)
diff := time.Since(stamps.Start)
if diff.Seconds() >= 28 {
log.WithFields(log.Fields{"image": stamps.Images, "seconds": diff.Seconds(),
"fetch": stamps.Fetched.Sub(stamps.GonnaFetch).Seconds()}).Warn("unexpected")
Expand Down
8 changes: 2 additions & 6 deletions controller/rest/bench.go
Original file line number Diff line number Diff line change
Expand Up @@ -123,9 +123,7 @@ func bench2REST(bench share.BenchType, item *share.CLUSBenchItem, cpf *complianc
}
}

for _, m := range item.Message {
r.Message = append(r.Message, m)
}
r.Message = append(r.Message, item.Message...)

if len(r.Message) > 0 {
allMessages := strings.Join(r.Message, ", ")
Expand Down Expand Up @@ -763,9 +761,7 @@ func getKubeCISReportFromCluster(id string, cpf *complianceProfileFilter, acc *a
if rpt1 == nil || len(rpt1.Items) == 0 {
return rpt2, 0, ""
} else {
for _, item := range rpt2.Items {
rpt1.Items = append(rpt1.Items, item)
}
rpt1.Items = append(rpt1.Items, rpt2.Items...)

return rpt1, 0, ""
}
Expand Down
16 changes: 4 additions & 12 deletions controller/rest/dlp_rule.go
Original file line number Diff line number Diff line change
Expand Up @@ -1432,9 +1432,7 @@ func parseDerivedDlpRules(dlpRuleMap map[string]*share.CLUSDerivedDlpRuleArray,
Wafrids: make([]uint32, 0),
RuleType: arr.RuleType,
}
for _, m := range arr.WlMacs {
wlDlpRule.DlpMacs = append(wlDlpRule.DlpMacs, m)
}
wlDlpRule.DlpMacs = append(wlDlpRule.DlpMacs, arr.WlMacs...)

for _, r := range arr.DlpRules {
wlDlpRule.DlpRules = append(wlDlpRule.DlpRules, derivedDlp2Rest(r))
Expand All @@ -1444,13 +1442,9 @@ func parseDerivedDlpRules(dlpRuleMap map[string]*share.CLUSDerivedDlpRuleArray,
wlDlpRule.WafRules = append(wlDlpRule.WafRules, derivedDlp2Rest(r))
}

for _, r := range arr.Rids {
wlDlpRule.Rids = append(wlDlpRule.Rids, r)
}
wlDlpRule.Rids = append(wlDlpRule.Rids, arr.Rids...)
wlDlpRule.Wafrids = append(wlDlpRule.Wafrids, arr.Wafrids...)

for _, r := range arr.Wafrids {
wlDlpRule.Wafrids = append(wlDlpRule.Wafrids, r)
}
wlrs = append(wlrs, &wlDlpRule)
}
return wlrs
Expand Down Expand Up @@ -1497,9 +1491,7 @@ func parseDerivedDlpRuleEntries(dlpRuleEntries []*share.CLUSDerivedDlpRuleEntry,
ID: dre.ID,
Patterns: make([]string, 0),
}
for _, p := range dre.Patterns {
dlpRuleEntry.Patterns = append(dlpRuleEntry.Patterns, p)
}
dlpRuleEntry.Patterns = append(dlpRuleEntry.Patterns, dre.Patterns...)

rdre[i] = dlpRuleEntry
}
Expand Down
2 changes: 1 addition & 1 deletion controller/rest/federation.go
Original file line number Diff line number Diff line change
Expand Up @@ -377,7 +377,7 @@ func isFedOpAllowed(expectedFedRole string, roleRequired RoleRquired, w http.Res

func isFedRulesCleanupOngoing(w http.ResponseWriter) bool {
if m := clusHelper.GetFedMembership(); m != nil && m.FedRole == api.FedRoleNone && m.PendingDismiss {
if diff := time.Now().Sub(m.PendingDismissAt); diff.Minutes() <= 5 {
if diff := time.Since(m.PendingDismissAt); diff.Minutes() <= 5 {
restRespErrorMessage(w, http.StatusBadRequest, api.RESTErrOpNotAllowed, "Federate rules cleanup is still ongoing. Please try again later.")
return true
}
Expand Down
8 changes: 2 additions & 6 deletions controller/rest/file_monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -260,9 +260,7 @@ func handlerFileMonitorConfig(w http.ResponseWriter, r *http.Request, ps httprou
// add rule
idx := utils.FilterIndexKey(flt.Path, flt.Regex)
capps := make([]string, len(filter.Apps))
for j, app := range filter.Apps {
capps[j] = app
}
copy(capps, filter.Apps)
frule := &share.CLUSFileAccessFilterRule{
Apps: capps,
CreatedAt: tm,
Expand All @@ -286,9 +284,7 @@ func handlerFileMonitorConfig(w http.ResponseWriter, r *http.Request, ps httprou
// update the rule
idx := utils.FilterIndexKey(cfilter.Path, cfilter.Regex)
capps := make([]string, len(filter.Apps))
for j, app := range filter.Apps {
capps[j] = app
}
copy(capps, filter.Apps)

frule := &share.CLUSFileAccessFilterRule{
Apps: capps,
Expand Down
3 changes: 1 addition & 2 deletions controller/rest/log.go
Original file line number Diff line number Diff line change
Expand Up @@ -323,8 +323,7 @@ func handlerViolationWorkloads(w http.ResponseWriter, r *http.Request, ps httpro
}
}

var violationMap map[string]*api.RESTViolationWorkload
violationMap = make(map[string]*api.RESTViolationWorkload)
violationMap := make(map[string]*api.RESTViolationWorkload)
for _, v := range violations {
var wlID, wlName, wlDomain string
if client {
Expand Down
11 changes: 4 additions & 7 deletions controller/rest/mock_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -86,10 +86,9 @@ func (m *mockCache) Group2CLUS(group *api.RESTGroup) *share.CLUSGroup {
PlatformRole: group.PlatformRole,
Criteria: make([]share.CLUSCriteriaEntry, len(group.Criteria)),
}
c.CfgType, _ = cfgTypeMapping[group.CfgType]
for i, d := range group.CreaterDomains {
c.CreaterDomains[i] = d
}
c.CfgType = cfgTypeMapping[group.CfgType]
copy(c.CreaterDomains, group.CreaterDomains)

for i, crt := range group.Criteria {
c.Criteria[i] = share.CLUSCriteriaEntry{
Key: crt.Key, Value: crt.Value, Op: crt.Op,
Expand Down Expand Up @@ -322,9 +321,7 @@ func (m *mockCache) Group2REST(group *share.CLUSGroup) *api.RESTGroup {
CreaterDomains: make([]string, len(group.CreaterDomains)),
},
}
for idx, cd := range group.CreaterDomains {
g.CreaterDomains[idx] = cd
}
copy(g.CreaterDomains, group.CreaterDomains)
g.CfgType, _ = cfgTypeMap2Api[group.CfgType]
return &g
}
Expand Down
2 changes: 0 additions & 2 deletions controller/rest/policy.go
Original file line number Diff line number Diff line change
Expand Up @@ -2279,6 +2279,4 @@ LOOP_ALL_IDS:
}
}
restRespErrorMessage(w, http.StatusInternalServerError, api.RESTErrPromoteFail, errMsg)

return
}
2 changes: 1 addition & 1 deletion controller/rest/registry.go
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ func parseWildcardRegex(s string) (string, error) {
}

func parseFilter(filters []string, regType string) ([]*share.CLUSRegistryFilter, error) {
if filters == nil || len(filters) == 0 {
if len(filters) == 0 {
return make([]*share.CLUSRegistryFilter, 0), nil
}

Expand Down
13 changes: 3 additions & 10 deletions controller/rest/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -482,7 +482,6 @@ func handlerGenerateSLORequest(w http.ResponseWriter, r *http.Request, ps httpro
log.WithField("url", url).Debug("SAML SLO request generated")
resp.Redirect = &api.RESTTokenAuthServerRedirect{Name: login.server, Type: api.ServerTypeSAML, RedirectURL: url}
restRespSuccess(w, r, &resp, nil, nil, nil, "")
return
}

func handlerTokenAuthServerList(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
Expand Down Expand Up @@ -723,9 +722,7 @@ func updateLDAPServer(cs *share.CLUSServer, ldap *api.RESTServerLDAPConfig, crea
var groupRoleMappings []*share.GroupRoleMapping
if ldap.GroupMappedRoles != nil {
copiedMappings := make([]*share.GroupRoleMapping, len(*ldap.GroupMappedRoles))
for idx, m := range *ldap.GroupMappedRoles {
copiedMappings[idx] = m
}
copy(copiedMappings, *ldap.GroupMappedRoles)
if groupRoleMappings, err = checkGroupRolesMapping(cldap.GroupMappedRoles, copiedMappings, acc); err == nil {
cldap.GroupMappedRoles = groupRoleMappings
}
Expand Down Expand Up @@ -851,9 +848,7 @@ func updateSAMLServer(cs *share.CLUSServer, saml *api.RESTServerSAMLConfig, acc
var groupRoleMappings []*share.GroupRoleMapping
if saml.GroupMappedRoles != nil {
copiedMappings := make([]*share.GroupRoleMapping, len(*saml.GroupMappedRoles))
for idx, m := range *saml.GroupMappedRoles {
copiedMappings[idx] = m
}
copy(copiedMappings, *saml.GroupMappedRoles)
if groupRoleMappings, err = checkGroupRolesMapping(csaml.GroupMappedRoles, copiedMappings, acc); err == nil {
csaml.GroupMappedRoles = groupRoleMappings
}
Expand Down Expand Up @@ -978,9 +973,7 @@ func updateOIDCServer(cs *share.CLUSServer, oidc *api.RESTServerOIDCConfig, acc
var groupRoleMappings []*share.GroupRoleMapping
if oidc.GroupMappedRoles != nil {
copiedMappings := make([]*share.GroupRoleMapping, len(*oidc.GroupMappedRoles))
for idx, m := range *oidc.GroupMappedRoles {
copiedMappings[idx] = m
}
copy(copiedMappings, *oidc.GroupMappedRoles)
if groupRoleMappings, err = checkGroupRolesMapping(coidc.GroupMappedRoles, copiedMappings, acc); err == nil {
coidc.GroupMappedRoles = groupRoleMappings
}
Expand Down
Loading

0 comments on commit 11c75d4

Please sign in to comment.