-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathopaserver_bundle_client.go
73 lines (62 loc) · 2.01 KB
/
opaserver_bundle_client.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
package openpolicyagent
import (
"bytes"
"fmt"
"io"
"strings"
"mime/multipart"
"net/url"
"github.com/hexa-org/policy-mapper/pkg/hexapolicy"
"github.com/hexa-org/policy-mapper/providers/openpolicyagent/compressionsupport"
)
/*
OpaBundleClient is intended to use the OPA Policy API to directly update and retrieve Policy bundles from an OPA Policy Server instance.
Note: typically OPA servers are configured to poll for updates at some configured common retrieval point. Usage of this bundle is mainly for local
development purposes.
*/
type OpaBundleClient struct {
OpaServerUrl string
HttpClient HTTPClient
}
type OpaDataResponse struct {
Result []hexapolicy.PolicyInfo `json:"result"`
}
const PolicyDataPath string = "/v1/data/policies"
func (b *OpaBundleClient) GetDataFromBundle(_ string) ([]byte, error) {
opaUrl, err := url.Parse(b.OpaServerUrl)
if err != nil {
return nil, err
}
policyDataUrl := opaUrl.JoinPath(PolicyDataPath)
get, getErr := b.HttpClient.Get(policyDataUrl.String())
if getErr != nil {
return nil, getErr
}
defer get.Body.Close()
var resBytes []byte
if strings.EqualFold("application/json", get.Header.Get("Content-Type")) {
resBytes, err = io.ReadAll(get.Body)
if err != nil {
return nil, fmt.Errorf("unable to read application/json body: %w", err)
}
} else {
resBytes, err = compressionsupport.UnGzip(get.Body)
if err != nil {
return nil, fmt.Errorf("unable to ungzip: %w", err)
}
}
return resBytes, nil
}
// todo - ignoring errors for the moment while spiking
func (b *OpaBundleClient) PostBundle(bundle []byte) (int, error) {
// todo - Log out the errors at minimum.
buf := new(bytes.Buffer)
writer := multipart.NewWriter(buf)
formFile, _ := writer.CreateFormFile("bundle", "bundle.tar.gz")
_, _ = formFile.Write(bundle)
_ = writer.Close()
parse, _ := url.Parse(b.OpaServerUrl)
contentType := writer.FormDataContentType()
resp, err := b.HttpClient.Post(fmt.Sprintf("%s://%s/bundles", parse.Scheme, parse.Host), contentType, buf)
return resp.StatusCode, err
}