Skip to content

Commit

Permalink
Merge pull request #25 from zanecodes/vault-skip-verify
Browse files Browse the repository at this point in the history
Add vault_skip_verify attribute to provider configuration
  • Loading branch information
rickardgranberg authored Oct 18, 2023
2 parents 665de8e + 45ab3cb commit f664e79
Show file tree
Hide file tree
Showing 7 changed files with 176 additions and 22 deletions.
1 change: 1 addition & 0 deletions docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ provider "vaultoperator" {
- `kube_config` (Block List) (see [below for nested schema](#nestedblock--kube_config))
- `request_headers` (Map of String)
- `vault_addr` (String) Vault instance URL
- `vault_skip_verify` (Boolean) Disable TLS certificate verification
- `vault_url` (String, Deprecated) Vault instance URL

<a id="nestedblock--kube_config"></a>
Expand Down
4 changes: 2 additions & 2 deletions internal/provider/data_source_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ data "%[2]s" "test" {
`, provider, resInit)

func TestAccDataSourceInit(t *testing.T) {
startVault(t)
startVault(t, false)

resource.UnitTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Expand All @@ -34,7 +34,7 @@ func TestAccDataSourceInit(t *testing.T) {
}

func TestAccDataSourceInitComplete(t *testing.T) {
startVault(t)
startVault(t, false)

resource.UnitTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Expand Down
98 changes: 94 additions & 4 deletions internal/provider/helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,110 @@ package provider
import (
"bufio"
"bytes"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"crypto/x509/pkix"
"encoding/pem"
"fmt"
"io"
"math/big"
"net"
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"testing"
"text/template"
"time"
)

func startVault(t *testing.T) {
func startVault(t *testing.T, enableTLS bool) {
t.Helper()

configPath, err := filepath.Abs("../../vault.hcl")
tempDir, err := os.MkdirTemp("", "vaultoperator-*")
if err != nil {
t.Fatal(err)
}
defer os.RemoveAll(tempDir)

keyPath := filepath.Join(tempDir, "key")
certPath := filepath.Join(tempDir, "cert")
configPath := filepath.Join(tempDir, "vault.hcl")
disableTLS := "1"
protocol := "http"

if enableTLS {
disableTLS = "0"
protocol = "https"

key, err := rsa.GenerateKey(rand.Reader, 2048)
if err != nil {
t.Fatal(err)
}

keyFile, err := os.Create(keyPath)
if err != nil {
t.Fatal(err)
}
defer keyFile.Close()

err = pem.Encode(keyFile, &pem.Block{Type: "RSA PRIVATE KEY", Bytes: x509.MarshalPKCS1PrivateKey(key)})
if err != nil {
t.Fatal(err)
}

certTemplate := x509.Certificate{
SerialNumber: big.NewInt(1),
Subject: pkix.Name{CommonName: "localhost"},
NotBefore: time.Now(),
NotAfter: time.Now().AddDate(1, 0, 0),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
BasicConstraintsValid: true,
IPAddresses: []net.IP{net.ParseIP("127.0.0.1")},
}

certBytes, err := x509.CreateCertificate(rand.Reader, &certTemplate, &certTemplate, &key.PublicKey, key)
if err != nil {
t.Fatal(err)
}

certFile, err := os.Create(certPath)
if err != nil {
t.Fatal(err)
}
defer certFile.Close()

err = pem.Encode(certFile, &pem.Block{Type: "CERTIFICATE", Bytes: certBytes})
if err != nil {
t.Fatal(err)
}
}

configTemplate, err := template.ParseFiles("../../vault.hcl")
if err != nil {
t.Fatal(err)
}

config := struct {
CertFile string
KeyFile string
DisableTLS string
}{
CertFile: certPath,
KeyFile: keyPath,
DisableTLS: disableTLS,
}

configFile, err := os.Create(configPath)
if err != nil {
t.Fatal(err)
}
defer configFile.Close()

err = configTemplate.Execute(configFile, config)
if err != nil {
t.Fatal(err)
}
Expand All @@ -42,7 +132,7 @@ func startVault(t *testing.T) {

for scanner.Scan() {
if match := clusterAddress.FindStringSubmatch(scanner.Text()); match != nil {
clusterHost, clusterPort, err := net.SplitHostPort(match[1])
_, clusterPort, err := net.SplitHostPort(match[1])
if err != nil {
t.Fatal(err)
}
Expand All @@ -52,7 +142,7 @@ func startVault(t *testing.T) {
t.Fatal(err)
}

t.Setenv("VAULT_ADDR", fmt.Sprintf("http://%s:%d", clusterHost, port-1))
t.Setenv("VAULT_ADDR", fmt.Sprintf("%s://localhost:%d", protocol, port-1))
}

if vaultStarted.MatchString(scanner.Text()) {
Expand Down
46 changes: 33 additions & 13 deletions internal/provider/provider.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,18 +16,20 @@ import (
)

const (
envVaultAddr = "VAULT_ADDR"
provider = "vaultoperator"
resInit = provider + "_init"
argVaultUrl = "vault_url"
argVaultAddr = "vault_addr"
argRequestHeaders = "request_headers"
argKubeConfig = "kube_config"
argKubeConfigPath = "path"
argNameSpace = "namespace"
argServiceName = "service"
argLocalPort = "local_port"
argRemotePort = "remote_port"
envVaultAddr = "VAULT_ADDR"
envVaultSkipVerify = "VAULT_SKIP_VERIFY"
provider = "vaultoperator"
resInit = provider + "_init"
argVaultUrl = "vault_url"
argVaultAddr = "vault_addr"
argVaultSkipVerify = "vault_skip_verify"
argRequestHeaders = "request_headers"
argKubeConfig = "kube_config"
argKubeConfigPath = "path"
argNameSpace = "namespace"
argServiceName = "service"
argLocalPort = "local_port"
argRemotePort = "remote_port"
)

func init() {
Expand Down Expand Up @@ -96,6 +98,12 @@ func providerSchema() map[string]*schema.Schema {
Optional: true,
Description: "Vault instance URL",
},
argVaultSkipVerify: {
Type: schema.TypeBool,
Optional: true,
DefaultFunc: schema.EnvDefaultFunc(envVaultSkipVerify, false),
Description: "Disable TLS certificate verification",
},
argRequestHeaders: {
Type: schema.TypeMap,
Optional: true,
Expand Down Expand Up @@ -252,7 +260,19 @@ func configure(version string, p *schema.Provider) func(context.Context, *schema
return nil, diag.Errorf("argument '%s' is required, or set VAULT_ADDR environment variable", argVaultUrl)
}

if c, err := api.NewClient(&api.Config{Address: a.url}); err != nil {
apiConfig := api.DefaultConfig()
apiConfig.Address = a.url

err := apiConfig.ConfigureTLS(&api.TLSConfig{
Insecure: d.Get(argVaultSkipVerify).(bool),
})

if err != nil {
logError("failed to configure Vault TLS: %v", err)
return nil, diag.FromErr(err)
}

if c, err := api.NewClient(apiConfig); err != nil {
logError("failed to create Vault API client: %v", err)
return nil, diag.FromErr(err)
} else {
Expand Down
40 changes: 40 additions & 0 deletions internal/provider/provider_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,46 @@ func TestProvider_configure_url_env(t *testing.T) {
}
}

func TestProvider_configure_skip_verify(t *testing.T) {
ctx := context.TODO()

rc := terraform.NewResourceConfigRaw(map[string]interface{}{argVaultUrl: "https://localhost:8200", argVaultSkipVerify: true})
p := New("dev")()
diags := p.Configure(ctx, rc)
if diags.HasError() {
t.Fatal(diags)
}
}
func TestProvider_configure_skip_verify_env(t *testing.T) {
ctx := context.TODO()
addr, addrExists := os.LookupEnv(envVaultAddr)
skipVerify, skipVerifyExists := os.LookupEnv(envVaultSkipVerify)
resetEnv := func() {
if addrExists {
os.Setenv(envVaultAddr, addr)
} else {
os.Unsetenv(envVaultAddr)
}

if skipVerifyExists {
os.Setenv(envVaultSkipVerify, skipVerify)
} else {
os.Unsetenv(envVaultSkipVerify)
}
}
defer resetEnv()

os.Setenv(envVaultAddr, "https://localhost:8200")
os.Setenv(envVaultSkipVerify, "true")

rc := terraform.NewResourceConfigRaw(map[string]interface{}{})
p := New("dev")()
diags := p.Configure(ctx, rc)
if diags.HasError() {
t.Fatal(diags)
}
}

func testAccPreCheck(t *testing.T) {
// You can add code here to run prior to any test case execution, for example assertions
// about the appropriate environment variables being set are common to see in a pre-check
Expand Down
5 changes: 3 additions & 2 deletions internal/provider/resource_init_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
var testAccResourceInitVar = fmt.Sprintf("%[1]s.test", resInit)
var testAccResourceInit = fmt.Sprintf(`
provider "%[1]s" {
vault_skip_verify = true
}
resource "%[2]s" "test" {
Expand All @@ -22,7 +23,7 @@ resource "%[2]s" "test" {
`, provider, resInit)

func TestAccResourceInit(t *testing.T) {
startVault(t)
startVault(t, true)

resource.UnitTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Expand Down Expand Up @@ -115,7 +116,7 @@ resource "%[2]s" "test" {
publicKeys[5],
)

startVault(t)
startVault(t, false)

resource.UnitTest(t, resource.TestCase{
PreCheck: func() { testAccPreCheck(t) },
Expand Down
4 changes: 3 additions & 1 deletion vault.hcl
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
disable_mlock = true

listener "tcp" {
tls_disable = 1
address = "[::]:0"
tls_disable = "{{ .DisableTLS }}"
tls_cert_file = "{{ .CertFile }}"
tls_key_file = "{{ .KeyFile }}"
}

storage "inmem" {}

0 comments on commit f664e79

Please sign in to comment.