Skip to content

Commit

Permalink
Implement tests alongside an improved fix for #368
Browse files Browse the repository at this point in the history
  • Loading branch information
Joel Cressy committed May 13, 2019
1 parent 680bfef commit b5c5f48
Show file tree
Hide file tree
Showing 2 changed files with 144 additions and 4 deletions.
19 changes: 15 additions & 4 deletions vault/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,11 @@ func Provider() terraform.ResourceProvider {
DefaultFunc: schema.EnvDefaultFunc("VAULT_NAMESPACE", ""),
Description: "The namespace to use. Available only for Vault Enterprise",
},
"token_namespace": {
Type: schema.TypeString,
Optional: true,
Description: "The namespace where the provided vault token was created, if different from the value in 'namespace'",
},
},

ConfigureFunc: providerConfigure,
Expand Down Expand Up @@ -237,6 +242,15 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) {
return nil, errors.New("no vault token found")
}

// If 'token_namespace' provided, set client namespace to use it for child token creation, else use 'namespace'
tokenNamespace := d.Get("token_namespace").(string)
namespace := d.Get("namespace").(string)
if tokenNamespace != "" {
client.SetNamespace(tokenNamespace)
} else if namespace != "" {
client.SetNamespace(namespace)
}

// In order to enforce our relatively-short lease TTL, we derive a
// temporary child token that inherits all of the policies of the
// token we were given but expires after max_lease_ttl_seconds.
Expand Down Expand Up @@ -267,12 +281,9 @@ func providerConfigure(d *schema.ResourceData) (interface{}, error) {

log.Printf("[INFO] Using Vault token with the following policies: %s", strings.Join(policies, ", "))

namespace := d.Get("namespace").(string)
client.SetToken(childToken)
if namespace != "" {
client.SetNamespace(namespace)
}

client.SetToken(childToken)

return client, nil
}
129 changes: 129 additions & 0 deletions vault/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package vault

import (
"fmt"
"github.com/hashicorp/terraform/helper/acctest"
"io/ioutil"
"os"
"path"
Expand Down Expand Up @@ -115,6 +116,134 @@ const tokenHelperScript = `
echo "helper-token"
`

func TestAccNamespaceProviderConfigure(t *testing.T) {
isEnterprise := os.Getenv("TF_ACC_ENTERPRISE")
if isEnterprise == "" {
t.Skip("TF_ACC_ENTERPRISE is not set, test is applicable only for Enterprise version of Vault")
}

rootProvider := Provider().(*schema.Provider)
rootProviderResource := &schema.Resource{
Schema: rootProvider.Schema,
}
rootProviderData := rootProviderResource.TestResourceData()
providerConfigure(rootProviderData)

namespacePath := acctest.RandomWithPrefix("test-namespace") + "/"

//Create a test namespace and make sure it stays there
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: map[string]terraform.ResourceProvider{
"vault": rootProvider,
},
Steps: []resource.TestStep{
{
Config: testNamespaceConfig(namespacePath),
Check: testNamespaceCheckAttrs(),
},
},
})

nsProvider := Provider().(*schema.Provider)
nsProviderResource := &schema.Resource{
Schema: nsProvider.Schema,
}
nsProviderData := nsProviderResource.TestResourceData()
// We auth to the root namespace, but will configure resources in the test namespace
nsProviderData.Set("token_namespace", "/")
nsProviderData.Set("namespace", namespacePath)
providerConfigure(nsProviderData)

// Create a policy with sudo permissions and an orphaned periodic token within the test namespace
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: map[string]terraform.ResourceProvider{
"vault": nsProvider,
},
Steps: []resource.TestStep{
{
Config: testResourceAdminPeriodicOrphanTokenConfig_basic(),
Check: testResourceAdminPeriodicOrphanTokenCheckAttrs(namespacePath, t),
},
},
})

}

func testResourceAdminPeriodicOrphanTokenConfig_basic() string {
return `
resource "vault_policy" "test" {
name = "admin"
policy = <<EOT
path "*" { capabilities = ["create", "read", "update", "delete", "list", "sudo"] }
EOT
}
resource "vault_token" "test" {
policies = [ "${vault_policy.test.name}" ]
ttl = "60s"
}`
}

func testResourceAdminPeriodicOrphanTokenCheckAttrs(namespacePath string, t *testing.T) resource.TestCheckFunc {
return func(s *terraform.State) error {
//Check that it made the policy
resourceState := s.Modules[0].Resources["vault_policy.test"]
if resourceState == nil {
return fmt.Errorf("resource not found in state")
}

instanceState := resourceState.Primary
if instanceState == nil {
return fmt.Errorf("resource has no primary instance")
}

//Check that it made the token and read it back

tokenResourceState := s.Modules[0].Resources["vault_token.test"]
if tokenResourceState == nil {
return fmt.Errorf("token resource not found in state")
}

tokenInstanceState := tokenResourceState.Primary
if tokenInstanceState == nil {
return fmt.Errorf("token resource has no primary instance")
}

vaultToken := tokenResourceState.Primary.Attributes["token"]

ns2Provider := Provider().(*schema.Provider)
ns2ProviderResource := &schema.Resource{
Schema: ns2Provider.Schema,
}
ns2ProviderData := ns2ProviderResource.TestResourceData()
//We use the token created above to auth against the namespace (instead of root)
ns2ProviderData.Set("token_namespace", namespacePath)
ns2ProviderData.Set("namespace", namespacePath)
ns2ProviderData.Set("token", vaultToken)
providerConfigure(ns2ProviderData)

ns2Path := acctest.RandomWithPrefix("test-namespace2") + "/"

//Finally test that you can do stuff with the new token by creating a sub namespace
resource.Test(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Providers: map[string]terraform.ResourceProvider{
"vault": ns2Provider,
},
Steps: []resource.TestStep{
{
Config: testNamespaceConfig(ns2Path),
Check: testNamespaceCheckAttrs(),
},
},
})

return nil
}
}

func TestAccProviderToken(t *testing.T) {
// This is an acceptance test because it requires filesystem and env var
// changes that could interfere with other Vault operations.
Expand Down

0 comments on commit b5c5f48

Please sign in to comment.