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