open-vault/api/sys_policy.go

112 lines
2.3 KiB
Go
Raw Normal View History

2015-04-02 00:59:41 +00:00
package api
import (
"context"
"fmt"
)
2015-04-02 00:59:41 +00:00
func (c *Sys) ListPolicies() ([]string, error) {
r := c.c.NewRequest("GET", "/v1/sys/policy")
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
resp, err := c.c.RawRequestWithContext(ctx, r)
2015-04-02 00:59:41 +00:00
if err != nil {
return nil, err
}
defer resp.Body.Close()
var result map[string]interface{}
err = resp.DecodeJSON(&result)
2016-08-08 20:00:31 +00:00
if err != nil {
return nil, err
}
var ok bool
if _, ok = result["policies"]; !ok {
return nil, fmt.Errorf("policies not found in response")
2016-08-08 20:00:31 +00:00
}
listRaw := result["policies"].([]interface{})
var policies []string
for _, val := range listRaw {
policies = append(policies, val.(string))
2016-08-08 20:00:31 +00:00
}
return policies, err
2015-04-02 00:59:41 +00:00
}
func (c *Sys) GetPolicy(name string) (string, error) {
r := c.c.NewRequest("GET", fmt.Sprintf("/v1/sys/policy/%s", name))
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
resp, err := c.c.RawRequestWithContext(ctx, r)
2015-07-13 09:20:00 +00:00
if resp != nil {
defer resp.Body.Close()
if resp.StatusCode == 404 {
return "", nil
}
}
2015-04-02 00:59:41 +00:00
if err != nil {
return "", err
}
var result map[string]interface{}
err = resp.DecodeJSON(&result)
2016-08-08 20:00:31 +00:00
if err != nil {
return "", err
}
2017-10-23 20:52:56 +00:00
if rulesRaw, ok := result["rules"]; ok {
return rulesRaw.(string), nil
}
if policyRaw, ok := result["policy"]; ok {
return policyRaw.(string), nil
2016-08-08 20:00:31 +00:00
}
2017-10-23 20:52:56 +00:00
return "", fmt.Errorf("no policy found in response")
2015-04-02 00:59:41 +00:00
}
func (c *Sys) PutPolicy(name, rules string) error {
body := map[string]string{
"rules": rules,
}
r := c.c.NewRequest("PUT", fmt.Sprintf("/v1/sys/policy/%s", name))
if err := r.SetJSONBody(body); err != nil {
return err
}
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
resp, err := c.c.RawRequestWithContext(ctx, r)
2015-04-02 00:59:41 +00:00
if err != nil {
return err
}
defer resp.Body.Close()
return nil
}
func (c *Sys) DeletePolicy(name string) error {
r := c.c.NewRequest("DELETE", fmt.Sprintf("/v1/sys/policy/%s", name))
ctx, cancelFunc := context.WithCancel(context.Background())
defer cancelFunc()
resp, err := c.c.RawRequestWithContext(ctx, r)
2015-04-02 00:59:41 +00:00
if err == nil {
defer resp.Body.Close()
}
return err
}
type getPoliciesResp struct {
Rules string `json:"rules"`
}
type listPoliciesResp struct {
Policies []string `json:"policies"`
}