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

session renewal support for both json and html #57

Merged
merged 2 commits into from
Feb 9, 2024
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
79 changes: 62 additions & 17 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@
log "github.com/akutz/gournal"
"github.com/sirupsen/logrus"

"github.com/PuerkitoBio/goquery"
"github.com/dell/goisilon/api/json"
)

Expand All @@ -46,7 +47,7 @@
defaultVolumesPathPermissions = "0777"
defaultIgnoreUnresolvableHosts = false
headerISISessToken = "Cookie"
headerISICSRFToken = "X-CSRF-Token"

Check failure on line 50 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

G101: Potential hardcoded credentials (gosec)
headerISIReferer = "Referer"
isiSessCsrfToken = "Set-Cookie"
authTypeBasic = 0
Expand Down Expand Up @@ -167,9 +168,9 @@
type VerboseType uint

const (
Verbose_High VerboseType = 0

Check warning on line 171 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

var-naming: don't use underscores in Go names; const Verbose_High should be VerboseHigh (revive)
Verbose_Medium VerboseType = 1

Check warning on line 172 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

var-naming: don't use underscores in Go names; const Verbose_Medium should be VerboseMedium (revive)
Verbose_Low VerboseType = 2

Check warning on line 173 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

var-naming: don't use underscores in Go names; const Verbose_Low should be VerboseLow (revive)
)

type apiVerResponse struct {
Expand All @@ -189,6 +190,12 @@
Err []Error `json:"errors"`
}

// HTMLError is an HTML response with one or more errors.
type HTMLError struct {
StatusCode int
Message string
}

// ClientOptions are options for the API client.
type ClientOptions struct {
// Insecure is a flag that indicates whether or not to supress SSL errors.
Expand Down Expand Up @@ -259,7 +266,7 @@
if opts.Insecure {
c.http.Transport = &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,

Check failure on line 269 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

G402: TLS InsecureSkipVerify set true. (gosec)
},
}
} else {
Expand All @@ -268,7 +275,7 @@
return nil, err
}
c.http.Transport = &http.Transport{
TLSClientConfig: &tls.Config{

Check failure on line 278 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

G402: TLS MinVersion too low. (gosec)
RootCAs: pool,
InsecureSkipVerify: false,
},
Expand Down Expand Up @@ -401,7 +408,7 @@
return err
}
default:
return parseJSONError(res)
return parseJSONHTMLError(res)
}

return nil
Expand Down Expand Up @@ -573,6 +580,10 @@
return err.Err[0].Message
}

func (err *HTMLError) Error() string {
return err.Message
}

func (c *client) SetAuthToken(cookie string) {
c.sessionCredentials.sessionCookies = cookie
}
Expand All @@ -597,18 +608,43 @@
return c.sessionCredentials.referer
}

func parseJSONError(r *http.Response) error {
jsonError := &JSONError{}
if err := json.NewDecoder(r.Body).Decode(jsonError); err != nil {
return err
}
func parseJSONHTMLError(r *http.Response) error {
// check the content type of the response
contentType := r.Header.Get("Content-Type")
switch {
case strings.HasPrefix(contentType, "application/json"):
jsonErr := &JSONError{}
// decode JSON error response
err := json.NewDecoder(r.Body).Decode(jsonErr)
if err != nil {
return err
}
jsonErr.StatusCode = r.StatusCode
if len(jsonErr.Err) > 0 && jsonErr.Err[0].Message == "" {
jsonErr.Err[0].Message = r.Status
}
return jsonErr
case strings.HasPrefix(contentType, "text/html"):
htmlError := &HTMLError{}
// decode HTML error response
doc, err := goquery.NewDocumentFromReader(r.Body)
if err != nil {
return err
}
htmlError.StatusCode = r.StatusCode

jsonError.StatusCode = r.StatusCode
if jsonError.Err[0].Message == "" {
jsonError.Err[0].Message = r.Status
}
if h1 := doc.Find("h1"); h1 != nil {
htmlError.Message = h1.Text()
}

return jsonError
if strings.TrimSpace(htmlError.Message) == "" && doc.Find("title") != nil {
htmlError.Message = doc.Find("title").Text()
nitesh3108 marked this conversation as resolved.
Show resolved Hide resolved
}
return htmlError
default:
// Unexpected content type
return fmt.Errorf("unexpected content type: %s", contentType)
}
}

// Authenticate make a REST API call [/session/1/session] to PowerScale to authenticate the given credentials.
Expand All @@ -619,7 +655,7 @@
data := &setupConnection{Services: []string{"platform", "namespace"}, Username: username, Password: password}
resp, _, err := c.DoAndGetResponseBody(ctx, http.MethodPost, "/session/1/session", "", nil, headers, data)
if err != nil {
return errors.New(fmt.Sprintf("Authentication error: %v", err))

Check warning on line 658 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

errorf: should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) (revive)
}

if resp != nil {
Expand All @@ -638,18 +674,18 @@
case resp.StatusCode == 401:
{
log.Debug(ctx, "Response Code %v", resp)
return errors.New(fmt.Sprintf("Authentication failed. Unable to login to PowerScale. Verify username and password."))

Check warning on line 677 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

errorf: should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) (revive)
}
default:
return errors.New(fmt.Sprintf("Authenticate error. Response:"))

Check warning on line 680 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

errorf: should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) (revive)
}

headerRes := strings.Join(resp.Header.Values(isiSessCsrfToken), " ")

