diff --git a/.github/workflows/linters.yaml b/.github/workflows/linters.yaml index 87494023..831352b6 100644 --- a/.github/workflows/linters.yaml +++ b/.github/workflows/linters.yaml @@ -26,5 +26,5 @@ jobs: - name: golangci-lint uses: golangci/golangci-lint-action@v3 with: - version: v1.53 + version: latest skip-cache: true diff --git a/.golangci.yaml b/.golangci.yaml index 56f53324..5e09bae4 100644 --- a/.golangci.yaml +++ b/.golangci.yaml @@ -4,6 +4,10 @@ run: tests: true skip-dirs-use-default: true modules-download-mode: readonly + skip-dirs: + - go/pkg # remove third party mod lib from scanning + - go/src # remove third party mod lib from scanning + - hostedtoolcache # remove the mod caches from scanning issues: max-issues-per-linter: 0 diff --git a/cmd/karavictl/cmd/api/api.go b/cmd/karavictl/cmd/api/api.go index ec762b30..b1ab20a7 100644 --- a/cmd/karavictl/cmd/api/api.go +++ b/cmd/karavictl/cmd/api/api.go @@ -85,10 +85,10 @@ type ClientOptions struct { // New returns a new API client. func New( - ctx context.Context, + _ context.Context, host string, - opts ClientOptions) (Client, error) { - + opts ClientOptions, +) (Client, error) { if host == "" { return nil, fmt.Errorf("host must not be empty") } @@ -102,10 +102,11 @@ func New( host: host, } - if opts.Insecure { + if opts.Insecure { // #nosec G402 c.http.Transport = &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, + MinVersion: tls.VersionTLS13, }, } } else { @@ -118,6 +119,7 @@ func New( TLSClientConfig: &tls.Config{ RootCAs: pool, InsecureSkipVerify: false, + MinVersion: tls.VersionTLS13, }, } } @@ -131,8 +133,8 @@ func (c *client) Get( path string, headers map[string]string, query url.Values, - resp interface{}) error { - + resp interface{}, +) error { return c.DoWithHeaders( ctx, http.MethodGet, path, headers, query, nil, resp) } @@ -143,8 +145,8 @@ func (c *client) Post( path string, headers map[string]string, query url.Values, - body, resp interface{}) error { - + body, resp interface{}, +) error { return c.DoWithHeaders( ctx, http.MethodPost, path, headers, query, body, resp) } @@ -155,8 +157,8 @@ func (c *client) Patch( path string, headers map[string]string, query url.Values, - body, resp interface{}) error { - + body, resp interface{}, +) error { return c.DoWithHeaders( ctx, http.MethodPatch, path, headers, query, body, resp) } @@ -167,8 +169,8 @@ func (c *client) Delete( path string, headers map[string]string, query url.Values, - body, resp interface{}) error { - + body, resp interface{}, +) error { return c.DoWithHeaders( ctx, http.MethodDelete, path, headers, query, body, resp) } @@ -187,8 +189,8 @@ func (c *client) DoWithHeaders( method, uri string, headers map[string]string, query url.Values, - body, resp interface{}) error { - + body, resp interface{}, +) error { res, err := c.DoAndGetResponseBody( ctx, method, uri, headers, query, body) if err != nil { @@ -217,8 +219,8 @@ func (c *client) DoAndGetResponseBody( method, uri string, headers map[string]string, query url.Values, - body interface{}) (*http.Response, error) { - + body interface{}, +) (*http.Response, error) { var ( err error req *http.Request diff --git a/cmd/karavictl/cmd/api/mocks/api.go b/cmd/karavictl/cmd/api/mocks/api.go index 59f68351..e319879a 100644 --- a/cmd/karavictl/cmd/api/mocks/api.go +++ b/cmd/karavictl/cmd/api/mocks/api.go @@ -40,7 +40,8 @@ func (f *FakeClient) Get(ctx context.Context, path string, headers map[string]string, query url.Values, - resp interface{}) error { + resp interface{}, +) error { if f.GetFn != nil { return f.GetFn(ctx, path, headers, query, resp) } @@ -53,7 +54,8 @@ func (f *FakeClient) Post( path string, headers map[string]string, query url.Values, - body, resp interface{}) error { + body, resp interface{}, +) error { if f.PostFn != nil { return f.PostFn(ctx, path, headers, query, body, resp) } @@ -66,7 +68,8 @@ func (f *FakeClient) Patch( path string, headers map[string]string, query url.Values, - body, resp interface{}) error { + body, resp interface{}, +) error { if f.PatchFn != nil { return f.PatchFn(ctx, path, headers, query, body, resp) } @@ -79,7 +82,8 @@ func (f *FakeClient) Delete( path string, headers map[string]string, query url.Values, - body, resp interface{}) error { + body, resp interface{}, +) error { if f.DeleteFn != nil { return f.DeleteFn(ctx, path, headers, query, body, resp) } diff --git a/cmd/karavictl/cmd/cluster_info.go b/cmd/karavictl/cmd/cluster_info.go index 48fef300..9ab4a6ac 100644 --- a/cmd/karavictl/cmd/cluster_info.go +++ b/cmd/karavictl/cmd/cluster_info.go @@ -33,15 +33,15 @@ func NewClusterInfoCmd() *cobra.Command { if v, _ := cmd.Flags().GetBool("watch"); v { cmdArgs = append(cmdArgs, "--watch") } - kCmd := exec.Command(K3sPath, cmdArgs...) - kCmd.Stdout = os.Stdout - err := kCmd.Start() + k3sCmd := exec.Command(K3sPath, cmdArgs...) + k3sCmd.Stdout = os.Stdout + err := k3sCmd.Start() if err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } - if err := kCmd.Wait(); err != nil { + if err := k3sCmd.Wait(); err != nil { fmt.Fprintf(os.Stderr, "error: %v\n", err) os.Exit(1) } diff --git a/cmd/karavictl/cmd/generate_admin_token.go b/cmd/karavictl/cmd/generate_admin_token.go index b9ac2735..acde4147 100644 --- a/cmd/karavictl/cmd/generate_admin_token.go +++ b/cmd/karavictl/cmd/generate_admin_token.go @@ -35,7 +35,6 @@ func NewAdminTokenCmd() *cobra.Command { Short: "Generate tokens for an admin.", Long: `Generates tokens for an admin.`, RunE: func(cmd *cobra.Command, args []string) error { - adminName, err := cmd.Flags().GetString("name") if err != nil { reportErrorAndExit(JSONOutput, cmd.ErrOrStderr(), err) diff --git a/cmd/karavictl/cmd/role.go b/cmd/karavictl/cmd/role.go index 35b58b49..28189917 100644 --- a/cmd/karavictl/cmd/role.go +++ b/cmd/karavictl/cmd/role.go @@ -97,7 +97,6 @@ func GetAuthorizedStorageSystems() (map[string]Storage, error) { "secret/karavi-storage-secret") b, err := k3sCmd.Output() - if err != nil { return nil, err } @@ -245,7 +244,7 @@ func validatePowerMaxStorageResourcePool(ctx context.Context, storageSystemDetai return nil } -func validatePowerScaleIsiPath(storageSystemDetails System, storageSystemID string, poolQuota PoolQuota) error { +func validatePowerScaleIsiPath(storageSystemDetails System, _ string, poolQuota PoolQuota) error { endpoint := GetPowerScaleEndpoint(storageSystemDetails) epURL, err := url.Parse(endpoint) if err != nil { @@ -368,7 +367,7 @@ func createRoleServiceClient(addr string, insecure bool) (pb.RoleServiceClient, var conn *grpc.ClientConn var err error - if insecure { + if insecure { // #nosec G402 conn, err = grpc.Dial(addr, grpc.WithTimeout(10*time.Second), grpc.WithContextDialer(func(_ context.Context, addr string) (net.Conn, error) { diff --git a/cmd/karavictl/cmd/role_create.go b/cmd/karavictl/cmd/role_create.go index d73c5323..ae19a9a7 100644 --- a/cmd/karavictl/cmd/role_create.go +++ b/cmd/karavictl/cmd/role_create.go @@ -112,7 +112,7 @@ func NewRoleCreateCmd() *cobra.Command { return roleCreateCmd } -func doRoleCreateRequest(ctx context.Context, addr string, insecure bool, role *roles.Instance, cmd *cobra.Command, adminTknBody token.AdminToken) error { +func doRoleCreateRequest(_ context.Context, addr string, insecure bool, role *roles.Instance, cmd *cobra.Command, adminTknBody token.AdminToken) error { client, err := CreateHTTPClient(fmt.Sprintf("https://%s", addr), insecure) if err != nil { reportErrorAndExit(JSONOutput, cmd.ErrOrStderr(), err) diff --git a/cmd/karavictl/cmd/role_get.go b/cmd/karavictl/cmd/role_get.go index 6900634e..f8b9178a 100644 --- a/cmd/karavictl/cmd/role_get.go +++ b/cmd/karavictl/cmd/role_get.go @@ -19,12 +19,11 @@ import ( "encoding/json" "errors" "fmt" - "net/http" - "net/url" - "karavi-authorization/internal/token" "karavi-authorization/internal/web" "karavi-authorization/pb" + "net/http" + "net/url" "github.com/spf13/cobra" ) diff --git a/cmd/karavictl/cmd/storage.go b/cmd/karavictl/cmd/storage.go index 4a780cf6..abe678f0 100644 --- a/cmd/karavictl/cmd/storage.go +++ b/cmd/karavictl/cmd/storage.go @@ -71,7 +71,7 @@ func createStorageServiceClient(addr string, insecure bool) (pb.StorageServiceCl var conn *grpc.ClientConn var err error - if insecure { + if insecure { // #nosec G402 conn, err = grpc.Dial(addr, grpc.WithTimeout(10*time.Second), grpc.WithContextDialer(func(_ context.Context, addr string) (net.Conn, error) { diff --git a/cmd/karavictl/cmd/storage_create.go b/cmd/karavictl/cmd/storage_create.go index a2bf317e..fca96cda 100644 --- a/cmd/karavictl/cmd/storage_create.go +++ b/cmd/karavictl/cmd/storage_create.go @@ -103,7 +103,7 @@ func NewStorageCreateCmd() *cobra.Command { } // Gather the inputs - var input = struct { + input := struct { Type string Endpoint string SystemID string diff --git a/cmd/karavictl/cmd/storage_delete.go b/cmd/karavictl/cmd/storage_delete.go index 9ea45de0..77b22112 100644 --- a/cmd/karavictl/cmd/storage_delete.go +++ b/cmd/karavictl/cmd/storage_delete.go @@ -51,7 +51,7 @@ func NewStorageDeleteCmd() *cobra.Command { } // Gather the inputs - var input = struct { + input := struct { Type string SystemID string }{ @@ -93,7 +93,6 @@ func NewStorageDeleteCmd() *cobra.Command { } func doStorageDeleteRequest(ctx context.Context, addr string, storageType string, systemID string, insecure bool, cmd *cobra.Command, adminTknBody token.AdminToken) error { - client, err := CreateHTTPClient(fmt.Sprintf("https://%s", addr), insecure) if err != nil { reportErrorAndExit(JSONOutput, cmd.ErrOrStderr(), err) diff --git a/cmd/karavictl/cmd/storage_get.go b/cmd/karavictl/cmd/storage_get.go index 5d320a11..4fdafe2b 100644 --- a/cmd/karavictl/cmd/storage_get.go +++ b/cmd/karavictl/cmd/storage_get.go @@ -119,7 +119,6 @@ func NewStorageGetCmd() *cobra.Command { } func doStorageGetRequest(ctx context.Context, addr string, storageType string, systemID string, insecure bool, cmd *cobra.Command, adminTknBody token.AdminToken) ([]byte, error) { - client, err := CreateHTTPClient(fmt.Sprintf("https://%s", addr), insecure) if err != nil { reportErrorAndExit(JSONOutput, cmd.ErrOrStderr(), err) diff --git a/cmd/karavictl/cmd/tenant.go b/cmd/karavictl/cmd/tenant.go index 6e0caeba..d40ec3a4 100644 --- a/cmd/karavictl/cmd/tenant.go +++ b/cmd/karavictl/cmd/tenant.go @@ -84,7 +84,8 @@ func reportErrorAndExit(er ErrorReporter, w io.Writer, err error) { func jsonOutput(w io.Writer, v interface{}) error { enc := json.NewEncoder(w) enc.SetIndent("", " ") - if err := enc.Encode(&v); err != nil { + err := enc.Encode(&v) + if err != nil { return err } return nil diff --git a/cmd/karavictl/cmd/tenant_list_test.go b/cmd/karavictl/cmd/tenant_list_test.go index 5748154f..b03ce920 100644 --- a/cmd/karavictl/cmd/tenant_list_test.go +++ b/cmd/karavictl/cmd/tenant_list_test.go @@ -122,7 +122,7 @@ func TestTenantList(t *testing.T) { var gotOutput bytes.Buffer rootCmd := NewRootCmd() - //tenantListCmd := NewTenantListCmd() + // tenantListCmd := NewTenantListCmd() rootCmd.SetErr(&gotOutput) rootCmd.SetArgs([]string{"tenant", "list", "--admin-token", "admin.yaml", "--addr", "proxy.com"}) diff --git a/cmd/proxy-server/main.go b/cmd/proxy-server/main.go index 9a2ab812..1e3c966e 100644 --- a/cmd/proxy-server/main.go +++ b/cmd/proxy-server/main.go @@ -34,7 +34,6 @@ import ( "karavi-authorization/internal/web" "karavi-authorization/pb" "net/http" - _ "net/http/pprof" "os" "os/signal" "path/filepath" @@ -79,7 +78,7 @@ var ( ) func init() { - http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // #nosec G402 } func main() { @@ -266,10 +265,6 @@ func run(log *logrus.Entry) error { } // Start debug service - // - // /debug/pprof - added to the default mux by importing the net/http/pprof package. - // /debug/vars - added to the default mux by importing the expvar package. - // log.Info("main: initializing debugging support") // Default prometheus metrics @@ -620,7 +615,7 @@ func rolesHandler(log *logrus.Entry, opaHost string) http.Handler { func volumesHandler(roleServ *roleClientService, storageServ *storageClientService, rdb *redis.Client, tm token.Manager, log *logrus.Entry) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { var sysID, sysType, storPool, tenant string - var volumeMap = make(map[string]map[string]string) + volumeMap := make(map[string]map[string]string) var volumeList []*pb.Volume var resp *pb.RoleListResponse keyTenantRevoked := "tenant:revoked" @@ -639,7 +634,7 @@ func volumesHandler(roleServ *roleClientService, storageServ *storageClientServi switch scheme { case "Bearer": var claims token.Claims - //check validity of token + // check validity of token _, err := tm.ParseWithClaims(tkn, JWTSigningSecret, &claims) if err != nil { log.WithError(err).Printf("error parsing token: %v", err) @@ -723,7 +718,7 @@ func volumesHandler(roleServ *roleClientService, storageServ *storageClientServi for volKey := range res { if strings.Contains(volKey, "capacity") { splitStr := strings.Split(volKey, ":") - //example : vol:k8s-cb89d36285:capacity + // example : vol:k8s-cb89d36285:capacity if len(splitStr) == 3 { volumeMap[sysID][splitStr[1]] = splitStr[1] } @@ -732,7 +727,7 @@ func volumesHandler(roleServ *roleClientService, storageServ *storageClientServi for volKey := range res { if strings.Contains(volKey, "deleted") { splitStr := strings.Split(volKey, ":") - //example : vol:k8s-cb89d36285:deleted + // example : vol:k8s-cb89d36285:deleted if len(splitStr) == 3 { delete(volumeMap[sysID], splitStr[1]) } diff --git a/cmd/proxy-server/main_test.go b/cmd/proxy-server/main_test.go index 33263468..59c31d92 100644 --- a/cmd/proxy-server/main_test.go +++ b/cmd/proxy-server/main_test.go @@ -135,6 +135,7 @@ func TestUpdateStorageSystems(t *testing.T) { }) } } + func TestVolumesHandler(t *testing.T) { ctx := context.Background() log := logrus.New().WithContext(ctx) @@ -164,7 +165,7 @@ func TestVolumesHandler(t *testing.T) { checkError(t, err) decAccTkn, err := base64.StdEncoding.DecodeString(tokenData.Data.Access) checkError(t, err) - //Create role + // Create role roleInstance, err := roles.NewInstance("CA-medium-0", "powerflex", "542a2d5f5122210f", "bronze", "9GB") checkError(t, err) @@ -199,10 +200,10 @@ func TestVolumesHandler(t *testing.T) { }, } - //create volume + // create volume rdb.HSetNX("quota:powerflex:542a2d5f5122210f:bronze:PancakeGroup-0:data", "vol:k8s-6aac50817e:capacity", 1) - //list volumes test + // list volumes test h := volumesHandler(&roleClientService{roleService: roleSvc}, &storageClientService{storageClient: storageClient}, rdb, jwx.NewTokenManager(jwx.HS256), log) w := httptest.NewRecorder() @@ -236,7 +237,7 @@ func TestVolumesHandler(t *testing.T) { } }, "Successful run of Multiple Roles": func(t *testing.T, ctx context.Context, rdb *redis.Client, log *logrus.Entry) { - //creates tenant and binds role by name + // creates tenant and binds role by name name := "PancakeGroup-1" createTenant(t, sut, tenantConfig{Name: name, Roles: "CA-medium-1,CA-large-1"}) @@ -255,7 +256,7 @@ func TestVolumesHandler(t *testing.T) { decAccTkn, err := base64.StdEncoding.DecodeString(tokenData.Data.Access) checkError(t, err) - //Create Roles + // Create Roles roleInstance, err := roles.NewInstance("CA-medium-1", "powerflex", "542a2d5f5122210f", "bronze", "9GB") roleInstanceTwo, err := roles.NewInstance("CA-large-1", "powerflex", "542a2d5f5122210f", "bronze", "20GB") checkError(t, err) @@ -294,10 +295,10 @@ func TestVolumesHandler(t *testing.T) { return &resp, nil }, } - //create volume + // create volume rdb.HSetNX("quota:powerflex:542a2d5f5122210f:bronze:PancakeGroup-1:data", "vol:k8s-6aac50817e:capacity", 1) - //list volumes test + // list volumes test h := volumesHandler(&roleClientService{roleService: rolesSvc}, &storageClientService{storageClient: storageClient}, rdb, jwx.NewTokenManager(jwx.HS256), log) w := httptest.NewRecorder() @@ -331,7 +332,7 @@ func TestVolumesHandler(t *testing.T) { } }, "Unsuccessfull run of HGET failing": func(t *testing.T, ctx context.Context, rdb *redis.Client, log *logrus.Entry) { - //creates tenant and binds role by name + // creates tenant and binds role by name name := "PancakeGroup-2" createTenant(t, sut, tenantConfig{Name: name, Roles: "CA-medium-2"}) @@ -349,7 +350,7 @@ func TestVolumesHandler(t *testing.T) { checkError(t, err) decAccTkn, err := base64.StdEncoding.DecodeString(tokenData.Data.Access) checkError(t, err) - //create No Roles + // create No Roles rff := roles.NewJSON() getRolesFn := func(ctx context.Context) (*roles.JSON, error) { @@ -379,10 +380,10 @@ func TestVolumesHandler(t *testing.T) { }, } - //create volume + // create volume rdb.HSetNX("quota:powerflex:542a2d5f5122210f:bronze:PancakeGroup-2:data", "vol:k8s-6aac50817e:capacity", 1) - //list volumes test + // list volumes test h := volumesHandler(&roleClientService{roleService: roleSvc}, &storageClientService{storageClient: storageClient}, rdb, jwx.NewTokenManager(jwx.HS256), log) w := httptest.NewRecorder() @@ -393,14 +394,14 @@ func TestVolumesHandler(t *testing.T) { h.ServeHTTP(w, r) - //check if endpoint returns internalErrorServer status + // check if endpoint returns internalErrorServer status if got := w.Result().StatusCode; got != http.StatusInternalServerError { t.Errorf("got %d, want %d", got, http.StatusInternalServerError) } return }, "Successfull run of multiple pools": func(t *testing.T, ctx context.Context, rdb *redis.Client, log *logrus.Entry) { - //creates tenant and binds role by name + // creates tenant and binds role by name name := "PancakeGroup-3" createTenant(t, sut, tenantConfig{Name: name, Roles: "CA-medium-3,CA-large-3"}) @@ -418,7 +419,7 @@ func TestVolumesHandler(t *testing.T) { checkError(t, err) decAccTkn, err := base64.StdEncoding.DecodeString(tokenData.Data.Access) checkError(t, err) - //create Roles + // create Roles roleInstance, err := roles.NewInstance("CA-medium-3", "powerflex", "542a2d5f5122210f", "bronze", "9GB") roleInstanceTwo, err := roles.NewInstance("CA-large-3", "powerflex", "542a2d5f5122210f", "steel", "20GB") checkError(t, err) @@ -458,11 +459,11 @@ func TestVolumesHandler(t *testing.T) { }, } - //create volume + // create volume rdb.HSetNX("quota:powerflex:542a2d5f5122210f:bronze:PancakeGroup-3:data", "vol:k8s-6aac50817e:capacity", 1) rdb.HSetNX("quota:powerflex:542a2d5f5122210f:steel:PancakeGroup-3:data", "vol:k8s-6aac50818e:capacity", 1) - //list volumes test + // list volumes test h := volumesHandler(&roleClientService{roleService: roleSvc}, &storageClientService{storageClient: storageClient}, rdb, jwx.NewTokenManager(jwx.HS256), log) w := httptest.NewRecorder() @@ -496,7 +497,7 @@ func TestVolumesHandler(t *testing.T) { } }, "Successfull run of deleted Role": func(t *testing.T, ctx context.Context, rdb *redis.Client, log *logrus.Entry) { - //creates tenant and binds role by name + // creates tenant and binds role by name name := "PancakeGroup-4" createTenant(t, sut, tenantConfig{Name: name, Roles: "CA-medium-4,CA-large-4"}) @@ -514,7 +515,7 @@ func TestVolumesHandler(t *testing.T) { checkError(t, err) decAccTkn, err := base64.StdEncoding.DecodeString(tokenData.Data.Access) checkError(t, err) - //create Roles + // create Roles roleInstance, err := roles.NewInstance("CA-medium-4", "powerflex", "542a2d5f5122210f", "bronze", "9GB") roleInstanceTwo, err := roles.NewInstance("CA-large-4", "powerflex", "542a2d5f5122210f", "bronze", "20GB") checkError(t, err) @@ -554,11 +555,11 @@ func TestVolumesHandler(t *testing.T) { }, } - //create volume + // create volume rdb.HSetNX("quota:powerflex:542a2d5f5122210f:bronze:PancakeGroup-4:data", "vol:k8s-6aac50817e:capacity", 1) rdb.HSetNX("quota:powerflex:542a2d5f5122210f:bronze:PancakeGroup-4:data", "vol:k8s-6aac50818e:deleted", 1) - //list volumes test + // list volumes test h := volumesHandler(&roleClientService{roleService: roleSvc}, &storageClientService{storageClient: storageClient}, rdb, jwx.NewTokenManager(jwx.HS256), log) w := httptest.NewRecorder() @@ -599,7 +600,6 @@ func TestVolumesHandler(t *testing.T) { tc(t, ctx, rdb, log) }) } - } func checkError(t *testing.T, err error) { @@ -713,12 +713,12 @@ func (k fakeStorageKube) GetConfiguredStorage(ctx context.Context) (cmd.Storage, type successfulRoleValidator struct{} -func (v successfulRoleValidator) Validate(ctx context.Context, role *roles.Instance) error { +func (v successfulRoleValidator) Validate(_ context.Context, _ *roles.Instance) error { return nil } type successfulStorageValidator struct{} -func (v successfulStorageValidator) Validate(ctx context.Context, systemID string, systemType string, system cmd.System) error { +func (v successfulStorageValidator) Validate(_ context.Context, _ string, _ string, _ cmd.System) error { return nil } diff --git a/cmd/role-service/main.go b/cmd/role-service/main.go index 17d6ecd0..83091104 100644 --- a/cmd/role-service/main.go +++ b/cmd/role-service/main.go @@ -49,9 +49,7 @@ const ( logFormat = "LOG_FORMAT" ) -var ( - cfg Config -) +var cfg Config // Config is the configuration details on the role-service type Config struct { diff --git a/cmd/sidecar-proxy/main.go b/cmd/sidecar-proxy/main.go index e0b7e884..24d71cf8 100644 --- a/cmd/sidecar-proxy/main.go +++ b/cmd/sidecar-proxy/main.go @@ -108,7 +108,7 @@ func (pi *ProxyInstance) Start(proxyHost, access, refresh string) error { Host: proxyHost, } pi.rp = httputil.NewSingleHostReverseProxy(&proxyURL) - if insecureProxy { + if insecureProxy { // #nosec G402 pi.rp.Transport = &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, @@ -124,6 +124,7 @@ func (pi *ProxyInstance) Start(proxyHost, access, refresh string) error { TLSClientConfig: &tls.Config{ RootCAs: pool, InsecureSkipVerify: false, + MinVersion: tls.VersionTLS13, }, } } @@ -270,7 +271,7 @@ func run(log *logrus.Entry) error { } tlsConfig := &tls.Config{ Certificates: []tls.Certificate{tlsCert}, - InsecureSkipVerify: true, + InsecureSkipVerify: true, // #nosec G402 } var proxyInstances []*ProxyInstance @@ -338,7 +339,7 @@ func refreshTokens(proxyHost url.URL, refreshToken string, accessToken *string, return err } httpClient := &http.Client{} - if insecureProxy { + if insecureProxy { // #nosec G402 httpClient.Transport = &http.Transport{ TLSClientConfig: &tls.Config{ InsecureSkipVerify: true, @@ -353,6 +354,7 @@ func refreshTokens(proxyHost url.URL, refreshToken string, accessToken *string, TLSClientConfig: &tls.Config{ RootCAs: pool, InsecureSkipVerify: false, + MinVersion: tls.VersionTLS13, }, } } diff --git a/cmd/storage-service/main.go b/cmd/storage-service/main.go index 054caabb..c1d40e02 100644 --- a/cmd/storage-service/main.go +++ b/cmd/storage-service/main.go @@ -52,9 +52,7 @@ const ( concurrentPowerFlexRequests = "CONCURRENT_POWERFLEX_REQUESTS" ) -var ( - cfg Config -) +var cfg Config // Config is the configuration details on the storage-service type Config struct { @@ -70,7 +68,7 @@ func main() { // define the logger log := logrus.NewEntry(logrus.New()) - //declare Config values + // declare Config values cfgViper := viper.New() cfgViper.SetConfigName("config") cfgViper.AddConfigPath(".") diff --git a/cmd/tenant-service/main.go b/cmd/tenant-service/main.go index 58e926d1..219288fe 100644 --- a/cmd/tenant-service/main.go +++ b/cmd/tenant-service/main.go @@ -49,9 +49,7 @@ const ( logFormat = "LOG_FORMAT" ) -var ( - cfg Config -) +var cfg Config // Config is the configuration details on the tenant-service type Config struct { diff --git a/deploy/install.go b/deploy/install.go index 4fded893..69aa7185 100644 --- a/deploy/install.go +++ b/deploy/install.go @@ -308,7 +308,6 @@ func (dp *DeployProcess) CopySidecarProxyToCwd() { return nil }) - if err != nil { dp.Err = fmt.Errorf("finding sidecar file: %w", err) return @@ -409,7 +408,7 @@ loop: return } - f, err := os.OpenFile(filepath.Clean(target), os.O_CREATE|os.O_RDWR, os.FileMode(0755)) + f, err := os.OpenFile(filepath.Clean(target), os.O_CREATE|os.O_RDWR, os.FileMode(0o755)) if err != nil { dp.Err = fmt.Errorf("creating file %q: %w", target, err) return @@ -421,7 +420,8 @@ loop: } if err := f.Close(); err != nil { - // ignore + dp.Err = fmt.Errorf("closing file %q: %w", target, err) + return } } } @@ -444,7 +444,7 @@ func (dp *DeployProcess) InstallKaravictl() { dp.Err = fmt.Errorf("installing karavictl: %w", err) return } - if err := osChmod(tgtPath, 0755); err != nil { + if err := osChmod(tgtPath, 0o755); err != nil { dp.Err = fmt.Errorf("chmod karavictl: %w", err) return } @@ -511,12 +511,12 @@ func (dp *DeployProcess) InstallK3s() { return } - if err := osChmod(tmpPath, 0755); err != nil { + if err := osChmod(tmpPath, 0o755); err != nil { dp.Err = fmt.Errorf("chmod %s: %w", tmpPath, err) return } - if err := osChmod(tgtPath, 0755); err != nil { + if err := osChmod(tgtPath, 0o755); err != nil { dp.Err = fmt.Errorf("chmod %s: %w", tgtPath, err) return } @@ -597,7 +597,7 @@ func (dp *DeployProcess) WriteConfigSecretManifest() { } fname := filepath.Join(RancherManifestsDir, "karavi-config-secret.yaml") - f, err := osOpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0341) + f, err := osOpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o341) if err != nil { dp.Err = fmt.Errorf("creating %s: %w", fname, err) return @@ -623,11 +623,11 @@ func (dp *DeployProcess) WriteStorageSecretManifest() { return } - //check if a secret already exists from previous install + // check if a secret already exists from previous install cmd := execCommand("/usr/local/bin/k3s", "kubectl", "get", "secret", "karavi-storage-secret", "-n", "karavi", "-o", "json") err := cmd.Run() if err == nil { - //skip creating the secret + // skip creating the secret return } @@ -655,7 +655,7 @@ func (dp *DeployProcess) WriteStorageSecretManifest() { } fname := filepath.Join(RancherManifestsDir, "karavi-storage-secret.yaml") - f, err := osOpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0341) + f, err := osOpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o341) if err != nil { dp.Err = fmt.Errorf("creating %s: %w", fname, err) return @@ -672,7 +672,6 @@ func (dp *DeployProcess) WriteStorageSecretManifest() { dp.Err = fmt.Errorf("writing secret: %w", err) return } - } // WriteConfigMapManifest generates and writes the Kubernetes @@ -738,7 +737,7 @@ func (dp *DeployProcess) WriteConfigMapManifest() { } fname := filepath.Join(RancherManifestsDir, "csm-config-params.yaml") - f, err := osOpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0341) + f, err := osOpenFile(fname, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o341) if err != nil { dp.Err = fmt.Errorf("creating %s: %w", fname, err) return @@ -781,7 +780,7 @@ func (dp *DeployProcess) ExecuteK3sInstallScript() { defer fmt.Fprintln(dp.stdout, "Done!") tmpPath := filepath.Join(dp.tmpDir, k3SInstallScript) - if err := osChmod(tmpPath, 0755); err != nil { + if err := osChmod(tmpPath, 0o755); err != nil { dp.Err = fmt.Errorf("chmod %s: %w", k3SInstallScript, err) return } @@ -819,7 +818,7 @@ func realCreateDir(newDir string) error { // TODO(alik): Do we need to check these errors? // if dir is not exist create it if _, err := os.Stat(filepath.Clean(newDir)); err != nil { - if err := os.MkdirAll(newDir, 0750); err != nil { + if err := os.MkdirAll(newDir, 0o750); err != nil { return err } } @@ -834,7 +833,7 @@ func (dp *DeployProcess) AddCertificate() { } if !dp.cfg.IsSet("certificate") { - //no certificate found, create self-signed certificate + // no certificate found, create self-signed certificate dp.manifests = append(dp.manifests, selfSignedCertManifest) return } @@ -867,7 +866,7 @@ func (dp *DeployProcess) AddCertificate() { } fmt.Fprintf(dp.stdout, "Provided Crtfile %s, KeyFile %s\n", crtFile, keyFile) - //replace cert info in manifest file + // replace cert info in manifest file certFile := filepath.Join(dp.tmpDir, certConfigManifest) read, err := ioutilReadFile(certFile) @@ -885,7 +884,6 @@ func (dp *DeployProcess) AddCertificate() { return } dp.manifests = append(dp.manifests, certConfigManifest) - } // AddHostName replaces the ingress hostname in the manifest @@ -901,7 +899,7 @@ func (dp *DeployProcess) AddHostName() { hostName := dp.cfg.GetString("hostname") - //update hostnames in ingress manifest + // update hostnames in ingress manifest ingressFile := filepath.Join(dp.tmpDir, authIngressManifest) read, err := ioutilReadFile(ingressFile) diff --git a/deploy/install_test.go b/deploy/install_test.go index 20fe1c3b..4b686bf4 100644 --- a/deploy/install_test.go +++ b/deploy/install_test.go @@ -21,6 +21,7 @@ import ( "fmt" "io" "io/fs" + "io/ioutil" "os" "os/exec" "path/filepath" @@ -45,7 +46,6 @@ func TestRun(t *testing.T) { dp.Steps = append(dp.Steps, func() {}) err := run(dp) - if err != nil { t.Fatal(err) } @@ -97,7 +97,7 @@ func TestDeployProcess_CheckRootPermissions(t *testing.T) { osGeteuid = func() int { return 0 // pretend to be effectively root. } - var tests = []struct { + tests := []struct { name string givenSudoUID string givenSudoGID string @@ -611,7 +611,7 @@ func TestDeployProcess_CreateRancherDirs(t *testing.T) { var testOut, testErr bytes.Buffer sut := buildDeployProcess(&testOut, &testErr) - var tests = []struct { + tests := []struct { name string givenErr error wantCallCount int @@ -805,7 +805,8 @@ func TestDeployProcess_InstallK3s(t *testing.T) { } osOpenFile = func(name string, flag int, perm os.FileMode) (*os.File, error) { var err error - openedFile, err = os.Create(filepath.Join(os.TempDir(), filepath.Base(name))) + // openedFile, err = os.Create(filepath.Join(os.TempDir(), filepath.Base(name))) + openedFile, err = ioutil.TempFile(os.TempDir(), "") if err != nil { t.Fatal(err) } @@ -871,7 +872,8 @@ func TestDeployProcess_InstallK3s(t *testing.T) { osOpenFile = func(name string, flag int, perm os.FileMode) (*os.File, error) { var err error - openedFile, err = os.Create(filepath.Join(os.TempDir(), filepath.Base(name))) + // openedFile, err = os.Create(filepath.Join(os.TempDir(), filepath.Base(name))) + openedFile, err = ioutil.TempFile(os.TempDir(), "") if err != nil { t.Fatal(err) } @@ -1063,7 +1065,7 @@ func TestDeployProcess_WriteConfigSecretManifest(t *testing.T) { var configPath string osOpenFile = func(path string, _ int, _ os.FileMode) (*os.File, error) { configPath = filepath.Join(tmpDir, path) - if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil { t.Fatal(err) } return os.Create(configPath) @@ -1174,7 +1176,7 @@ func TestDeployProcess_WriteStorageSecretManifest(t *testing.T) { t.Run("it writes config to a storage secret manifest", func(t *testing.T) { defer afterEach() execCommand = func(_ string, _ ...string) *exec.Cmd { - return exec.Command("false") //return a failure + return exec.Command("false") // return a failure } tmpDir, err := os.MkdirTemp("", "WriteStorageSecretManifest") if err != nil { @@ -1184,7 +1186,7 @@ func TestDeployProcess_WriteStorageSecretManifest(t *testing.T) { var configPath string osOpenFile = func(path string, _ int, _ os.FileMode) (*os.File, error) { configPath = filepath.Join(tmpDir, path) - if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil { t.Fatal(err) } return os.Create(configPath) @@ -1210,7 +1212,7 @@ func TestDeployProcess_WriteStorageSecretManifest(t *testing.T) { t.Run("it handles file creation failure", func(t *testing.T) { defer afterEach() execCommand = func(_ string, _ ...string) *exec.Cmd { - return exec.Command("false") //return a failure + return exec.Command("false") // return a failure } wantErr := errors.New("test error") osOpenFile = func(_ string, _ int, _ os.FileMode) (*os.File, error) { @@ -1227,7 +1229,7 @@ func TestDeployProcess_WriteStorageSecretManifest(t *testing.T) { t.Run("it handles file writing failure", func(t *testing.T) { defer afterEach() execCommand = func(_ string, _ ...string) *exec.Cmd { - return exec.Command("false") //return a failure + return exec.Command("false") // return a failure } osOpenFile = func(_ string, _ int, _ os.FileMode) (*os.File, error) { // Return a nil file to force #Write to return an error. @@ -1244,7 +1246,7 @@ func TestDeployProcess_WriteStorageSecretManifest(t *testing.T) { t.Run("it handles secret marshal failure", func(t *testing.T) { defer afterEach() execCommand = func(_ string, _ ...string) *exec.Cmd { - return exec.Command("false") //return a failure + return exec.Command("false") // return a failure } wantErr := errors.New("test error") yamlMarshalSecret = func(_ *corev1.Secret) ([]byte, error) { @@ -1314,7 +1316,7 @@ func TestDeployProcess_WriteConfigMapManifest(t *testing.T) { var configPath string osOpenFile = func(path string, _ int, _ os.FileMode) (*os.File, error) { configPath = filepath.Join(tmpDir, path) - if err := os.MkdirAll(filepath.Dir(configPath), 0755); err != nil { + if err := os.MkdirAll(filepath.Dir(configPath), 0o755); err != nil { t.Fatal(err) } return os.Create(configPath) @@ -1491,7 +1493,6 @@ func TestDeployProcess_PrintFinishedMessage(t *testing.T) { if got := len(testOut.Bytes()); got != want { t.Errorf("len(stdout): got = %d, want %d", got, want) } - }) t.Run("it prints the finished message", func(t *testing.T) { t.Cleanup(func() { @@ -1504,7 +1505,6 @@ func TestDeployProcess_PrintFinishedMessage(t *testing.T) { if got := len(testOut.Bytes()); got != want { t.Errorf("len(stdout): got = %d, want %d", got, want) } - }) } @@ -1566,7 +1566,6 @@ func TestDeployProcess_AddCertificate(t *testing.T) { if got := len(testOut.Bytes()); got != want { t.Errorf("len(stdout): got = %d, want %d", got, want) } - }) t.Run("no certificate info in config file", func(t *testing.T) { t.Cleanup(func() { @@ -1580,7 +1579,6 @@ func TestDeployProcess_AddCertificate(t *testing.T) { if got := sut.manifests; got == nil { t.Errorf("manifests: got = %s, want not nil", got) } - }) t.Run("certificate files not listed", func(t *testing.T) { t.Cleanup(func() { @@ -1593,7 +1591,6 @@ func TestDeployProcess_AddCertificate(t *testing.T) { if got := sut.Err; got == nil { t.Errorf("Error: got = %s, want not nil", got) } - }) t.Run("certificate file type unknown", func(t *testing.T) { t.Cleanup(func() { @@ -1677,7 +1674,6 @@ func TestDeployProcess_AddHostName(t *testing.T) { if got := len(testOut.Bytes()); got != want { t.Errorf("len(stdout): got = %d, want %d", got, want) } - }) t.Run("missing hostName configuration", func(t *testing.T) { t.Cleanup(func() { @@ -1689,7 +1685,6 @@ func TestDeployProcess_AddHostName(t *testing.T) { if got := sut.Err; got == nil { t.Errorf("Error: got = %s, want not nil", got) } - }) t.Run("ingress file read error", func(t *testing.T) { t.Cleanup(func() { diff --git a/internal/k8s/api.go b/internal/k8s/api.go index c7451669..759b8718 100644 --- a/internal/k8s/api.go +++ b/internal/k8s/api.go @@ -248,7 +248,6 @@ func (api *API) UpdateStorages(ctx context.Context, storages cmd.Storage) error } func (api *API) getStorageSecret(storages storage.Storage) (*clientv1.SecretApplyConfiguration, error) { - var data map[string]storage.Storage = make(map[string]storage.Storage) data["storage"] = storages diff --git a/internal/k8s/api_test.go b/internal/k8s/api_test.go index 9ccf69f5..f939d10b 100644 --- a/internal/k8s/api_test.go +++ b/internal/k8s/api_test.go @@ -30,8 +30,10 @@ import ( "k8s.io/client-go/rest" ) -type connectFn func(*API) error -type configFn func() (*rest.Config, error) +type ( + connectFn func(*API) error + configFn func() (*rest.Config, error) +) func TestGetConfiguredRoles(t *testing.T) { // define check functions to pass or fail tests @@ -150,7 +152,6 @@ roles = { checkFn(t, roles, err) }) } - } func TestUpdateRoles(t *testing.T) { @@ -365,8 +366,8 @@ func testGetApplyConfig(t *testing.T) { checkExpectedOutput := func(want string) func(*testing.T, string, error) { return func(t *testing.T, got string, err error) { // remove spacing issues by removing white space and new line characters - //want := strings.ReplaceAll(strings.ReplaceAll(expected, "\n", ""), " ", "") - //got := strings.ReplaceAll(strings.ReplaceAll(result, "\n", ""), " ", "") + // want := strings.ReplaceAll(strings.ReplaceAll(expected, "\n", ""), " ", "") + // got := strings.ReplaceAll(strings.ReplaceAll(result, "\n", ""), " ", "") if want != got { t.Errorf("want %s, got %s", want, got) @@ -439,7 +440,6 @@ func testGetStorageSecret(t *testing.T) { tests := map[string]func(t *testing.T) (storage.Storage, checkFn){ "success": func(*testing.T) (storage.Storage, checkFn) { - storage := storage.Storage{ "powerflex": storage.SystemType{ "542a2d5f5122210f": storage.System{ @@ -450,8 +450,7 @@ func testGetStorageSecret(t *testing.T) { }, }, } - want := - `storage: + want := `storage: powerflex: 542a2d5f5122210f: Endpoint: 0.0.0.0:443 diff --git a/internal/powerflex/storage_pool_cache_test.go b/internal/powerflex/storage_pool_cache_test.go index 2c69e5b2..4b2d4b9b 100644 --- a/internal/powerflex/storage_pool_cache_test.go +++ b/internal/powerflex/storage_pool_cache_test.go @@ -27,10 +27,6 @@ import ( "golang.org/x/sync/errgroup" ) -var ( - token = "YWRtaW46MTYxMDUxNzk5NDQxODpjYzBkMGEwMmUwYzNiODUxOTM1NWMxZThkNTcwZWEwNA" -) - func TestStoragePoolCache_GetStoragePoolNameByID(t *testing.T) { t.Run("success getting a storage pool not in cache", func(t *testing.T) { // Arrange @@ -115,7 +111,6 @@ func TestStoragePoolCache_GetStoragePoolNameByID(t *testing.T) { default: t.Fatalf("path %s not supported", r.URL.String()) } - }) defer powerFlexSvr.Close() @@ -176,7 +171,6 @@ func TestStoragePoolCache_GetStoragePoolNameByID(t *testing.T) { default: t.Fatalf("path %s not supported", r.URL.String()) } - }) defer powerFlexSvr.Close() @@ -229,7 +223,6 @@ func TestStoragePoolCache_GetStoragePoolNameByID(t *testing.T) { default: t.Fatalf("path %s not supported", r.URL.String()) } - }) defer powerFlexSvr.Close() @@ -263,7 +256,6 @@ func TestStoragePoolCache_GetStoragePoolNameByID(t *testing.T) { default: t.Fatalf("path %s not supported", r.URL.String()) } - }) defer powerFlexSvr.Close() @@ -301,7 +293,6 @@ func TestStoragePoolCache_GetStoragePoolNameByID(t *testing.T) { default: t.Fatalf("path %s not supported", r.URL.String()) } - }) defer powerFlexSvr.Close() @@ -373,7 +364,7 @@ func newPowerFlexClient(t *testing.T, addr string) *goscaleio.Client { return client } -func newTokenGetter(t *testing.T, client *goscaleio.Client, addr string) *powerflex.TokenGetter { +func newTokenGetter(_ *testing.T, client *goscaleio.Client, addr string) *powerflex.TokenGetter { return powerflex.NewTokenGetter(powerflex.Config{ PowerFlexClient: client, TokenRefreshInterval: 5 * time.Minute, diff --git a/internal/powerflex/token_getter.go b/internal/powerflex/token_getter.go index a7980f90..e74d2f0e 100644 --- a/internal/powerflex/token_getter.go +++ b/internal/powerflex/token_getter.go @@ -15,11 +15,10 @@ package powerflex import ( + "context" "sync" "time" - "context" - "github.com/dell/goscaleio" "github.com/sirupsen/logrus" "go.opentelemetry.io/otel/trace" diff --git a/internal/powerflex/token_getter_test.go b/internal/powerflex/token_getter_test.go index 8e7b0250..d31fad67 100644 --- a/internal/powerflex/token_getter_test.go +++ b/internal/powerflex/token_getter_test.go @@ -17,6 +17,7 @@ package powerflex_test import ( "context" "fmt" + "io/ioutil" "karavi-authorization/internal/powerflex" "net/http" "net/http/httptest" @@ -25,15 +26,21 @@ import ( "github.com/dell/goscaleio" "github.com/sirupsen/logrus" -) - -var ( - firstToken = "YWRtaW46MTYxMDUxNzk5NDQxODpjYzBkMGEwMmUwYzNiODUxOTM1NWMxZThkNTcwZWEwNA" - secondToken = "YWRtaW46MTYxMDU3OTI1NjMyMjo2MGFiNTIyYTcxYjEwMGM3ZTdlYzRhMDU3MDA1MjNhMw" + "gopkg.in/yaml.v2" ) func TestLogin_GetToken(t *testing.T) { t.Run("success getting a token", func(t *testing.T) { + tokens := make(map[string]interface{}) + credFile, err := ioutil.ReadFile("../../tokens.yaml") + if err != nil { + t.Errorf("unable to read token: %v", err) + } + err = yaml.Unmarshal(credFile, &tokens) + if err != nil { + t.Errorf("unable to unmarshal token: %v", err) + } + firstToken := tokens["firstToken"].(string) // Arrange // Ready channel to know when tokengetter is ready @@ -91,6 +98,17 @@ func TestLogin_GetToken(t *testing.T) { }) t.Run("success getting a token during refresh", func(t *testing.T) { + tokens := make(map[string]interface{}) + credFile, err := ioutil.ReadFile("../../tokens.yaml") + if err != nil { + t.Errorf("unable to read token: %v", err) + } + err = yaml.Unmarshal(credFile, &tokens) + if err != nil { + t.Errorf("unable to unmarshal token: %v", err) + } + firstToken := tokens["firstToken"].(string) + secondToken := tokens["secondToken"].(string) // Arrange // Ready channel to know when tokengetter is ready @@ -163,6 +181,16 @@ func TestLogin_GetToken(t *testing.T) { }) t.Run("timeout getting a token during refresh", func(t *testing.T) { + tokens := make(map[string]interface{}) + credFile, err := ioutil.ReadFile("../../tokens.yaml") + if err != nil { + t.Errorf("unable to read token: %v", err) + } + err = yaml.Unmarshal(credFile, &tokens) + if err != nil { + t.Errorf("unable to unmarshal token: %v", err) + } + firstToken := tokens["firstToken"].(string) // Arrange // Ready channel to know when tokengetter is ready diff --git a/internal/proxy/dispatch_handler_test.go b/internal/proxy/dispatch_handler_test.go index 65920e9b..161602f0 100644 --- a/internal/proxy/dispatch_handler_test.go +++ b/internal/proxy/dispatch_handler_test.go @@ -53,7 +53,7 @@ func testEmptyDispatchHandler(t *testing.T) { w := httptest.NewRecorder() r, err := http.NewRequestWithContext(ctx, http.MethodGet, "/", nil) checkError(t, err) - //r.Header.Set("x-csi-plugin-identifier", "omitted-or-blank") + // r.Header.Set("x-csi-plugin-identifier", "omitted-or-blank") h.ServeHTTP(w, r) t.Log("Then I should get back an 502 response") @@ -125,6 +125,6 @@ func testForwardedHeaders(t *testing.T) { } } -func buildSystemRegistry(t *testing.T) map[string]http.Handler { +func buildSystemRegistry(_ *testing.T) map[string]http.Handler { return map[string]http.Handler{} } diff --git a/internal/proxy/powerflex_handler.go b/internal/proxy/powerflex_handler.go index 40d3ce3a..6c95b45c 100644 --- a/internal/proxy/powerflex_handler.go +++ b/internal/proxy/powerflex_handler.go @@ -313,7 +313,7 @@ func (s *System) volumeCreateHandler(next http.Handler, enf *quota.RedisEnforcem pvName := r.Header.Get(HeaderPVName) // Update metrics counter for volumes requested. - //volReqCount.Add(pvName, 1) + // volReqCount.Add(pvName, 1) // Ask OPA to make a decision var requestBody map[string]json.RawMessage diff --git a/internal/proxy/powerflex_handler_test.go b/internal/proxy/powerflex_handler_test.go index 48716f87..fcb38166 100644 --- a/internal/proxy/powerflex_handler_test.go +++ b/internal/proxy/powerflex_handler_test.go @@ -42,7 +42,7 @@ import ( ) func init() { - http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} + http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: true} // #nosec G402 } func TestPowerFlex(t *testing.T) { @@ -328,7 +328,7 @@ func TestPowerFlex(t *testing.T) { // PowerFlex itself. type DeleteRequestResponse struct { ErrorCode int `json:"errorCode"` - HttpStatusCode int `json:"httpStatusCode"` + HTTPStatusCode int `json:"httpStatusCode"` Message string `json:"message"` } got := DeleteRequestResponse{} @@ -338,10 +338,10 @@ func TestPowerFlex(t *testing.T) { } want := DeleteRequestResponse{ ErrorCode: 403, - HttpStatusCode: 403, + HTTPStatusCode: 403, Message: "request denied", } - if !strings.Contains(got.Message, want.Message) || got.ErrorCode != want.ErrorCode || got.HttpStatusCode != want.HttpStatusCode { + if !strings.Contains(got.Message, want.Message) || got.ErrorCode != want.ErrorCode || got.HTTPStatusCode != want.HTTPStatusCode { t.Errorf("got %q, expected response body to contain %q", got, want) } }) @@ -515,7 +515,7 @@ func TestPowerFlex(t *testing.T) { // PowerFlex itself. type MapRequestResponse struct { ErrorCode int `json:"errorCode"` - HttpStatusCode int `json:"httpStatusCode"` + HTTPStatusCode int `json:"httpStatusCode"` Message string `json:"message"` } got := MapRequestResponse{} @@ -525,10 +525,10 @@ func TestPowerFlex(t *testing.T) { } want := MapRequestResponse{ ErrorCode: 403, - HttpStatusCode: 403, + HTTPStatusCode: 403, Message: "map denied", } - if !strings.Contains(got.Message, want.Message) || got.ErrorCode != want.ErrorCode || got.HttpStatusCode != want.HttpStatusCode { + if !strings.Contains(got.Message, want.Message) || got.ErrorCode != want.ErrorCode || got.HTTPStatusCode != want.HTTPStatusCode { t.Errorf("got %q, expected response body to contain %q", got, want) } }) @@ -731,7 +731,7 @@ func TestPowerFlex(t *testing.T) { // PowerFlex itself. type UnmapRequestResponse struct { ErrorCode int `json:"errorCode"` - HttpStatusCode int `json:"httpStatusCode"` + HTTPStatusCode int `json:"httpStatusCode"` Message string `json:"message"` } got := UnmapRequestResponse{} @@ -741,10 +741,10 @@ func TestPowerFlex(t *testing.T) { } want := UnmapRequestResponse{ ErrorCode: 403, - HttpStatusCode: 403, + HTTPStatusCode: 403, Message: "unmap denied", } - if !strings.Contains(got.Message, want.Message) || got.ErrorCode != want.ErrorCode || got.HttpStatusCode != want.HttpStatusCode { + if !strings.Contains(got.Message, want.Message) || got.ErrorCode != want.ErrorCode || got.HTTPStatusCode != want.HTTPStatusCode { t.Errorf("got %q, expected response body to contain %q", got, want) } }) @@ -1291,7 +1291,7 @@ func TestPowerFlex(t *testing.T) { // PowerFlex itself. type ApprovesdcRequestResponse struct { ErrorCode int `json:"errorCode"` - HttpStatusCode int `json:"httpStatusCode"` + HTTPStatusCode int `json:"httpStatusCode"` Message string `json:"message"` } got := ApprovesdcRequestResponse{} @@ -1301,10 +1301,10 @@ func TestPowerFlex(t *testing.T) { } want := ApprovesdcRequestResponse{ ErrorCode: 403, - HttpStatusCode: 403, + HTTPStatusCode: 403, Message: "sdc approve request denied", } - if !strings.Contains(got.Message, want.Message) || got.ErrorCode != want.ErrorCode || got.HttpStatusCode != want.HttpStatusCode { + if !strings.Contains(got.Message, want.Message) || got.ErrorCode != want.ErrorCode || got.HTTPStatusCode != want.HTTPStatusCode { t.Errorf("got %q, expected response body to contain %q", got, want) } }) diff --git a/internal/proxy/powermax_handler.go b/internal/proxy/powermax_handler.go index dec9ece1..f5bdc8cc 100644 --- a/internal/proxy/powermax_handler.go +++ b/internal/proxy/powermax_handler.go @@ -117,7 +117,7 @@ func (h *PowerMaxHandler) UpdateSystems(ctx context.Context, r io.Reader, log *l return nil } -func buildPowerMaxSystem(ctx context.Context, e SystemEntry, log *logrus.Entry) (*PowerMaxSystem, error) { +func buildPowerMaxSystem(_ context.Context, e SystemEntry, log *logrus.Entry) (*PowerMaxSystem, error) { tgt, err := url.Parse(e.Endpoint) if err != nil { return nil, err @@ -493,7 +493,7 @@ func (s *PowerMaxSystem) volumeCreateHandler(next http.Handler, enf *quota.Redis // "volumeIdentifier":{"volumeIdentifierChoice":"identifier_name","identifier_name":"_DEL003E4"} // } // },"executionOption":"SYNCHRONOUS"} -func (s *PowerMaxSystem) volumeModifyHandler(next http.Handler, enf *quota.RedisEnforcement, opaHost string) http.Handler { +func (s *PowerMaxSystem) volumeModifyHandler(next http.Handler, enf *quota.RedisEnforcement, _ string) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx, span := trace.SpanFromContext(r.Context()).TracerProvider().Tracer("").Start(r.Context(), "powermaxVolumeModifyHandler") defer span.End() diff --git a/internal/proxy/powermax_handler_test.go b/internal/proxy/powermax_handler_test.go index f1c7e57e..e426974c 100644 --- a/internal/proxy/powermax_handler_test.go +++ b/internal/proxy/powermax_handler_test.go @@ -109,9 +109,7 @@ func testPowerMaxServeHTTP(t *testing.T) { } }) t.Run("it intercepts volume create requests", func(t *testing.T) { - var ( - gotExistsKey, gotExistsField string - ) + var gotExistsKey, gotExistsField string fakeUni := fakeServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Logf("fake unisphere received: %s %s", r.Method, r.URL) if r.URL.Path == "/univmax/restapi/100/sloprovisioning/symmetrix/1234567890/storagegroup/csi-CSM-Bronze-SRP_1-SG" { @@ -168,9 +166,7 @@ func testPowerMaxServeHTTP(t *testing.T) { } }) t.Run("it intercepts volume modify requests", func(t *testing.T) { - var ( - gotExistsKey, gotExistsField string - ) + var gotExistsKey, gotExistsField string fakeUni := fakeServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Logf("fake unisphere received: %s %s", r.Method, r.URL) switch r.URL.Path { @@ -235,9 +231,7 @@ func testPowerMaxServeHTTP(t *testing.T) { } }) t.Run("provisioning request with a role with infinite quota", func(t *testing.T) { - var ( - gotExistsKey, gotExistsField string - ) + var gotExistsKey, gotExistsField string fakeUni := fakeServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Logf("fake unisphere received: %s %s", r.Method, r.URL) if r.URL.Path == "/univmax/restapi/100/sloprovisioning/symmetrix/1234567890/storagegroup/csi-CSM-Bronze-SRP_1-SG" { @@ -309,7 +303,7 @@ func testPowerMaxServeHTTP(t *testing.T) { } func testPowerMaxUpdateSystems(t *testing.T) { - var tests = []struct { + tests := []struct { name string given io.Reader expectedErr error diff --git a/internal/proxy/powerscale_handler.go b/internal/proxy/powerscale_handler.go index 82fded47..d920fccd 100644 --- a/internal/proxy/powerscale_handler.go +++ b/internal/proxy/powerscale_handler.go @@ -106,7 +106,7 @@ func (h *PowerScaleHandler) UpdateSystems(ctx context.Context, r io.Reader, log return nil } -func buildPowerScaleSystem(ctx context.Context, e SystemEntry, log *logrus.Entry) (*PowerScaleSystem, error) { +func buildPowerScaleSystem(_ context.Context, e SystemEntry, log *logrus.Entry) (*PowerScaleSystem, error) { tgt, err := url.Parse(e.Endpoint) if err != nil { return nil, err @@ -315,7 +315,6 @@ func (h *PowerScaleHandler) addSessionHeaders(r *http.Request, v *PowerScaleSyst } func fetchValueIndexForKey(l string, match string, sep string) (int, int, int) { - if i := strings.Index(l, match); i != -1 { if j := strings.Index(l[i+len(match):], sep); j != -1 { return i, j, len(match) diff --git a/internal/proxy/powerscale_handler_test.go b/internal/proxy/powerscale_handler_test.go index 35ce151f..3c7fda23 100644 --- a/internal/proxy/powerscale_handler_test.go +++ b/internal/proxy/powerscale_handler_test.go @@ -90,7 +90,6 @@ func testPowerScaleServeHTTP(t *testing.T) { if got, want := w.Result().StatusCode, http.StatusOK; got != want { t.Errorf("got status code %d, want status code %d", got, want) } - }) t.Run("it returns 502 Bad Gateway on unknown system", func(t *testing.T) { sut := buildPowerScaleHandler(t) @@ -160,7 +159,7 @@ func testPowerScaleServeHTTP(t *testing.T) { func testPowerScaleUpdateSystems(t *testing.T) { u := &powerscaleUtils{} - var tests = []struct { + tests := []struct { name string given io.Reader expectedErr error diff --git a/internal/proxy/role_handler_test.go b/internal/proxy/role_handler_test.go index 325db68f..d348e0ff 100644 --- a/internal/proxy/role_handler_test.go +++ b/internal/proxy/role_handler_test.go @@ -218,7 +218,6 @@ func TestRoleHandler(t *testing.T) { if !reflect.DeepEqual(want, got) { t.Errorf("expectecd %v, got %v", want, got) } - }) t.Run("handles error from role service get", func(t *testing.T) { client := &mocks.FakeRoleServiceClient{ @@ -296,7 +295,6 @@ func TestRoleHandler(t *testing.T) { if !reflect.DeepEqual(want, got) { t.Errorf("expectecd %v, got %v", want, got) } - }) t.Run("handles error from tenant service list", func(t *testing.T) { client := &mocks.FakeRoleServiceClient{ @@ -331,7 +329,6 @@ func TestRoleHandler(t *testing.T) { Pool: "bronze", Quota: "10", }) - if err != nil { t.Fatal(err) } @@ -377,7 +374,6 @@ func TestRoleHandler(t *testing.T) { Pool: "bronze", Quota: "10", }) - if err != nil { t.Fatal(err) } diff --git a/internal/proxy/root_handler_internal_test.go b/internal/proxy/root_handler_internal_test.go index 6deb8aa9..15e8629a 100644 --- a/internal/proxy/root_handler_internal_test.go +++ b/internal/proxy/root_handler_internal_test.go @@ -17,7 +17,7 @@ package proxy import "testing" func Test_cleanPath(t *testing.T) { - var tests = []struct { + tests := []struct { name string given string want string @@ -32,7 +32,6 @@ func Test_cleanPath(t *testing.T) { if got != tt.want { t.Errorf("(%s): got %s, want %s", tt.given, got, tt.want) } - }) } } diff --git a/internal/proxy/storage_handler_test.go b/internal/proxy/storage_handler_test.go index 3d449a4d..84321a2d 100644 --- a/internal/proxy/storage_handler_test.go +++ b/internal/proxy/storage_handler_test.go @@ -113,7 +113,6 @@ func TestStorageHandler(t *testing.T) { t.Run("successfully lists storages", func(t *testing.T) { client := &mocks.FakeStorageServiceClient{ ListStorageFn: func(ctx context.Context, ctr *pb.StorageListRequest, co ...grpc.CallOption) (*pb.StorageListResponse, error) { - return &pb.StorageListResponse{Storage: []byte("{\"powerflex\":{\"11e4e7d35817bd0f\":{\"User\":\"admin\",\"Password\":\"test\",\"Endpoint\":\"https://10.0.0.1\",\"Insecure\":false}}," + "\"powermax\":{\"542a2d5f5122210f\":{\"User\":\"admin\",\"Password\":\"test\",\"Endpoint\":\"https://10.0.0.1\",\"Insecure\":false}}}")}, nil }, @@ -148,7 +147,6 @@ func TestStorageHandler(t *testing.T) { if !reflect.DeepEqual(want, got) { t.Errorf("expectecd %v, got %v", want, got) } - }) t.Run("handles error from storage service list", func(t *testing.T) { client := &mocks.FakeStorageServiceClient{ @@ -347,7 +345,6 @@ func TestStorageHandler(t *testing.T) { if !reflect.DeepEqual(want, got) { t.Errorf("expected %v, got %v", want, got) } - }) t.Run("handles error from storage service get", func(t *testing.T) { diff --git a/internal/proxy/tenant_handler_test.go b/internal/proxy/tenant_handler_test.go index 1ce63d88..6399e61b 100644 --- a/internal/proxy/tenant_handler_test.go +++ b/internal/proxy/tenant_handler_test.go @@ -225,7 +225,6 @@ func TestTenantHandler(t *testing.T) { if !reflect.DeepEqual(want, got) { t.Errorf("expectecd %v, got %v", want, got) } - }) t.Run("handles error from tenant service get", func(t *testing.T) { client := &mocks.FakeTenantServiceClient{ @@ -306,7 +305,6 @@ func TestTenantHandler(t *testing.T) { if !reflect.DeepEqual(want, got) { t.Errorf("expectecd %v, got %v", want, got) } - }) t.Run("handles error from tenant service list", func(t *testing.T) { client := &mocks.FakeTenantServiceClient{ diff --git a/internal/quota/enforcer.go b/internal/quota/enforcer.go index 85da3e29..16a49d4b 100644 --- a/internal/quota/enforcer.go +++ b/internal/quota/enforcer.go @@ -111,7 +111,7 @@ func WithDB(db DB) Option { } // NewRedisEnforcement returns a new RedisEnforcement. -func NewRedisEnforcement(ctx context.Context, opts ...Option) *RedisEnforcement { +func NewRedisEnforcement(_ context.Context, opts ...Option) *RedisEnforcement { v := &RedisEnforcement{} for _, opt := range opts { opt(v) @@ -295,7 +295,7 @@ return 0 // DeleteRequest marks the volume as being in the process of deletion only. // It's OK for this to be called multiple times, as the only negative impact // would be multiple stream entries. -func (e *RedisEnforcement) DeleteRequest(ctx context.Context, r Request) (bool, error) { +func (e *RedisEnforcement) DeleteRequest(_ context.Context, r Request) (bool, error) { changed, err := e.rdb.EvalInt(` local key = KEYS[1] local approvedField = ARGV[1] @@ -323,7 +323,7 @@ return 0 } // PublishCreated publishes that a volume was created -func (e *RedisEnforcement) PublishCreated(ctx context.Context, r Request) (bool, error) { +func (e *RedisEnforcement) PublishCreated(_ context.Context, r Request) (bool, error) { changed, err := e.rdb.EvalInt(` local key = KEYS[1] local approvedField = ARGV[1] @@ -353,7 +353,7 @@ return 0 } // PublishDeleted publishes that a volume was deleted -func (e *RedisEnforcement) PublishDeleted(ctx context.Context, r Request) (bool, error) { +func (e *RedisEnforcement) PublishDeleted(_ context.Context, r Request) (bool, error) { changed, err := e.rdb.EvalInt(` local key = KEYS[1] local approvedField = ARGV[1] @@ -394,7 +394,7 @@ return 0 // ApprovedNotCreated returns volume data for a volume that was approved to be created but not created // TODO(ian): this should be a continous stream to build an eventually // consistent view. -func (e *RedisEnforcement) ApprovedNotCreated(ctx context.Context, streamKey string) []VolumeData { +func (e *RedisEnforcement) ApprovedNotCreated(_ context.Context, streamKey string) []VolumeData { msgs, err := e.rdb.XRange(streamKey, "-", "+") if err != nil { panic(err) diff --git a/internal/quota/enforcer_test.go b/internal/quota/enforcer_test.go index 5068b9fe..76914c05 100644 --- a/internal/quota/enforcer_test.go +++ b/internal/quota/enforcer_test.go @@ -17,13 +17,12 @@ import ( "context" "errors" "fmt" + "karavi-authorization/internal/quota" "strconv" "sync" "sync/atomic" "testing" - "karavi-authorization/internal/quota" - "github.com/alicebob/miniredis/v2" "github.com/go-redis/redis" ) @@ -104,7 +103,6 @@ func TestRedisEnforcement_ValidateOwnership(t *testing.T) { t.Errorf("got %v, want %v", got, want) } }) - } func TestRedisEnforcement_DeleteRequest(t *testing.T) { @@ -165,7 +163,6 @@ func TestRedisEnforcement_DeleteRequest(t *testing.T) { t.Errorf("got %v, want %v", got, want) } }) - } func TestRedisEnforcement_PublishCreated(t *testing.T) { @@ -363,7 +360,7 @@ func TestRequest(t *testing.T) { type keyFunc func() string r := buildRequest() - var tests = []struct { + tests := []struct { name string fn keyFunc want string @@ -378,7 +375,6 @@ func TestRequest(t *testing.T) { if got != tt.want { t.Errorf("%s(): got %q, want %q", tt.name, got, tt.want) } - }) } }) @@ -386,7 +382,7 @@ func TestRequest(t *testing.T) { type fieldFunc func() string r := buildRequest() - var tests = []struct { + tests := []struct { name string fn fieldFunc want string @@ -405,7 +401,6 @@ func TestRequest(t *testing.T) { if got != tt.want { t.Errorf("%s(): got %q, want %q", tt.name, got, tt.want) } - }) } }) diff --git a/internal/role-service/roles/json.go b/internal/role-service/roles/json.go index 5cabd469..c2927dfe 100644 --- a/internal/role-service/roles/json.go +++ b/internal/role-service/roles/json.go @@ -59,7 +59,6 @@ func TransformReadable(rolesmap *JSON) *ReadableJSON { // It adds extra maps around each type of data to // help describe it. func (j *ReadableJSON) MarshalJSON() ([]byte, error) { - m := make(map[string]interface{}) initMap := func(m interface{}, key string) map[string]interface{} { @@ -101,7 +100,6 @@ func (j *ReadableJSON) MarshalJSON() ([]byte, error) { // UnmarshalJSON unmarshals the given bytes into this // JSON value. func (j *ReadableJSON) UnmarshalJSON(b []byte) error { - if j.m == nil { j.m = make(map[RoleKey]*ReadableInstance) } @@ -123,7 +121,7 @@ func (j *ReadableJSON) UnmarshalJSON(b []byte) error { v2.GetObject("system_ids").Visit(func(k3 []byte, v3 *fastjson.Value) { // k3 = system id v3.GetObject("pool_quotas").Visit(func(k4 []byte, v4 *fastjson.Value) { - //n, err := v4.Int() + // n, err := v4.Int() if err != nil { return } diff --git a/internal/role-service/roles/roles.go b/internal/role-service/roles/roles.go index 11354a51..b300ee6c 100644 --- a/internal/role-service/roles/roles.go +++ b/internal/role-service/roles/roles.go @@ -107,7 +107,6 @@ func NewInstance(role string, parts ...string) (*Instance, error) { // store quota in kilobytes ins.Quota = int(n / 1000) } - } return ins, nil } diff --git a/internal/role-service/roles/roles_test.go b/internal/role-service/roles/roles_test.go index c224919f..8fe1d954 100644 --- a/internal/role-service/roles/roles_test.go +++ b/internal/role-service/roles/roles_test.go @@ -24,7 +24,7 @@ import ( const ExpectedInstanceCount = 3 func TestRoleKey_String(t *testing.T) { - var tests = []struct { + tests := []struct { want string given roles.RoleKey }{ @@ -66,7 +66,6 @@ func TestRoleKey_String(t *testing.T) { if got != tt.want { t.Errorf("(%s): got %s, want %s", tt.want, got, tt.want) } - }) } } @@ -111,7 +110,7 @@ func TestJSON_Unmarshal(t *testing.T) { func TestNewInstance(t *testing.T) { t.Run("validation", func(t *testing.T) { - var tests = []struct { + tests := []struct { name string args []string expectedQuota int @@ -242,7 +241,7 @@ func TestJSON_Add(t *testing.T) { func TestJSON_Remove(t *testing.T) { t.Run("validation", func(t *testing.T) { - var tests = []struct { + tests := []struct { name string givenArgs []string expectErr bool diff --git a/internal/role-service/service.go b/internal/role-service/service.go index 378ada0f..490db5fc 100644 --- a/internal/role-service/service.go +++ b/internal/role-service/service.go @@ -174,7 +174,7 @@ func (s *Service) Delete(ctx context.Context, req *pb.RoleDeleteRequest) (*pb.Ro } // List lists the configured roles -func (s *Service) List(ctx context.Context, req *pb.RoleListRequest) (*pb.RoleListResponse, error) { +func (s *Service) List(ctx context.Context, _ *pb.RoleListRequest) (*pb.RoleListResponse, error) { s.log.Info("Serving list role request") s.log.Debug("Getting configured roles from Kubernetes") diff --git a/internal/role-service/service_test.go b/internal/role-service/service_test.go index bba26922..fb786f0f 100644 --- a/internal/role-service/service_test.go +++ b/internal/role-service/service_test.go @@ -524,12 +524,12 @@ func (k fakeKube) GetConfiguredRoles(ctx context.Context) (*roles.JSON, error) { type successfulValidator struct{} -func (v successfulValidator) Validate(ctx context.Context, role *roles.Instance) error { +func (v successfulValidator) Validate(_ context.Context, _ *roles.Instance) error { return nil } type failValidator struct{} -func (v failValidator) Validate(ctx context.Context, role *roles.Instance) error { +func (v failValidator) Validate(_ context.Context, _ *roles.Instance) error { return errors.New("error") } diff --git a/internal/role-service/validate/powerflex.go b/internal/role-service/validate/powerflex.go index 204580eb..322725da 100644 --- a/internal/role-service/validate/powerflex.go +++ b/internal/role-service/validate/powerflex.go @@ -31,7 +31,7 @@ var GetPowerFlexEndpoint = func(system storage.System) string { } // PowerFlex validates powerflex role parameters -func PowerFlex(ctx context.Context, log *logrus.Entry, system storage.System, systemID string, pool string, quota int64) error { +func PowerFlex(_ context.Context, log *logrus.Entry, system storage.System, systemID string, pool string, quota int64) error { if quota < 0 { return errors.New("the specified quota needs to be a positive number") } diff --git a/internal/role-service/validate/validate_test.go b/internal/role-service/validate/validate_test.go index e5675e5c..f67e0dc4 100644 --- a/internal/role-service/validate/validate_test.go +++ b/internal/role-service/validate/validate_test.go @@ -169,7 +169,6 @@ storage: // define the tests tests := map[string]func(t *testing.T) (validate.Kube, *roles.Instance, checkFn){ "negative quota": func(t *testing.T) (validate.Kube, *roles.Instance, checkFn) { - // configure fake k8s with storage secret data := []byte(fmt.Sprintf(` storage: diff --git a/internal/sdc/sdc_approve.go b/internal/sdc/sdc_approve.go index 8db31347..fb1d58f9 100644 --- a/internal/sdc/sdc_approve.go +++ b/internal/sdc/sdc_approve.go @@ -73,7 +73,7 @@ func WithDB(db sdcDB) Option { } // NewSdcApprover returns a new RedisSdcApprover. -func NewSdcApprover(ctx context.Context, opts ...Option) *RedisSdcApprover { +func NewSdcApprover(_ context.Context, opts ...Option) *RedisSdcApprover { v := &RedisSdcApprover{} for _, opt := range opts { opt(v) diff --git a/internal/sdc/sdc_approve_test.go b/internal/sdc/sdc_approve_test.go index 5572d826..fa889dbe 100644 --- a/internal/sdc/sdc_approve_test.go +++ b/internal/sdc/sdc_approve_test.go @@ -90,9 +90,10 @@ func TestSdcApprover_checkSdcApproveFlag(t *testing.T) { }) t.Run("returns any error", func(t *testing.T) { sut := sdc.NewSdcApprover(context.Background(), - sdc.WithDB(&sdc.FakeRedis{HGetFn: func(key, field string) (string, error) { - return "false", ErrFake - }, + sdc.WithDB(&sdc.FakeRedis{ + HGetFn: func(key, field string) (string, error) { + return "false", ErrFake + }, })) _, got := sut.CheckSdcApproveFlag(context.Background(), req) @@ -115,7 +116,7 @@ func TestRequest(t *testing.T) { type keyFunc func() string r := buildRequest() - var tests = []struct { + tests := []struct { name string fn keyFunc want string @@ -129,7 +130,6 @@ func TestRequest(t *testing.T) { if got != tt.want { t.Errorf("%s(): got %q, want %q", tt.name, got, tt.want) } - }) } }) @@ -137,7 +137,7 @@ func TestRequest(t *testing.T) { type fieldFunc func() string r := buildRequest() - var tests = []struct { + tests := []struct { name string fn fieldFunc want string @@ -151,7 +151,6 @@ func TestRequest(t *testing.T) { if got != tt.want { t.Errorf("%s(): got %q, want %q", tt.name, got, tt.want) } - }) } }) diff --git a/internal/storage-service/middleware/storage_telemetry.go b/internal/storage-service/middleware/storage_telemetry.go index cbb1dc8c..72576ce2 100644 --- a/internal/storage-service/middleware/storage_telemetry.go +++ b/internal/storage-service/middleware/storage_telemetry.go @@ -157,7 +157,6 @@ func (t *TelemetryMW) Delete(ctx context.Context, req *pb.StorageDeleteRequest) } return &pb.StorageDeleteResponse{}, nil - } // List wraps List diff --git a/internal/storage-service/middleware/storage_telemetry_test.go b/internal/storage-service/middleware/storage_telemetry_test.go index 927c3b7e..4a2ea6ec 100644 --- a/internal/storage-service/middleware/storage_telemetry_test.go +++ b/internal/storage-service/middleware/storage_telemetry_test.go @@ -169,7 +169,6 @@ func TestStorage(t *testing.T) { t.Errorf("expected next service to be called") } }) - }) t.Run("Delete test cases", func(t *testing.T) { t.Run("Delete sucssessful run", func(t *testing.T) { @@ -302,5 +301,4 @@ func TestStorage(t *testing.T) { } }) }) - } diff --git a/internal/storage-service/service.go b/internal/storage-service/service.go index fb330a0b..94c75eb0 100644 --- a/internal/storage-service/service.go +++ b/internal/storage-service/service.go @@ -146,7 +146,7 @@ func (s *Service) Create(ctx context.Context, req *pb.StorageCreateRequest) (*pb } // List lists the configured roles -func (s *Service) List(ctx context.Context, req *pb.StorageListRequest) (*pb.StorageListResponse, error) { +func (s *Service) List(ctx context.Context, _ *pb.StorageListRequest) (*pb.StorageListResponse, error) { s.log.Info("Serving list storage request") // Get the current list of registered storage systems @@ -381,8 +381,7 @@ func (s *Service) GetPowerflexVolumes(ctx context.Context, req *pb.GetPowerflexV } // CheckForDuplicates checks if requested systemID already exists -func CheckForDuplicates(ctx context.Context, existingStorages storage.Storage, systemID string, storageType string) error { - +func CheckForDuplicates(_ context.Context, existingStorages storage.Storage, systemID string, storageType string) error { // Check that we are not duplicating, no errors, etc. sysIDs := strings.Split(systemID, ",") isDuplicate := func() (string, bool) { diff --git a/internal/storage-service/service_test.go b/internal/storage-service/service_test.go index c2875f5e..f8757887 100644 --- a/internal/storage-service/service_test.go +++ b/internal/storage-service/service_test.go @@ -357,7 +357,6 @@ func TestServiceGet(t *testing.T) { tests := map[string]func(t *testing.T) (*pb.StorageGetRequest, service.Kube, checkFn){ "success": func(t *testing.T) (*pb.StorageGetRequest, service.Kube, checkFn) { getStorageFn := func(ctx context.Context) (storage.Storage, error) { - return storage.Storage{ "powerflex": storage.SystemType{ "11e4e7d35817bd0f": storage.System{ @@ -1014,33 +1013,33 @@ func errIsNotNil(t *testing.T, err error) { type successfulKube struct{} -func (k successfulKube) UpdateStorages(ctx context.Context, storages storage.Storage) error { +func (k successfulKube) UpdateStorages(_ context.Context, _ storage.Storage) error { return nil } -func (k successfulKube) GetConfiguredStorage(ctx context.Context) (storage.Storage, error) { +func (k successfulKube) GetConfiguredStorage(_ context.Context) (storage.Storage, error) { return storage.Storage{}, nil } type failKube struct{} -func (k failKube) UpdateStorages(ctx context.Context, storages storage.Storage) error { +func (k failKube) UpdateStorages(_ context.Context, _ storage.Storage) error { return errors.New("error") } -func (k failKube) GetConfiguredStorage(ctx context.Context) (storage.Storage, error) { +func (k failKube) GetConfiguredStorage(_ context.Context) (storage.Storage, error) { return nil, nil } type successfulValidator struct{} -func (v successfulValidator) Validate(ctx context.Context, systemID string, systemType string, system storage.System) error { +func (v successfulValidator) Validate(_ context.Context, _ string, _ string, _ storage.System) error { return nil } type failValidator struct{} -func (v failValidator) Validate(ctx context.Context, systemID string, systemType string, system storage.System) error { +func (v failValidator) Validate(_ context.Context, _ string, _ string, _ storage.System) error { return errors.New("error") } diff --git a/internal/storage-service/validate.go b/internal/storage-service/validate.go index c63c77a7..7c14cab8 100644 --- a/internal/storage-service/validate.go +++ b/internal/storage-service/validate.go @@ -57,7 +57,6 @@ func NewSystemValidator(kube Kube, log *logrus.Entry) *SystemValidator { // Validate validates a storage instance func (v *SystemValidator) Validate(ctx context.Context, systemID string, systemType string, system storage.System) error { - v.log.Info("Validating storage") if !validSystemType(systemType) { return fmt.Errorf("system type %s is not supported", systemType) @@ -75,8 +74,7 @@ func (v *SystemValidator) Validate(ctx context.Context, systemID string, systemT } } -func validatePowerflex(ctx context.Context, log *logrus.Entry, system storage.System, systemID string) error { - +func validatePowerflex(_ context.Context, _ *logrus.Entry, system storage.System, systemID string) error { endpoint := GetPowerFlexEndpoint(system) epURL, err := url.Parse(endpoint) if err != nil { @@ -101,8 +99,7 @@ func validatePowerflex(ctx context.Context, log *logrus.Entry, system storage.Sy return nil } -func validatePowermax(ctx context.Context, log *logrus.Entry, system storage.System, systemID string) error { - +func validatePowermax(ctx context.Context, _ *logrus.Entry, system storage.System, _ string) error { endpoint := GetPowerMaxEndpoint(system) epURL, err := url.Parse(endpoint) if err != nil { @@ -125,8 +122,7 @@ func validatePowermax(ctx context.Context, log *logrus.Entry, system storage.Sys return nil } -func validatePowerscale(ctx context.Context, log *logrus.Entry, system storage.System, systemID string) error { - +func validatePowerscale(_ context.Context, _ *logrus.Entry, system storage.System, systemID string) error { endpoint := GetPowerScaleEndpoint(system) epURL, err := url.Parse(endpoint) if err != nil { diff --git a/internal/storage-service/validate_test.go b/internal/storage-service/validate_test.go index 422ce36c..bddb2952 100644 --- a/internal/storage-service/validate_test.go +++ b/internal/storage-service/validate_test.go @@ -120,7 +120,6 @@ storage: // Error cases t.Run("Error", func(t *testing.T) { - // define check functions to pass or fail tests type checkFn func(*testing.T, error) @@ -271,7 +270,6 @@ storage: // Error paths t.Run("Error", func(t *testing.T) { - // define check functions to pass or fail tests type checkFn func(*testing.T, error) @@ -417,7 +415,6 @@ func TestValidatePowerScale(t *testing.T) { // Error paths t.Run("Error", func(t *testing.T) { - // define check functions to pass or fail tests type checkFn func(*testing.T, error) @@ -483,9 +480,7 @@ func TestValidatePowerScale(t *testing.T) { } func TestValidateError(t *testing.T) { - t.Run("invalid system type", func(t *testing.T) { - // define the validator with a k8s client that has no karavi-storage-secret configured fakeClient := fake.NewSimpleClientset() diff --git a/internal/tenantsvc/middleware/telemetry.go b/internal/tenantsvc/middleware/telemetry.go index 1571ae04..2be8d003 100644 --- a/internal/tenantsvc/middleware/telemetry.go +++ b/internal/tenantsvc/middleware/telemetry.go @@ -133,7 +133,6 @@ func (t *TelemetryMW) DeleteTenant(ctx context.Context, req *pb.DeleteTenantRequ } return &pb.DeleteTenantResponse{}, nil - } // ListTenant wraps ListTenant diff --git a/internal/tenantsvc/service.go b/internal/tenantsvc/service.go index 91d2b72e..02f0d5cf 100644 --- a/internal/tenantsvc/service.go +++ b/internal/tenantsvc/service.go @@ -113,7 +113,7 @@ func (t *TenantService) CreateTenant(ctx context.Context, req *pb.CreateTenantRe } // UpdateTenant handles tenant updation requests. -func (t *TenantService) UpdateTenant(ctx context.Context, req *pb.UpdateTenantRequest) (*pb.Tenant, error) { +func (t *TenantService) UpdateTenant(_ context.Context, req *pb.UpdateTenantRequest) (*pb.Tenant, error) { m, err := t.rdb.HGetAll(tenantKey(req.TenantName)).Result() if err != nil { return nil, err @@ -158,7 +158,7 @@ func (t *TenantService) UpdateTenant(ctx context.Context, req *pb.UpdateTenantRe } // GetTenant handles tenant query requests. -func (t *TenantService) GetTenant(ctx context.Context, req *pb.GetTenantRequest) (*pb.Tenant, error) { +func (t *TenantService) GetTenant(_ context.Context, req *pb.GetTenantRequest) (*pb.Tenant, error) { m, err := t.rdb.HGetAll(tenantKey(req.Name)).Result() if err != nil { return nil, err @@ -217,7 +217,7 @@ func (t *TenantService) DeleteTenant(ctx context.Context, req *pb.DeleteTenantRe } // ListTenant handles tenant listing requests. -func (t *TenantService) ListTenant(ctx context.Context, req *pb.ListTenantRequest) (*pb.ListTenantResponse, error) { +func (t *TenantService) ListTenant(_ context.Context, _ *pb.ListTenantRequest) (*pb.ListTenantResponse, error) { var tenants []*pb.Tenant var cursor uint64 @@ -246,7 +246,7 @@ func (t *TenantService) ListTenant(ctx context.Context, req *pb.ListTenantReques } // BindRole handles rolebinding creation requests. -func (t *TenantService) BindRole(ctx context.Context, req *pb.BindRoleRequest) (*pb.BindRoleResponse, error) { +func (t *TenantService) BindRole(_ context.Context, req *pb.BindRoleRequest) (*pb.BindRoleResponse, error) { // Update a set with role -> tenants mappings t.rdb.SAdd(rolesTenantKey(req.RoleName), req.TenantName) // Update a set with tenant -> roles mappings @@ -256,7 +256,7 @@ func (t *TenantService) BindRole(ctx context.Context, req *pb.BindRoleRequest) ( } // UnbindRole handles rolebinding deletion requests. -func (t *TenantService) UnbindRole(ctx context.Context, req *pb.UnbindRoleRequest) (*pb.UnbindRoleResponse, error) { +func (t *TenantService) UnbindRole(_ context.Context, req *pb.UnbindRoleRequest) (*pb.UnbindRoleResponse, error) { // Update a set with role -> tenants mappings t.rdb.SRem(rolesTenantKey(req.RoleName), req.TenantName) // Update a set with tenant -> roles mappings @@ -267,7 +267,7 @@ func (t *TenantService) UnbindRole(ctx context.Context, req *pb.UnbindRoleReques // GenerateToken generates a token for a given tenant. The returned token is // in the format of a Kubernetes Secret resource. -func (t *TenantService) GenerateToken(ctx context.Context, req *pb.GenerateTokenRequest) (*pb.GenerateTokenResponse, error) { +func (t *TenantService) GenerateToken(_ context.Context, req *pb.GenerateTokenRequest) (*pb.GenerateTokenResponse, error) { // Check the tenant exists. exists, err := t.rdb.Exists(tenantKey(req.TenantName)).Result() if err != nil { @@ -315,7 +315,7 @@ func (t *TenantService) GenerateToken(ctx context.Context, req *pb.GenerateToken // RefreshToken refreshes a token given a valid refresh and access token. // A refresh token is refused if the owning tenant is found to be in the // revocation list (tenant:revoked). -func (t *TenantService) RefreshToken(ctx context.Context, req *pb.RefreshTokenRequest) (*pb.RefreshTokenResponse, error) { +func (t *TenantService) RefreshToken(_ context.Context, req *pb.RefreshTokenRequest) (*pb.RefreshTokenResponse, error) { refreshToken := req.RefreshToken accessToken := req.AccessToken @@ -379,7 +379,7 @@ func (t *TenantService) RefreshToken(ctx context.Context, req *pb.RefreshTokenRe } // RevokeTenant revokes access for the given tenant. -func (t *TenantService) RevokeTenant(ctx context.Context, req *pb.RevokeTenantRequest) (*pb.RevokeTenantResponse, error) { +func (t *TenantService) RevokeTenant(_ context.Context, req *pb.RevokeTenantRequest) (*pb.RevokeTenantResponse, error) { _, err := t.rdb.SAdd(KeyTenantRevoked, req.TenantName).Result() if err != nil { return nil, err @@ -389,7 +389,7 @@ func (t *TenantService) RevokeTenant(ctx context.Context, req *pb.RevokeTenantRe } // CancelRevokeTenant cancels the revocation of access for the given tenant. -func (t *TenantService) CancelRevokeTenant(ctx context.Context, req *pb.CancelRevokeTenantRequest) (*pb.CancelRevokeTenantResponse, error) { +func (t *TenantService) CancelRevokeTenant(_ context.Context, req *pb.CancelRevokeTenantRequest) (*pb.CancelRevokeTenantResponse, error) { err := t.cancelRevokeTenant(req.TenantName) if err != nil { return nil, err @@ -408,7 +408,7 @@ func (t *TenantService) cancelRevokeTenant(name string) error { } // CheckRevoked checks to see if the given Tenant has had their access revoked. -func (t *TenantService) CheckRevoked(ctx context.Context, tenantName string) (bool, error) { +func (t *TenantService) CheckRevoked(_ context.Context, tenantName string) (bool, error) { b, err := t.rdb.SIsMember(KeyTenantRevoked, tenantName).Result() if err != nil { return false, err @@ -416,7 +416,7 @@ func (t *TenantService) CheckRevoked(ctx context.Context, tenantName string) (bo return b, nil } -func (t *TenantService) createOrUpdateTenant(ctx context.Context, v *pb.Tenant, isUpdate bool) (*pb.Tenant, error) { +func (t *TenantService) createOrUpdateTenant(_ context.Context, v *pb.Tenant, isUpdate bool) (*pb.Tenant, error) { if v == nil { return nil, ErrNilTenant } diff --git a/internal/tenantsvc/service_test.go b/internal/tenantsvc/service_test.go index cfcfc0a2..eb7ff49b 100644 --- a/internal/tenantsvc/service_test.go +++ b/internal/tenantsvc/service_test.go @@ -18,6 +18,7 @@ import ( "context" "encoding/base64" "fmt" + "io/ioutil" "karavi-authorization/internal/tenantsvc" "karavi-authorization/internal/token/jwx" "karavi-authorization/pb" @@ -31,12 +32,6 @@ import ( "sigs.k8s.io/yaml" ) -// Common values. -const ( - RefreshToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJrYXJhdmkiLCJleHAiOjE5MTU1ODU4ODMsImlzcyI6ImNvbS5kZWxsLmthcmF2aSIsInN1YiI6ImthcmF2aS10ZW5hbnQiLCJyb2xlcyI6IkNBLW1lZGl1bSIsImdyb3VwIjoiUGFuY2FrZUdyb3VwIn0.7fljbEr3ylTGO7MeeEk-jv4-QzxhcQaXjDAXXvmo9zI" - AccessToken = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJrYXJhdmkiLCJleHAiOjExMTQ0ODQ4ODMsImlzcyI6ImNvbS5kZWxsLmthcmF2aSIsInN1YiI6ImthcmF2aS10ZW5hbnQiLCJyb2xlcyI6IkNBLW1lZGl1bSIsImdyb3VwIjoiUGFuY2FrZUdyb3VwIn0.IE4yX53JaGwHZigD299ROtt0OH6DhUWGqejcLQ9N-xU" -) - type AfterFunc func() func TestTenantService(t *testing.T) { @@ -158,7 +153,7 @@ func testUpdateTenant(sut *tenantsvc.TenantService, afterFn AfterFunc) func(*tes } } -func testGetTenant(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn AfterFunc) func(*testing.T) { +func testGetTenant(sut *tenantsvc.TenantService, _ *redis.Client, afterFn AfterFunc) func(*testing.T) { return func(t *testing.T) { t.Run("it gets a created tenant", func(t *testing.T) { defer afterFn() @@ -282,7 +277,7 @@ func testDeleteTenant(sut *tenantsvc.TenantService, afterFn AfterFunc) func(*tes } } -func testBindRole(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn AfterFunc) func(*testing.T) { +func testBindRole(sut *tenantsvc.TenantService, _ *redis.Client, afterFn AfterFunc) func(*testing.T) { return func(t *testing.T) { t.Run("it creates a role binding", func(t *testing.T) { defer afterFn() @@ -307,7 +302,7 @@ func testBindRole(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn After } } -func testUnbindRole(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn AfterFunc) func(*testing.T) { +func testUnbindRole(sut *tenantsvc.TenantService, _ *redis.Client, afterFn AfterFunc) func(*testing.T) { return func(t *testing.T) { t.Run("it deletes a role binding", func(t *testing.T) { defer afterFn() @@ -332,7 +327,7 @@ func testUnbindRole(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn Aft } } -func testListTenant(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn AfterFunc) func(*testing.T) { +func testListTenant(sut *tenantsvc.TenantService, _ *redis.Client, afterFn AfterFunc) func(*testing.T) { return func(t *testing.T) { t.Run("it lists existing tenants", func(t *testing.T) { defer afterFn() @@ -351,7 +346,7 @@ func testListTenant(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn Aft } } -func testGenerateToken(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn AfterFunc) func(*testing.T) { +func testGenerateToken(sut *tenantsvc.TenantService, _ *redis.Client, afterFn AfterFunc) func(*testing.T) { return func(t *testing.T) { t.Run("it generates a token", func(t *testing.T) { defer afterFn() @@ -396,8 +391,19 @@ func testGenerateToken(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn } } -func testRefreshToken(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn AfterFunc) func(*testing.T) { +func testRefreshToken(sut *tenantsvc.TenantService, _ *redis.Client, afterFn AfterFunc) func(*testing.T) { return func(t *testing.T) { + tokens := make(map[string]interface{}) + credFile, err := ioutil.ReadFile("../../tokens.yaml") + if err != nil { + t.Errorf("unable to read token: %v", err) + } + err = yaml.Unmarshal(credFile, &tokens) + if err != nil { + t.Errorf("unable to unmarshal token: %v", err) + } + AccessToken := tokens["AccessToken"].(string) + RefreshToken := tokens["RefreshToken"].(string) t.Run("it refreshes a token", func(t *testing.T) { defer afterFn() @@ -495,10 +501,9 @@ func testRefreshToken(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn A } }) } - } -func testRevokeTenant(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn AfterFunc) func(*testing.T) { +func testRevokeTenant(sut *tenantsvc.TenantService, _ *redis.Client, afterFn AfterFunc) func(*testing.T) { return func(t *testing.T) { t.Run("it revokes access to a tenant", func(t *testing.T) { defer afterFn() @@ -519,7 +524,7 @@ func testRevokeTenant(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn A } } -func testCancelRevokeTenant(sut *tenantsvc.TenantService, rdb *redis.Client, afterFn AfterFunc) func(*testing.T) { +func testCancelRevokeTenant(sut *tenantsvc.TenantService, _ *redis.Client, afterFn AfterFunc) func(*testing.T) { return func(t *testing.T) { t.Run("it cancels a revocation operation on a tenant", func(t *testing.T) { defer afterFn() diff --git a/internal/token/generate_test.go b/internal/token/generate_test.go index de569edf..7086702e 100644 --- a/internal/token/generate_test.go +++ b/internal/token/generate_test.go @@ -214,6 +214,7 @@ func testBuildTokenConfig() token.Config { AccessExpiration: time.Minute, } } + func testBuildAdminTokenConfig() token.Config { return token.Config{ AdminName: "admin", diff --git a/internal/token/jwx/jwx.go b/internal/token/jwx/jwx.go index 3f83998b..9c6426ed 100644 --- a/internal/token/jwx/jwx.go +++ b/internal/token/jwx/jwx.go @@ -55,8 +55,10 @@ var ( JWTSigningSecret = "secret" ) -var _ token.Manager = &Manager{} -var _ token.Token = &Token{} +var ( + _ token.Manager = &Manager{} + _ token.Token = &Token{} +) // NewTokenManager returns a Manager configured with the supplied signature algorithm func NewTokenManager(alg SignatureAlgorithm) token.Manager { @@ -258,7 +260,7 @@ func tokenFromClaims(claims token.Claims) (jwt.Token, error) { // GenerateAdminToken generates a token for an admin. The returned token is // in JSON format. -func GenerateAdminToken(ctx context.Context, req *pb.GenerateAdminTokenRequest) (*pb.GenerateAdminTokenResponse, error) { +func GenerateAdminToken(_ context.Context, req *pb.GenerateAdminTokenRequest) (*pb.GenerateAdminTokenResponse, error) { tm := NewTokenManager(HS256) // Get the expiration values from config. @@ -289,7 +291,7 @@ func GenerateAdminToken(ctx context.Context, req *pb.GenerateAdminTokenRequest) } // RefreshAdminToken refreshes an admin access token given a valid refresh and access token. -func RefreshAdminToken(ctx context.Context, req *pb.RefreshAdminTokenRequest) (*pb.RefreshAdminTokenResponse, error) { +func RefreshAdminToken(_ context.Context, req *pb.RefreshAdminTokenRequest) (*pb.RefreshAdminTokenResponse, error) { tm := NewTokenManager(HS256) refreshToken := req.RefreshToken accessToken := req.AccessToken diff --git a/internal/token/jwx/jwx_test.go b/internal/token/jwx/jwx_test.go index 28ef4721..177fd766 100644 --- a/internal/token/jwx/jwx_test.go +++ b/internal/token/jwx/jwx_test.go @@ -269,7 +269,6 @@ func TestRefreshAdminToken(t *testing.T) { if err == nil { t.Errorf("expected non-nil err, got %v", refresh) } - }) } diff --git a/internal/token/token.go b/internal/token/token.go index f5e34138..8748ddad 100644 --- a/internal/token/token.go +++ b/internal/token/token.go @@ -19,10 +19,8 @@ import ( "time" ) -var ( - // ErrExpired is the error for an expired token - ErrExpired = errors.New("token has expired") -) +// ErrExpired is the error for an expired token +var ErrExpired = errors.New("token has expired") // Claims represents the standard JWT claims in addition // to Karavi-Authorization specific claims. diff --git a/internal/web/middleware.go b/internal/web/middleware.go index acbd453a..5508880d 100644 --- a/internal/web/middleware.go +++ b/internal/web/middleware.go @@ -44,10 +44,8 @@ const ( SystemIDKey // SystemIDKey is the context key for a system ID ) -var ( - // JWTSigningSecret is the secret string used to sign JWT tokens - JWTSigningSecret = "secret" -) +// JWTSigningSecret is the secret string used to sign JWT tokens +var JWTSigningSecret = "secret" // Middleware is a function that accepts an http Handler and returns an http Handler following the middleware pattern type Middleware func(http.Handler) http.Handler @@ -182,7 +180,7 @@ type HandlerWithError func(w http.ResponseWriter, r *http.Request) error // ServeHTTP implements the http.Handler interface // This is a noop because the underlying HandlerWithError should be executed explicitly -func (h HandlerWithError) ServeHTTP(w http.ResponseWriter, r *http.Request) {} +func (h HandlerWithError) ServeHTTP(_ http.ResponseWriter, _ *http.Request) {} // TelemetryMW logs the time for the next handler and records the error from the next handler in the span // The next handler must be the HandlerWithError type for logging and error recording diff --git a/internal/web/middleware_test.go b/internal/web/middleware_test.go index 502adbf0..819dec75 100644 --- a/internal/web/middleware_test.go +++ b/internal/web/middleware_test.go @@ -17,10 +17,10 @@ package web_test import ( "context" "errors" + "io/ioutil" "karavi-authorization/internal/token/jwx" "karavi-authorization/internal/web" "karavi-authorization/pb" - "net/http" "net/http/httptest" "testing" @@ -121,7 +121,16 @@ func TestAuthMW(t *testing.T) { h := web.Adapt(handler, web.AuthMW(discardLogger(), jwx.NewTokenManager(jwx.HS256))) // test token - tokenString := "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" + tokens := make(map[string]interface{}) + credFile, err := ioutil.ReadFile("../../tokens.yaml") + if err != nil { + t.Errorf("unable to read token: %v", err) + } + err = yaml.Unmarshal(credFile, &tokens) + if err != nil { + t.Errorf("unable to unmarshal token: %v", err) + } + tokenString := tokens["tokenString"].(string) w := httptest.NewRecorder() r, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil) @@ -139,7 +148,16 @@ func TestAuthMW(t *testing.T) { h := web.Adapt(handler, web.AuthMW(discardLogger(), jwx.NewTokenManager(jwx.HS256))) // test token - tokenString := "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" + tokens := make(map[string]interface{}) + credFile, err := ioutil.ReadFile("../../tokens.yaml") + if err != nil { + t.Errorf("unable to read token: %v", err) + } + err = yaml.Unmarshal(credFile, &tokens) + if err != nil { + t.Errorf("unable to unmarshal token: %v", err) + } + tokenString := tokens["tokenString"].(string) w := httptest.NewRecorder() r, err := http.NewRequestWithContext(context.Background(), http.MethodGet, "/", nil) @@ -157,7 +175,6 @@ func TestAuthMW(t *testing.T) { }) t.Run("it executes the next handler if next is wrong type", func(t *testing.T) { - var gotCalled bool handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotCalled = true @@ -196,7 +213,6 @@ func TestAuthMW(t *testing.T) { t.Errorf("expected next handler to be executed") } }) - } func discardLogger() *logrus.Entry { diff --git a/tokens.yaml b/tokens.yaml new file mode 100644 index 00000000..521e7209 --- /dev/null +++ b/tokens.yaml @@ -0,0 +1,5 @@ +tokenString: "Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" +AccessToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJrYXJhdmkiLCJleHAiOjExMTQ0ODQ4ODMsImlzcyI6ImNvbS5kZWxsLmthcmF2aSIsInN1YiI6ImthcmF2aS10ZW5hbnQiLCJyb2xlcyI6IkNBLW1lZGl1bSIsImdyb3VwIjoiUGFuY2FrZUdyb3VwIn0.IE4yX53JaGwHZigD299ROtt0OH6DhUWGqejcLQ9N-xU" +RefreshToken: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJhdWQiOiJrYXJhdmkiLCJleHAiOjE5MTU1ODU4ODMsImlzcyI6ImNvbS5kZWxsLmthcmF2aSIsInN1YiI6ImthcmF2aS10ZW5hbnQiLCJyb2xlcyI6IkNBLW1lZGl1bSIsImdyb3VwIjoiUGFuY2FrZUdyb3VwIn0.7fljbEr3ylTGO7MeeEk-jv4-QzxhcQaXjDAXXvmo9zI" +secondToken: "YWRtaW46MTYxMDU3OTI1NjMyMjo2MGFiNTIyYTcxYjEwMGM3ZTdlYzRhMDU3MDA1MjNhMw" +firstToken: "YWRtaW46MTYxMDUxNzk5NDQxODpjYzBkMGEwMmUwYzNiODUxOTM1NWMxZThkNTcwZWEwNA" \ No newline at end of file