Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix various lint issues #419

Merged
merged 1 commit into from
Aug 17, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 7 additions & 8 deletions controllers/auth_config_status_updater_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
k8score "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/types"
controllerruntime "sigs.k8s.io/controller-runtime"
ctrl "sigs.k8s.io/controller-runtime"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/reconcile"
Expand All @@ -28,7 +27,7 @@ func TestAuthConfigStatusUpdater_Reconcile(t *testing.T) {
reconciler := mockStatusUpdaterReconciler(client)
reconciler.StatusReport.Set(resourceName.String(), api.StatusReasonReconciled, "", []string{"echo-api"})

result, err := reconciler.Reconcile(context.Background(), controllerruntime.Request{NamespacedName: resourceName})
result, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: resourceName})

assert.Equal(t, result, ctrl.Result{})
assert.NilError(t, err)
Expand All @@ -47,7 +46,7 @@ func TestAuthConfigStatusUpdater_MissingWatchedAuthConfigLabels(t *testing.T) {
client := newTestK8sClient(&authConfig)
reconciler := mockStatusUpdaterReconciler(client)

result, err := reconciler.Reconcile(context.Background(), controllerruntime.Request{NamespacedName: resourceName})
result, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: resourceName})

assert.Equal(t, result, ctrl.Result{})
assert.NilError(t, err)
Expand All @@ -67,7 +66,7 @@ func TestAuthConfigStatusUpdater_MatchingAuthConfigLabels(t *testing.T) {
reconciler := mockStatusUpdaterReconciler(client)
reconciler.StatusReport.Set(resourceName.String(), api.StatusReasonReconciled, "", []string{"echo-api"})

result, err := reconciler.Reconcile(context.Background(), controllerruntime.Request{NamespacedName: resourceName})
result, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: resourceName})

assert.Equal(t, result, ctrl.Result{})
assert.NilError(t, err)
Expand All @@ -86,7 +85,7 @@ func TestAuthConfigStatusUpdater_UnmatchingAuthConfigLabels(t *testing.T) {
client := newTestK8sClient(&authConfig)
reconciler := mockStatusUpdaterReconciler(client)

result, err := reconciler.Reconcile(context.Background(), controllerruntime.Request{NamespacedName: resourceName})
result, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: resourceName})

assert.Equal(t, result, ctrl.Result{})
assert.NilError(t, err)
Expand All @@ -110,7 +109,7 @@ func TestAuthConfigStatusUpdater_NotReady(t *testing.T) {
var authConfigCheck api.AuthConfig

// try to reconcile once
result, err = reconciler.Reconcile(context.Background(), controllerruntime.Request{NamespacedName: resourceName})
result, err = reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: resourceName})

assert.Check(t, result.Requeue)
assert.NilError(t, err)
Expand All @@ -120,7 +119,7 @@ func TestAuthConfigStatusUpdater_NotReady(t *testing.T) {
assert.Check(t, !authConfigCheck.Status.Ready())

// try to reconcile again with no change in the status
result, err = reconciler.Reconcile(context.Background(), controllerruntime.Request{NamespacedName: resourceName})
result, err = reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: resourceName})