startIndex, endIndex, matchStrLen := FetchValueIndexForKey(headerRes, "isisessid=", ";")
if startIndex < 0 || endIndex < 0 {
return errors.New(fmt.Sprintf("Session ID not retrieved"))

Check warning on line 687 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

errorf: should replace errors.New(fmt.Sprintf(...)) with fmt.Errorf(...) (revive)
} else {

Check warning on line 688 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

indent-error-flow: if block ends with a return statement, so drop this else and outdent its block (revive)
c.SetAuthToken(headerRes[startIndex : startIndex+matchStrLen+endIndex])
}

Expand Down Expand Up @@ -678,22 +714,31 @@
log.Debug(ctx, "Execution successful on Method: %v, URI: %v", method, uri)
return nil
}
// check if we need to Re-authenticate
if e, ok := err.(*JSONError); ok {

switch e := err.(type) {
case *JSONError:
if e.StatusCode == 401 {
log.Debug(ctx, "Authentication failed. Trying to re-authenticate")
// Authenticate then try again
if err := c.authenticate(ctx, c.username, c.password, c.hostname); err != nil {
return fmt.Errorf("authentication failure due to: %v", err)
}
return c.DoWithHeaders(ctx, method, uri, id, params, headers, body, resp)
} else {

Check warning on line 726 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

indent-error-flow: if block ends with a return statement, so drop this else and outdent its block (revive)
log.Error(ctx, "Error in response. Method:%s URI:%s Error: %v JSON Error: %+v", method, uri, err, e)
}
} else {
log.Error(ctx, "Error is not a type of \"*JSONError\". Error:", err)
case *HTMLError:
if e.StatusCode == 401 {
log.Debug(ctx, "Authentication failed. Trying to re-authenticate")
if err := c.authenticate(ctx, c.username, c.password, c.hostname); err != nil {
return fmt.Errorf("authentication failure due to: %v", err)
}
return c.DoWithHeaders(ctx, method, uri, id, params, headers, body, resp)
} else {

Check warning on line 736 in api/api.go

View workflow job for this annotation

GitHub Actions / golangci-lint

indent-error-flow: if block ends with a return statement, so drop this else and outdent its block (revive)
log.Error(ctx, "Error in response. Method:%s URI:%s Error: %v HTML Error: %+v", method, uri, err, e)
}
default:
log.Error(ctx, "Error is not a type of \"*JSONError or *HTMLError\". Error:", err)
}

return err
}

Expand Down
17 changes: 10 additions & 7 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,17 @@ module github.com/dell/goisilon
go 1.21

require (
github.com/akutz/gournal v0.5.0
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.8.4
github.com/PuerkitoBio/goquery v1.8.1
github.com/akutz/gournal v0.5.0
github.com/sirupsen/logrus v1.9.3
github.com/stretchr/testify v1.8.4
)

require (
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/sys v0.7.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
github.com/andybalholm/cascadia v1.3.1 // indirect
github.com/davecgh/go-spew v1.1.1 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
golang.org/x/net v0.7.0 // indirect
golang.org/x/sys v0.7.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
)
37 changes: 36 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
@@ -1,5 +1,9 @@
github.com/PuerkitoBio/goquery v1.8.1 h1:uQxhNlArOIdbrH1tr0UXwdVFgDcZDrZVdcpygAcwmWM=
github.com/PuerkitoBio/goquery v1.8.1/go.mod h1:Q8ICL1kNUJ2sXGoAhPGUdYDJvgQgHzJsnnd3H7Ho5jQ=
github.com/akutz/gournal v0.5.0 h1:ELlKqTTp9dmaaadDvO19YxUmdMghYuSi23AxoSL/g98=
github.com/akutz/gournal v0.5.0/go.mod h1:w7Ucz8IOvtgsEL1321IY8bIUoASU/khBjAy/L6doMWc=
github.com/andybalholm/cascadia v1.3.1 h1:nhxRkql1kdYCc8Snf7D5/D3spOX+dBgjA6u8x004T2c=
github.com/andybalholm/cascadia v1.3.1/go.mod h1:R4bJ1UQfqADjvDa4P6HZHLh/3OxWWEqc0Sk8XGwHqvA=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
Expand All @@ -11,11 +15,42 @@ github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
github.com/yuin/goldmark v1.4.13/go.mod h1:6yULJ656Px+3vBD8DxQVa3kxgyrAnzto9xy5taEt/CY=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20210921155107-089bfa567519/go.mod h1:GvvjBRRGRdwPK5ydBHafDWAxML/pGHZbMvKqRZ5+Abc=
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
golang.org/x/net v0.0.0-20190620200207-3b0461eec859/go.mod h1:z5CRVTTTmAJ677TzLLGU+0bjPO0LkuOLi4/5GtJWs/s=
golang.org/x/net v0.0.0-20210226172049-e18ecbb05110/go.mod h1:m0MpNAwzfU5UDzcl9v0D8zg8gWTRqZa9RBIspLL5mdg=
golang.org/x/net v0.0.0-20210916014120-12bc252f5db8/go.mod h1:9nx3DQGgdP8bBQD5qxJ1jj9UTztislL4KSBs9R2vV5Y=
golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug+ECip1KBveYUHfp+8e9klMJ9c=
golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g=
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20220722155255-886fb9371eb4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
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=
golang.org/x/sys v0.0.0-20210615035016-665e8c7367d1/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.7.0 h1:3jlCCIQZPdOYu1h8BkNvLz8Kgwtae2cagcG/VamtZRU=
golang.org/x/sys v0.7.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtnZ6UAqBI28+e2cm9otk0dWdXHAEo=
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
Loading