github.com/blixtra/nomad@v0.7.2-0.20171221000451-da9a1d7bb050/nomad/mock/acl.go (about) 1 package mock 2 3 import ( 4 "fmt" 5 6 "github.com/hashicorp/nomad/nomad/structs" 7 "github.com/mitchellh/go-testing-interface" 8 "github.com/stretchr/testify/assert" 9 ) 10 11 // StateStore defines the methods required from state.StateStore but avoids a 12 // circular dependency. 13 type StateStore interface { 14 UpsertACLPolicies(index uint64, policies []*structs.ACLPolicy) error 15 UpsertACLTokens(index uint64, tokens []*structs.ACLToken) error 16 } 17 18 // NamespacePolicy is a helper for generating the policy hcl for a given 19 // namepsace. Either policy or capabilities may be nil but not both. 20 func NamespacePolicy(namespace string, policy string, capabilities []string) string { 21 policyHCL := fmt.Sprintf("namespace %q {", namespace) 22 if policy != "" { 23 policyHCL += fmt.Sprintf("\n\tpolicy = %q", policy) 24 } 25 if len(capabilities) != 0 { 26 policyHCL += fmt.Sprintf("\n\tcapabilities = %q", capabilities) 27 } 28 policyHCL += "\n}" 29 return policyHCL 30 } 31 32 // AgentPolicy is a helper for generating the hcl for a given agent policy. 33 func AgentPolicy(policy string) string { 34 return fmt.Sprintf("agent {\n\tpolicy = %q\n}\n", policy) 35 } 36 37 // NodePolicy is a helper for generating the hcl for a given node policy. 38 func NodePolicy(policy string) string { 39 return fmt.Sprintf("node {\n\tpolicy = %q\n}\n", policy) 40 } 41 42 // QuotaPolicy is a helper for generating the hcl for a given quota policy. 43 func QuotaPolicy(policy string) string { 44 return fmt.Sprintf("quota {\n\tpolicy = %q\n}\n", policy) 45 } 46 47 // CreatePolicy creates a policy with the given name and rule. 48 func CreatePolicy(t testing.T, state StateStore, index uint64, name, rule string) { 49 t.Helper() 50 51 // Create the ACLPolicy 52 policy := &structs.ACLPolicy{ 53 Name: name, 54 Rules: rule, 55 } 56 policy.SetHash() 57 assert.Nil(t, state.UpsertACLPolicies(index, []*structs.ACLPolicy{policy})) 58 } 59 60 // CreateToken creates a local, client token for the given policies 61 func CreateToken(t testing.T, state StateStore, index uint64, policies []string) *structs.ACLToken { 62 t.Helper() 63 64 // Create the ACLToken 65 token := ACLToken() 66 token.Policies = policies 67 token.SetHash() 68 assert.Nil(t, state.UpsertACLTokens(index, []*structs.ACLToken{token})) 69 return token 70 } 71 72 // CreatePolicyAndToken creates a policy and then returns a token configured for 73 // just that policy. CreatePolicyAndToken uses the given index and index+1. 74 func CreatePolicyAndToken(t testing.T, state StateStore, index uint64, name, rule string) *structs.ACLToken { 75 CreatePolicy(t, state, index, name, rule) 76 return CreateToken(t, state, index+1, []string{name}) 77 }