Skip to content

Commit

Permalink
Fix lints
Browse files Browse the repository at this point in the history
  • Loading branch information
SuperSandro2000 authored and notque committed Mar 21, 2024
1 parent e65d5e7 commit 463d8ba
Show file tree
Hide file tree
Showing 17 changed files with 57 additions and 66 deletions.
3 changes: 0 additions & 3 deletions go.mod
Expand Up @@ -20,7 +20,6 @@ require (

require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/catenacyber/perfsprint v0.7.1 // indirect
github.com/cespare/xxhash/v2 v2.2.0 // indirect
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
github.com/fsnotify/fsnotify v1.7.0 // indirect
Expand All @@ -43,10 +42,8 @@ require (
github.com/subosito/gotenv v1.6.0 // indirect
go.uber.org/multierr v1.11.0 // indirect
golang.org/x/exp v0.0.0-20240318143956-a85f2c67cd81 // indirect
golang.org/x/mod v0.16.0 // indirect
golang.org/x/sys v0.18.0 // indirect
golang.org/x/text v0.14.0 // indirect
golang.org/x/tools v0.19.0 // indirect
google.golang.org/protobuf v1.33.0 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
Expand Down
6 changes: 0 additions & 6 deletions go.sum
@@ -1,7 +1,5 @@
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
github.com/beorn7/perks v1.0.1/go.mod h1:G2ZrVWU2WbWT9wwq4/hrbKbnv/1ERSJQ0ibhJ6rlkpw=
github.com/catenacyber/perfsprint v0.7.1 h1:PGW5G/Kxn+YrN04cRAZKC+ZuvlVwolYMrIyyTJ/rMmc=
github.com/catenacyber/perfsprint v0.7.1/go.mod h1:/wclWYompEyjUD2FuIIDVKNkqz7IgBIWXIH3V0Zol50=
github.com/cespare/xxhash/v2 v2.2.0 h1:DC2CZ1Ep5Y4k3ZQ899DldepgrayRUGE6BBZ/cd9Cj44=
github.com/cespare/xxhash/v2 v2.2.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
github.com/databus23/goslo.policy v0.0.0-20210929125152-81bf2876dbdb h1:8JB2G8t3o1iCL8vCzssUj2Nn2qjqSab2/G3xXhvkpPQ=
Expand Down Expand Up @@ -96,8 +94,6 @@ go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN8
golang.org/x/crypto v0.0.0-20220829220503-c86fa9a7ed90/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
golang.org/x/exp v0.0.0-20240318143956-a85f2c67cd81 h1:6R2FC06FonbXQ8pK11/PDFY6N6LWlf9KlzibaCapmqc=
golang.org/x/exp v0.0.0-20240318143956-a85f2c67cd81/go.mod h1:CQ1k9gNrJ50XIzaKCRR2hssIjF07kZFEiieALBM/ARQ=
golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/net v0.0.0-20211112202133-69e39bad7dc2/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/sys v0.0.0-20201119102817-f84b799fce68/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20210423082822-04245dca01da/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
Expand All @@ -109,8 +105,6 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
google.golang.org/protobuf v1.33.0 h1:uNO2rsAINq/JlFpSdYEKIZ0uKD/R9cpdv0T+yoGwGmI=
google.golang.org/protobuf v1.33.0/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
Expand Down
4 changes: 2 additions & 2 deletions internal/api/api_test.go
Expand Up @@ -35,7 +35,7 @@ import (
)

func setupTest(t *testing.T) http.Handler {
//load test policy (where everything is allowed)
// load test policy (where everything is allowed)
policyBytes, err := os.ReadFile("../test/policy.json")
if err != nil {
t.Fatal(err)
Expand All @@ -51,7 +51,7 @@ func setupTest(t *testing.T) http.Handler {
}
viper.Set("hermes.PolicyEnforcer", policyEnforcer)

//create test driver with the domains and projects from start-data.sql
// create test driver with the domains and projects from start-data.sql
keystone := identity.Mock{}
storageInterface := storage.Mock{}

Expand Down
16 changes: 8 additions & 8 deletions internal/api/events.go
Expand Up @@ -59,7 +59,7 @@ func (p *v1Provider) ListEvents(res http.ResponseWriter, req *http.Request) {
limit, _ := strconv.ParseUint(req.FormValue("limit"), 10, 32) //nolint:errcheck

// Parse the sort query string
//slice of a struct, key and direction.
// slice of a struct, key and direction.

sortSpec := []hermes.FieldOrder{}
validSortTopics := map[string]bool{
Expand All @@ -86,7 +86,7 @@ func (p *v1Provider) ListEvents(res http.ResponseWriter, req *http.Request) {
if sortParam != "" {
for _, sortElement := range strings.Split(sortParam, ",") {
keyVal := strings.SplitN(sortElement, ":", 2)
//`time`, `source`, `resource_type`, `resource_name`, and `event_type`.
// `time`, `source`, `resource_type`, `resource_name`, and `event_type`.
sortfield := keyVal[0]
if !validSortTopics[sortfield] {
err := fmt.Errorf("not a valid topic: %s, valid topics: %v", sortfield, reflect.ValueOf(validSortTopics).MapKeys())
Expand Down Expand Up @@ -223,8 +223,8 @@ func (p *v1Provider) GetEventDetails(res http.ResponseWriter, req *http.Request)
}
// Sanitize user input
eventID := mux.Vars(req)["event_id"]
eventID = strings.Replace(eventID, "\n", "", -1)
eventID = strings.Replace(eventID, "\r", "", -1)
eventID = strings.ReplaceAll(eventID, "\n", "")
eventID = strings.ReplaceAll(eventID, "\r", "")

// Validate if eventID is a valid UUID
if _, err := uuid.Parse(eventID); err != nil {
Expand Down Expand Up @@ -261,8 +261,8 @@ func (p *v1Provider) GetAttributes(res http.ResponseWriter, req *http.Request) {

// Handle QueryParams, Sanitize user input
queryName := mux.Vars(req)["attribute_name"]
queryName = strings.Replace(queryName, "\n", "", -1)
queryName = strings.Replace(queryName, "\r", "", -1)
queryName = strings.ReplaceAll(queryName, "\n", "")
queryName = strings.ReplaceAll(queryName, "\r", "")
if queryName == "" {
logg.Debug("attribute_name empty")
return
Expand Down Expand Up @@ -313,8 +313,8 @@ func getIndexID(token *Token, r *http.Request, w http.ResponseWriter) (string, e

// Sanitize user input
projectid := r.FormValue("project_id")
projectid = strings.Replace(projectid, "\n", "", -1)
projectid = strings.Replace(projectid, "\r", "", -1)
projectid = strings.ReplaceAll(projectid, "\n", "")
projectid = strings.ReplaceAll(projectid, "\r", "")
// When the projectid argument is defined, check for the cluster_viewer rule
if v := projectid; v != "" {
if !token.Require(w, "cluster_viewer") {
Expand Down
10 changes: 5 additions & 5 deletions internal/api/server.go
Expand Up @@ -42,10 +42,10 @@ func Server(keystone identity.Identity, storageInterface storage.Storage) error
fmt.Println("API")
mainRouter := setupRouter(keystone, storageInterface)

//start HTTP server
// start HTTP server
listenaddress := viper.GetString("API.ListenAddress")
logg.Info("listening on %s", listenaddress)
//enable cors support
// enable cors support
c := cors.New(cors.Options{
AllowedHeaders: []string{"X-Auth-Token", "Content-Type", "Accept"},
AllowedMethods: []string{"GET", "HEAD"},
Expand All @@ -59,12 +59,12 @@ func Server(keystone identity.Identity, storageInterface storage.Storage) error

func setupRouter(keystone identity.Identity, storageInterface storage.Storage) http.Handler {
mainRouter := mux.NewRouter()
//hook up the v1 API (this code is structured so that a newer API version can
//be added easily later)
// hook up the v1 API (this code is structured so that a newer API version can
// be added easily later)
v1Router, v1VersionData := NewV1Handler(keystone, storageInterface)
mainRouter.PathPrefix("/v1/").Handler(v1Router)

//add the version advertisement that lists all available API versions
// add the version advertisement that lists all available API versions
mainRouter.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
allVersions := struct {
Versions []VersionData `json:"versions"`
Expand Down
6 changes: 3 additions & 3 deletions internal/api/token.go
Expand Up @@ -28,6 +28,7 @@ import (
policy "github.com/databus23/goslo.policy"
"github.com/gophercloud/gophercloud"
"github.com/gorilla/mux"
"github.com/sapcc/go-bits/errext"
"github.com/sapcc/go-bits/logg"
"github.com/spf13/viper"
)
Expand All @@ -53,8 +54,7 @@ func (p *v1Provider) CheckToken(r *http.Request) *Token {
t.context, t.err = p.keystone.ValidateToken(str)
if t.err != nil {
logg.Debug("Error connection to identity server %s", t.err)
switch t.err.(type) { //nolint:errorlint
case gophercloud.ErrDefault404:
if _, ok := errext.As[gophercloud.ErrDefault404](t.err); ok { // nolint: errcheck // type checking
t.err = errors.New("X-Auth-Token is invalid or expired")
}
}
Expand Down Expand Up @@ -82,7 +82,7 @@ func (t *Token) Require(w http.ResponseWriter, rule string) bool {
}

if os.Getenv("DEBUG") == "1" {
t.context.Logger = log.Printf //or any other function with the same signature
t.context.Logger = log.Printf // or any other function with the same signature
}
if !t.enforcer.Enforce(rule, t.context) {
http.Error(w, "Forbidden", http.StatusForbidden)
Expand Down
2 changes: 1 addition & 1 deletion internal/api/util.go
Expand Up @@ -51,7 +51,7 @@ type versionLinkData struct {
func ReturnJSON(w http.ResponseWriter, code int, data any) {
payload, err := json.MarshalIndent(&data, "", " ")
// Replaces & symbols properly in json within urls due to Elasticsearch
payload = bytes.Replace(payload, []byte("\\u0026"), []byte("&"), -1)
payload = bytes.ReplaceAll(payload, []byte("\\u0026"), []byte("&"))
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
Expand Down
2 changes: 1 addition & 1 deletion internal/hermes/events.go
Expand Up @@ -74,7 +74,7 @@ type EventFilter struct {
// FieldOrder is an embedded struct for Event Filtering
type FieldOrder struct {
Fieldname string
Order string //asc or desc
Order string // asc or desc
}

// AttributeFilter maps to the filtering allowed by the API for Attributes
Expand Down
6 changes: 3 additions & 3 deletions internal/identity/interface.go
Expand Up @@ -28,9 +28,9 @@ import (
// token checking of API users. Because it is an interface, the real implementation
// can be mocked away in unit tests.
type Identity interface {
//Return the main gophercloud client from which the respective service
//clients can be derived. For Mock drivers, this returns nil, so test code
//should be prepared to handle a nil Client() where appropriate.
// Return the main gophercloud client from which the respective service
// clients can be derived. For Mock drivers, this returns nil, so test code
// should be prepared to handle a nil Client() where appropriate.
Client() (*gophercloud.ProviderClient, error)
AuthOptions() *gophercloud.AuthOptions
/********** requests to Keystone **********/
Expand Down
16 changes: 8 additions & 8 deletions internal/identity/keystone.go
Expand Up @@ -75,7 +75,7 @@ func (d Keystone) keystoneClient() (*gophercloud.ServiceClient, error) {
}
if providerClient == nil {
var err error
//providerClient, err = openstack.NewClient(viper.GetString("Keystone.auth_url"))
// providerClient, err = openstack.NewClient(viper.GetString("Keystone.auth_url"))
opts := d.AuthOptions()
providerClient, err = openstack.AuthenticatedClient(*opts)
if err != nil {
Expand Down Expand Up @@ -115,11 +115,11 @@ func (d Keystone) ValidateToken(token string) (policy.Context, error) {

response := tokens.Get(client, token)
if response.Err != nil {
//this includes 4xx responses, so after this point, we can be sure that the token is valid
// this includes 4xx responses, so after this point, we can be sure that the token is valid
return policy.Context{}, response.Err
}

//use a custom token struct instead of tMap.Token which is way incomplete
// use a custom token struct instead of tMap.Token which is way incomplete
var tokenData keystoneToken
err = response.ExtractInto(&tokenData)
if err != nil {
Expand All @@ -137,10 +137,10 @@ func (d Keystone) Authenticate(credentials *gophercloud.AuthOptions) (policy.Con
}
response := tokens.Create(client, credentials)
if response.Err != nil {
//this includes 4xx responses, so after this point, we can be sure that the token is valid
// this includes 4xx responses, so after this point, we can be sure that the token is valid
return policy.Context{}, response.Err
}
//use a custom token struct instead of tMap.Token which is way incomplete
// use a custom token struct instead of tMap.Token which is way incomplete
var tokenData keystoneToken
err = response.ExtractInto(&tokenData)
if err != nil {
Expand Down Expand Up @@ -400,10 +400,10 @@ func (t *keystoneToken) ToContext() policy.Context {
// to fetch the initial token on startup.
func (d Keystone) RefreshToken() error {
//NOTE: This function is very similar to v3auth() in
//gophercloud/openstack/client.go, but with a few differences:
// gophercloud/openstack/client.go, but with a few differences:
//
//1. thread-safe token renewal
//2. proper support for cross-domain scoping
// 1. thread-safe token renewal
// 2. proper support for cross-domain scoping

logg.Debug("Getting service user Identity token...")

Expand Down
2 changes: 1 addition & 1 deletion internal/identity/mock.go
Expand Up @@ -28,7 +28,7 @@ import (
// Mock TODO: emnpty struct? Is there a better way?
type Mock struct{}

//keystoneClient for mocking connection - unused re:golangci
// keystoneClient for mocking connection - unused re:golangci
// func (d Mock) keystoneClient() (*gophercloud.ServiceClient, error) {
// return nil, nil
// }
Expand Down
14 changes: 7 additions & 7 deletions internal/policy/policy_test.go
Expand Up @@ -53,7 +53,7 @@ func Test_Policy_AuditViewerTrue(t *testing.T) {
},
// Auth will only have one entry
Auth: map[string]string{
//"domain_id": "ca1b267e149d4e44bf53d28d1c8d6bc9",
// "domain_id": "ca1b267e149d4e44bf53d28d1c8d6bc9",
"project_id": "7a09c05926ec452ca7992af4aa03c31d",
},
Request: map[string]string{
Expand All @@ -72,7 +72,7 @@ func Test_Policy_UnknownRoleFalse(t *testing.T) {
},
Auth: map[string]string{
"domain_id": "ca1b267e149d4e44bf53d28d1c8d6bc9",
//"project_id": "7a09c05926ec452ca7992af4aa03c31d",
// "project_id": "7a09c05926ec452ca7992af4aa03c31d",
},
Request: map[string]string{
"domain_id": "ca1b267e149d4e44bf53d28d1c8d6bc9",
Expand Down Expand Up @@ -150,17 +150,17 @@ func TestPolicy(t *testing.T) {
if enforcer.Enforce("non_existent_rule", serviceContext) {
t.Error("Non existent rule should not pass")
}
//if !enforcer.Enforce("cloud_admin", adminContext) {
// if !enforcer.Enforce("cloud_admin", adminContext) {
// t.Error("cloud_admin check should pass")
//}
//if !enforcer.Enforce("service_admin_or_owner", adminContext) {
// if !enforcer.Enforce("service_admin_or_owner", adminContext) {
// t.Error("service_admin_or_owner should pass for admin")
//}
//if !enforcer.Enforce("service_admin_or_owner", userContext) {
// if !enforcer.Enforce("service_admin_or_owner", userContext) {
// t.Error("service_admin_or_owner should pass for owner")
//}
//userContext.Request["user_id"] = "u-2"
//if enforcer.Enforce("service_admin_or_owner", userContext) {
// userContext.Request["user_id"] = "u-2"
// if enforcer.Enforce("service_admin_or_owner", userContext) {
// t.Error("service_admin_or_owner should pass for non owning user")
//}
}
8 changes: 4 additions & 4 deletions internal/storage/elasticsearch.go
Expand Up @@ -129,7 +129,7 @@ func (es ElasticSearch) GetEvents(filter *EventFilter, tenantID string) ([]*cadf
query := elastic.NewBoolQuery()

if filter.ObserverType != "" {
//logg.Debug("Filtering on ObserverType %s", filter.ObserverType)
// logg.Debug("Filtering on ObserverType %s", filter.ObserverType)
query = FilterQuery(filter.ObserverType, esFieldMapping["observer_type"], query)
}
if filter.TargetType != "" {
Expand Down Expand Up @@ -202,7 +202,7 @@ func (es ElasticSearch) GetEvents(filter *EventFilter, tenantID string) ([]*cadf
From(int(filter.Offset)).Size(int(filter.Limit))

searchResult, err := esSearch.Do(context.Background()) // execute
//errcheck already within an errchecek, this is for additional detail.
// errcheck already within an errchecek, this is for additional detail.
if err != nil {
e, _ := err.(*elastic.Error) //nolint:errcheck,errorlint
errdetails, _ := json.Marshal(e.Details) //nolint:errcheck
Expand All @@ -212,7 +212,7 @@ func (es ElasticSearch) GetEvents(filter *EventFilter, tenantID string) ([]*cadf

logg.Debug("Got %d hits", searchResult.TotalHits())

//Construct EventDetail array from search results
// Construct EventDetail array from search results
var events []*cadf.Event
for _, hit := range searchResult.Hits.Hits {
var de cadf.Event
Expand Down Expand Up @@ -276,7 +276,7 @@ func (es ElasticSearch) GetAttributes(filter *AttributeFilter, tenantID string)

esSearch := es.client().Search().Index(index).Size(int(filter.Limit)).Aggregation("attributes", queryAgg)
searchResult, err := esSearch.Do(context.Background())
//errcheck already within an errcheck, this is for additional detail.
// errcheck already within an errcheck, this is for additional detail.
if err != nil {
e, _ := err.(*elastic.Error) //nolint:errcheck,errorlint
errdetails, _ := json.Marshal(e.Details) //nolint:errcheck
Expand Down
2 changes: 1 addition & 1 deletion internal/storage/interface.go
Expand Up @@ -73,7 +73,7 @@ type Storage interface {
// FieldOrder maps the sort Fieldname and Order
type FieldOrder struct {
Fieldname string
Order string //asc or desc
Order string // asc or desc
}

// EventFilter is similar to hermes.EventFilter, but using IDs instead of names
Expand Down
12 changes: 6 additions & 6 deletions internal/test/http.go
Expand Up @@ -36,11 +36,11 @@ import (
type APIRequest struct {
Method string
Path string
RequestJSON any //if non-nil, will be encoded as JSON
RequestJSON any // if non-nil, will be encoded as JSON
ExpectStatusCode int
ExpectBody *string //raw content (not a file path)
ExpectJSON string //path to JSON file
ExpectFile string //path to arbitrary file
ExpectBody *string // raw content (not a file path)
ExpectJSON string // path to JSON file
ExpectFile string // path to arbitrary file
}

// Check performs the HTTP request described by this APIRequest against the
Expand Down Expand Up @@ -101,8 +101,8 @@ func (r APIRequest) Check(t *testing.T, handler http.Handler) {
}

func (r APIRequest) compareBodyToFixture(t *testing.T, fixturePath string, data []byte) {
//write actual content to file to make it easy to copy the computed result over
//to the fixture path when a new test is added or an existing one is modified
// write actual content to file to make it easy to copy the computed result over
// to the fixture path when a new test is added or an existing one is modified
fixturePathAbs, err := filepath.Abs(fixturePath)
if err != nil {
t.Fatal(err)
Expand Down
12 changes: 6 additions & 6 deletions internal/util/hacks.go
Expand Up @@ -26,12 +26,12 @@ import (
)

func init() {
//I have some trouble getting hermes to connect to our staging OpenStack
//through mitmproxy (which is very useful for development and debugging) when
//TLS certificate verification is enabled. Therefore, allow to turn it off
//with an env variable. (It's very important that this is not the standard
//"DEBUG" variable. "DEBUG" is meant to be useful for production systems,
//where you definitely don't want to turn off certificate verification.)
// I have some trouble getting hermes to connect to our staging OpenStack
// through mitmproxy (which is very useful for development and debugging) when
// TLS certificate verification is enabled. Therefore, allow to turn it off
// with an env variable. (It's very important that this is not the standard
// "DEBUG" variable. "DEBUG" is meant to be useful for production systems,
// where you definitely don't want to turn off certificate verification.)
if os.Getenv("HERMES_INSECURE") == "1" {
tlsConf := &tls.Config{
InsecureSkipVerify: true, //nolint:gosec // intentional usage of InsecureSkipVerify
Expand Down

0 comments on commit 463d8ba

Please sign in to comment.