Add additional logging for OPA connections (#7982)

This commit is contained in:
Harshavardhana
2019-07-27 20:03:25 -07:00
committed by Nitish Tiwari
parent e871e27562
commit 94c88890b8
3 changed files with 45 additions and 13 deletions

View File

@@ -37,6 +37,23 @@ type OpaArgs struct {
// Validate - validate opa configuration params.
func (a *OpaArgs) Validate() error {
req, err := http.NewRequest("POST", a.URL.String(), bytes.NewReader([]byte("")))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
if a.AuthToken != "" {
req.Header.Set("Authorization", a.AuthToken)
}
client := &http.Client{Transport: a.Transport}
resp, err := client.Do(req)
if err != nil {
return err
}
defer a.CloseRespFn(resp.Body)
return nil
}
@@ -92,9 +109,9 @@ func NewOpa(args OpaArgs) *Opa {
}
// IsAllowed - checks given policy args is allowed to continue the REST API.
func (o *Opa) IsAllowed(args Args) bool {
func (o *Opa) IsAllowed(args Args) (bool, error) {
if o == nil {
return false
return false, nil
}
// OPA input
@@ -103,12 +120,12 @@ func (o *Opa) IsAllowed(args Args) bool {
inputBytes, err := json.Marshal(body)
if err != nil {
return false
return false, err
}
req, err := http.NewRequest("POST", o.args.URL.String(), bytes.NewReader(inputBytes))
if err != nil {
return false
return false, err
}
req.Header.Set("Content-Type", "application/json")
@@ -118,14 +135,14 @@ func (o *Opa) IsAllowed(args Args) bool {
resp, err := o.client.Do(req)
if err != nil {
return false
return false, err
}
defer o.args.CloseRespFn(resp.Body)
// Read the body to be saved later.
opaRespBytes, err := ioutil.ReadAll(resp.Body)
if err != nil {
return false
return false, err
}
// Handle large OPA responses when OPA URL is of
@@ -149,9 +166,9 @@ func (o *Opa) IsAllowed(args Args) bool {
respBody.Seek(0, 0)
var resultAllow opaResultAllow
if err = json.NewDecoder(respBody).Decode(&resultAllow); err != nil {
return false
return false, err
}
return resultAllow.Result.Allow
return resultAllow.Result.Allow, nil
}
return result.Result
return result.Result, nil
}