vault: Adding policy parsing

This commit is contained in:
Armon Dadgar 2015-03-17 15:53:29 -07:00
parent 88c168507f
commit ddab671bf4
2 changed files with 102 additions and 0 deletions

56
vault/policy.go Normal file
View file

@ -0,0 +1,56 @@
package vault
import (
"fmt"
"github.com/hashicorp/hcl"
)
const (
PathPolicyDeny = "deny"
PathPolicyRead = "read"
PathPolicyWrite = "write"
PathPolicySudo = "sudo"
)
// Policy is used to represent the policy specified by
// an ACL configuration.
type Policy struct {
Name string `hcl:"name"`
Paths []*PathPolicy `hcl:"path,expand"`
}
// PathPolicy represents a policy for a path in the namespace
type PathPolicy struct {
Prefix string `hcl:",key"`
Policy string
}
// Parse is used to parse the specified ACL rules into an
// intermediary set of policies, before being compiled into
// the ACL
func Parse(rules string) (*Policy, error) {
// Decode the rules
p := &Policy{}
if err := hcl.Decode(p, rules); err != nil {
return nil, fmt.Errorf("Failed to parse ACL rules: %v", err)
}
// Validate a name is given
if p.Name == "" {
return nil, fmt.Errorf("Policy name is missing")
}
// Validate the path policy
for _, pp := range p.Paths {
switch pp.Policy {
case PathPolicyDeny:
case PathPolicyRead:
case PathPolicyWrite:
case PathPolicySudo:
default:
return nil, fmt.Errorf("Invalid path policy: %#v", pp)
}
}
return p, nil
}

46
vault/policy_test.go Normal file
View file

@ -0,0 +1,46 @@
package vault
import (
"reflect"
"testing"
)
func TestPolicy_Parse(t *testing.T) {
p, err := Parse(rawPolicy)
if err != nil {
t.Fatalf("err: %v", err)
}
if p.Name != "dev" {
t.Fatalf("bad: %#v", p)
}
expect := []*PathPolicy{
&PathPolicy{"", "deny"},
&PathPolicy{"stage/", "sudo"},
&PathPolicy{"prod/", "read"},
}
if !reflect.DeepEqual(p.Paths, expect) {
t.Fatalf("bad: %#v", p)
}
}
var rawPolicy = `
# Developer policy
name = "dev"
# Deny all paths by default
path "" {
policy = "deny"
}
# Allow full access to staging
path "stage/" {
policy = "sudo"
}
# Limited read privilege to production
path "prod/" {
policy = "read"
}
`