assert.Check(t, result.Requeue)
assert.NilError(t, err)
Expand All @@ -140,7 +139,7 @@ func TestAuthConfigStatusUpdater_HostNotLinked(t *testing.T) {
reconciler := mockStatusUpdaterReconciler(client)
reconciler.StatusReport.Set(resourceName.String(), api.StatusReasonHostsNotLinked, "one or more hosts are not linked to the resource", []string{"my-api.com"})

result, err := reconciler.Reconcile(context.Background(), controllerruntime.Request{NamespacedName: resourceName})
result, err := reconciler.Reconcile(context.Background(), ctrl.Request{NamespacedName: resourceName})

assert.Check(t, result.Requeue)
assert.NilError(t, err)
Expand Down
14 changes: 7 additions & 7 deletions pkg/auth/credentials.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const (
cookieHeaderNotSetMsg = "the Cookie header is not set"
)

var notFoundErr = fmt.Errorf(credentialNotFoundMsg)
var errNotFound = fmt.Errorf(credentialNotFoundMsg)

// AuthCredentials interface represents the methods needed to fetch credentials from input
type AuthCredentials interface {
Expand Down Expand Up @@ -125,7 +125,7 @@ func (c *AuthCredential) BuildRequestWithCredentials(ctx context.Context, endpoi
func getCredFromCustomHeader(headers map[string]string, keyName string) (string, error) {
cred, ok := headers[strings.ToLower(keyName)]
if !ok {
return "", notFoundErr
return "", errNotFound
}
return cred, nil
}
Expand All @@ -134,19 +134,19 @@ func getCredFromAuthHeader(headers map[string]string, keyName string) (string, e
authHeader, ok := headers["authorization"]

if !ok {
return "", notFoundErr
return "", errNotFound
}
prefix := keyName + " "
if strings.HasPrefix(authHeader, prefix) {
return strings.TrimPrefix(authHeader, prefix), nil
}
return "", notFoundErr
return "", errNotFound
}

func getFromCookieHeader(headers map[string]string, keyName string) (string, error) {
header, ok := headers["cookie"]
if !ok {
return "", notFoundErr
return "", errNotFound
}

for _, part := range strings.Split(header, ";") {
Expand All @@ -156,15 +156,15 @@ func getFromCookieHeader(headers map[string]string, keyName string) (string, err
}
}

return "", notFoundErr
return "", errNotFound
}

func getCredFromQuery(path string, keyName string) (string, error) {
const credValue = "credValue"
regex := regexp.MustCompile("([?&]" + keyName + "=)(?P<" + credValue + ">[^&]*)")
matches := regex.FindStringSubmatch(path)
if len(matches) == 0 {
return "", notFoundErr
return "", errNotFound
}
return matches[regex.SubexpIndex(credValue)], nil
}
18 changes: 9 additions & 9 deletions pkg/auth/credentials_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ import (
)

func TestConstants(t *testing.T) {
assert.Check(t, "custom_header" == inCustomHeader)
assert.Check(t, "authorization_header" == inAuthHeader)
assert.Check(t, "query" == inQuery)
assert.Check(t, "credential not found" == credentialNotFoundMsg)
assert.Check(t, "the credential was not found in the request header" == credentialNotFoundInHeaderMsg)
assert.Check(t, "the credential location is not supported" == credentialLocationNotSupportedMsg)
assert.Check(t, "the Authorization header is not set" == authHeaderNotSetMsg)
assert.Check(t, "the Cookie header is not set" == cookieHeaderNotSetMsg)
assert.Check(t, "Bearer" == defaultKeySelector)
assert.Check(t, inCustomHeader == "custom_header")
assert.Check(t, inAuthHeader == "authorization_header")
assert.Check(t, inQuery == "query")
assert.Check(t, credentialNotFoundMsg == "credential not found")
assert.Check(t, credentialNotFoundInHeaderMsg == "the credential was not found in the request header")
assert.Check(t, credentialLocationNotSupportedMsg == "the credential location is not supported")
assert.Check(t, authHeaderNotSetMsg == "the Authorization header is not set")
assert.Check(t, cookieHeaderNotSetMsg == "the Cookie header is not set")
assert.Check(t, defaultKeySelector == "Bearer")
}

func TestNewAuthCredential(t *testing.T) {
Expand Down
2 changes: 1 addition & 1 deletion pkg/evaluators/authorization/kubernetes_authz.go
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,6 @@ func parseSubjectAccessReviewResult(subjectAccessReview *kubeAuthz.SubjectAccess
if reason == "" {
reason = "unknown reason"
}
return false, fmt.Errorf("Not authorized: %s", reason)
return false, fmt.Errorf("not authorized: %s", reason)
}
}
4 changes: 2 additions & 2 deletions pkg/evaluators/authorization/kubernetes_authz_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ func TestKubernetesAuthzNonResource_Denied(t *testing.T) {
assert.Equal(t, requestData.NonResourceAttributes.Verb, "get")

assert.Check(t, !authorized.(bool))
assert.ErrorContains(t, err, "Not authorized: some-reason")
assert.ErrorContains(t, err, "not authorized: some-reason")
}

func TestKubernetesAuthzResource_Allowed(t *testing.T) {
Expand Down Expand Up @@ -165,7 +165,7 @@ func TestKubernetesAuthzResource_Denied(t *testing.T) {
authorized, err := kubernetesAuth.Call(pipelineMock, context.TODO())

assert.Check(t, !authorized.(bool))
assert.ErrorContains(t, err, "Not authorized: some-reason")
assert.ErrorContains(t, err, "not authorized: some-reason")

client, _ := kubernetesAuth.authorizer.(subjectAccessReviewTestClient)
requestData := client.GetRequest()
Expand Down
6 changes: 3 additions & 3 deletions pkg/evaluators/authorization/opa.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import (
"crypto/sha256"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"net/http"
"regexp"
"strings"
Expand Down Expand Up @@ -176,7 +176,7 @@ func precompilePolicy(ctx context.Context, policyUID, policyRego string, allValu
}

func cleanUpRegoDocument(rego string) string {
r, _ := regexp.Compile("(\\s)*package.*[;\\n]+")
r, _ := regexp.Compile(`(\s)*package.*[;\n]+`)
return r.ReplaceAllString(rego, "")
}

Expand Down Expand Up @@ -218,7 +218,7 @@ func (ext *OPAExternalSource) downloadRegoDataFromUrl() (string, error) {
} else {
defer resp.Body.Close()

body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("unable to read response body: %v", err)
}
Expand Down
2 changes: 1 addition & 1 deletion pkg/evaluators/identity/hmac.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,6 @@ type HMAC struct {
Secret string `yaml:"secret"`
}

func (self *HMAC) Call(pipeline auth.AuthPipeline, ctx context.Context) (interface{}, error) {
func (h *HMAC) Call(pipeline auth.AuthPipeline, ctx context.Context) (interface{}, error) {
return "Authenticated with HMAC", nil // TODO: implement
}
2 changes: 1 addition & 1 deletion pkg/evaluators/identity/kubernetes_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,6 @@ func parseTokenReviewResult(tokenReview *authv1.TokenReview) (interface{}, error
if tokenReviewStatus.Authenticated {
return tokenReviewStatus, nil
} else {
return nil, fmt.Errorf("Not authenticated")
return nil, fmt.Errorf("not authenticated")
}
}
4 changes: 2 additions & 2 deletions pkg/evaluators/identity/kubernetes_auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,7 +145,7 @@ func TestKubernetesTokenReviewUnauthenticatedToken(t *testing.T) {
ret, err := kubernetesAuth.Call(pipelineMock, context.TODO())

assert.Check(t, ret == nil)
assert.Error(t, err, "Not authenticated")
assert.Error(t, err, "not authenticated")
}

func TestKubernetesTokenReviewAudiencesMatch(t *testing.T) {
Expand Down Expand Up @@ -188,5 +188,5 @@ func TestKubernetesTokenReviewAudiencesUnmatch(t *testing.T) {
ret, err := kubernetesAuth.Call(pipelineMock, context.TODO())

assert.Check(t, ret == nil)
assert.Error(t, err, "Not authenticated")
assert.Error(t, err, "not authenticated")
}
2 changes: 1 addition & 1 deletion pkg/evaluators/identity/plain.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ func (p *Plain) Call(pipeline auth.AuthPipeline, ctx context.Context) (interface
if object := pattern.ResolveFor(pipeline.GetAuthorizationJSON()); object != nil {
return object, nil
}
return nil, fmt.Errorf("Could not retrieve identity object or null")
return nil, fmt.Errorf("could not retrieve identity object or null")
}

// impl: AuthCredentials
Expand Down
4 changes: 2 additions & 2 deletions pkg/evaluators/identity/plain_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ func TestPlainCallWithUresolvableObject(t *testing.T) {

plain := &Plain{Pattern: "context.request.http.body.@fromstr"}
id, err := plain.Call(pipelineMock, nil)
assert.ErrorContains(t, err, "Could not retrieve identity object")
assert.ErrorContains(t, err, "could not retrieve identity object")
assert.Check(t, id == nil)
}

Expand All @@ -47,7 +47,7 @@ func TestPlainCallWithInvalidPatttern(t *testing.T) {

plain := &Plain{Pattern: "not a valid json path"}
id, err := plain.Call(pipelineMock, nil)
assert.ErrorContains(t, err, "Could not retrieve identity object")
assert.ErrorContains(t, err, "could not retrieve identity object")
assert.Check(t, id == nil)
}

Expand Down
2 changes: 1 addition & 1 deletion pkg/evaluators/metadata/user_info.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ func (userinfo *UserInfo) Call(pipeline auth.AuthPipeline, parentCtx gocontext.C
resolvedIdentity, _ := pipeline.GetResolvedIdentity()
identityEvaluator, _ := resolvedIdentity.(auth.IdentityConfigEvaluator)
if resolvedOIDC, _ := identityEvaluator.GetOIDC().(*identity.OIDC); resolvedOIDC == nil || resolvedOIDC.Endpoint != oidc.Endpoint {
return nil, fmt.Errorf("Missing identity for OIDC issuer %v. Skipping related UserInfo metadata.", oidc.Endpoint)
return nil, fmt.Errorf("missing identity for oidc issuer %v. skipping related userinfo metadata", oidc.Endpoint)
}

// get access token from input
Expand Down
2 changes: 1 addition & 1 deletion pkg/evaluators/metadata/user_info_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -105,5 +105,5 @@ func TestUserInfoMissingOIDCConfig(t *testing.T) {
ta.pipelineMock.EXPECT().GetResolvedIdentity().Return(ta.idConfEvalMock, nil)

_, err := ta.userInfo.Call(ta.pipelineMock, ta.ctx)
assert.Error(t, err, "Missing identity for OIDC issuer http://127.0.0.1:9002. Skipping related UserInfo metadata.")
assert.Error(t, err, "missing identity for oidc issuer http://127.0.0.1:9002. skipping related userinfo metadata")
}
6 changes: 3 additions & 3 deletions pkg/json/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"encoding/base64"
"encoding/json"
"fmt"
"io/ioutil"
"io"
"mime"
"net/http"
"regexp"
Expand All @@ -21,7 +21,7 @@ const (
operatorExcl = "excl"
operatorRegex = "matches"

unsupportedOperatorErrorMsg = "Unsupported operator for JSON authorization"
unsupportedOperatorErrorMsg = "unsupported operator for json authorization"
)

var (
Expand Down Expand Up @@ -119,7 +119,7 @@ func (rule *JSONPatternMatchingRule) EvaluateFor(jsonData string) (bool, error)
// Pass optionally a pointer to a byte array to get the raw body of the response object written back
func UnmashalJSONResponse(resp *http.Response, v interface{}, b *[]byte) error {
// read response body
body, err := ioutil.ReadAll(resp.Body)
body, err := io.ReadAll(resp.Body)
if err != nil {
return fmt.Errorf("unable to read response body: %v", err)
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/service/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ package service
import (
"encoding/json"
"encoding/pem"
"io/ioutil"
"io"
"net/http"
"net/url"
"strings"
Expand Down Expand Up @@ -123,7 +123,7 @@ func (a *AuthService) ServeHTTP(resp http.ResponseWriter, req *http.Request) {
return
}

if payload, err = ioutil.ReadAll(http.MaxBytesReader(resp, req.Body, a.MaxHttpRequestBodySize)); err != nil {
if payload, err = io.ReadAll(http.MaxBytesReader(resp, req.Body, a.MaxHttpRequestBodySize)); err != nil {
switch err.Error() {
case "http: request body too large":
logger.Info(HTTP_MESSAGE_413)
Expand Down
4 changes: 2 additions & 2 deletions pkg/service/health.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,12 @@ import (
type HealthService struct{}

// Check performs a health of the gRPC service
func (self *HealthService) Check(ctx context.Context, in *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
func (hs *HealthService) Check(ctx context.Context, in *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) {
log.Printf("[HealthService] Check()")
return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil
}

// Watch is for streaming health-check (not yet implemented)
func (self *HealthService) Watch(in *healthpb.HealthCheckRequest, srv healthpb.Health_WatchServer) error {
func (hs *HealthService) Watch(in *healthpb.HealthCheckRequest, srv healthpb.Health_WatchServer) error {
return status.Error(codes.Unimplemented, "Watch is not implemented")
}
2 changes: 1 addition & 1 deletion pkg/service/oidc.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ func (o *OidcService) ServeHTTP(writer http.ResponseWriter, req *http.Request) {
responseBody, err = wristband.JWKS()
default:
statusCode = http.StatusNotFound
err = fmt.Errorf("Not found")
err = fmt.Errorf("not found")
}

var pathMetric string
Expand Down
Loading