├── cmd ├── out │ └── out.go ├── check │ └── check.go └── in │ └── in.go ├── pkg └── resource │ ├── models │ ├── request.go │ ├── response.go │ ├── version.go │ ├── metadata.go │ └── source.go │ ├── validate.go │ ├── auth.go │ └── vault.go ├── go.mod ├── examples └── pipeline.yml ├── test ├── resource_suite_test.go ├── vault_test.go ├── in_test.go ├── check_test.go └── fakes │ └── fake_vault.go ├── Makefile ├── README.md ├── go.sum └── LICENSE /cmd/out/out.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | func main() { 8 | fmt.Println("[]") 9 | } 10 | -------------------------------------------------------------------------------- /pkg/resource/models/request.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | // Request - the request 4 | type Request struct { 5 | Source Source `json:"source"` 6 | Version Version `json:"version"` 7 | } 8 | -------------------------------------------------------------------------------- /pkg/resource/models/response.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | // Response - the response 4 | type Response struct { 5 | Metadata Metadata `json:"metadata"` 6 | Version Version `json:"version"` 7 | } 8 | -------------------------------------------------------------------------------- /pkg/resource/models/version.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | // Version - the version of the resource 4 | type Version struct { 5 | // Path - the path to the secret in vault 6 | Path string `json:"path"` 7 | // Version - the version of the resource. 8 | Version string `json:"version"` 9 | } 10 | -------------------------------------------------------------------------------- /pkg/resource/models/metadata.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | // MetadataKvP - for any available information from the resource 4 | type MetadataKvP struct { 5 | Key string `json:"key"` 6 | Value string `json:"value"` 7 | } 8 | 9 | // Metadata - metadata kvps 10 | type Metadata []MetadataKvP 11 | -------------------------------------------------------------------------------- /go.mod: -------------------------------------------------------------------------------- 1 | module github.com/comcast/concourse-vault-resource 2 | 3 | require ( 4 | github.com/golang/snappy v0.0.1 // indirect 5 | github.com/hashicorp/go-cleanhttp v0.5.1 // indirect 6 | github.com/hashicorp/go-retryablehttp v0.5.3 // indirect 7 | github.com/hashicorp/go-rootcerts v1.0.0 // indirect 8 | github.com/hashicorp/go-sockaddr v1.0.2 // indirect 9 | github.com/hashicorp/hcl v1.0.0 // indirect 10 | github.com/hashicorp/vault v1.1.0 11 | github.com/mitchellh/mapstructure v1.1.2 // indirect 12 | github.com/onsi/ginkgo v1.8.0 13 | github.com/onsi/gomega v1.5.0 14 | github.com/pierrec/lz4 v2.0.5+incompatible // indirect 15 | github.com/rs/zerolog v1.13.0 16 | github.com/ryanuber/go-glob v1.0.0 // indirect 17 | golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 // indirect 18 | gopkg.in/yaml.v2 v2.2.2 19 | ) 20 | -------------------------------------------------------------------------------- /cmd/check/check.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "os" 6 | 7 | "github.com/rs/zerolog" 8 | 9 | "github.com/comcast/concourse-vault-resource/pkg/resource" 10 | "github.com/comcast/concourse-vault-resource/pkg/resource/models" 11 | ) 12 | 13 | func main() { 14 | logger := zerolog.New(os.Stderr).With().Timestamp().Logger() 15 | zerolog.TimeFieldFormat = "" 16 | zerolog.SetGlobalLevel(zerolog.InfoLevel) 17 | 18 | var request models.Request 19 | if err := json.NewDecoder(os.Stdin).Decode(&request); err != nil { 20 | logger.Fatal().Err(err). 21 | Msg("error reading from stdin") 22 | } 23 | 24 | vault, err := resource.New("vault", request, logger) 25 | if err != nil { 26 | logger.Fatal().Err(err).Msg("error creating resource client") 27 | } 28 | 29 | if err := json.NewEncoder(os.Stdout).Encode(vault.Check()); err != nil { 30 | logger.Fatal().Err(err). 31 | Msg("writing response") 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /examples/pipeline.yml: -------------------------------------------------------------------------------- 1 | resource_types: 2 | - name: vault 3 | type: docker-image 4 | source: 5 | repository: registry:5000/shellfu/concourse-vault-resource 6 | tag: latest 7 | insecure_registries: [ "registry:5000" ] 8 | 9 | resources: 10 | - name: vault-test 11 | type: vault 12 | source: 13 | debug: true 14 | format: yaml 15 | sanitize: true 16 | upcase: false 17 | vault_addr: https://vault.example.com:8200 18 | vault_insecure: true 19 | vault_token: {{token}} 20 | role_name: {{role_name}} 21 | vault_paths: 22 | # KV1 Engine Test 23 | secret/foo: -1 24 | # KV2 Engine Test 25 | kv2/data/foo: 2 26 | kv2/data/bar: -1 27 | 28 | jobs: 29 | - name: vault 30 | plan: 31 | - get: vault-test 32 | trigger: true 33 | - task: show-result 34 | config: 35 | inputs: 36 | - name: vault-test 37 | platform: linux 38 | image_resource: 39 | type: docker-image 40 | source: {repository: busybox} 41 | run: 42 | path: /bin/ls 43 | args: 44 | - ./vault-test/secrets 45 | -------------------------------------------------------------------------------- /pkg/resource/validate.go: -------------------------------------------------------------------------------- 1 | package resource 2 | 3 | import ( 4 | "errors" 5 | "os" 6 | "strings" 7 | 8 | "github.com/comcast/concourse-vault-resource/pkg/resource/models" 9 | ) 10 | 11 | // validate - validates the resource configuration 12 | func validate(config models.Request) (models.Request, error) { 13 | if len(config.Source.VaultAddr) <= 0 { 14 | config.Source.VaultAddr = os.Getenv("VAULT_ADDR") 15 | if len(config.Source.VaultAddr) <= 0 { 16 | return config, errors.New("required argument vault_addr was not provided") 17 | } 18 | } 19 | 20 | if len(config.Source.VaultPaths) <= 0 { 21 | return config, errors.New("required argument vault_paths was not provided") 22 | } 23 | 24 | if len(config.Source.Format) <= 0 { 25 | config.Source.Format = "json" 26 | } 27 | 28 | if config.Source.Retries <= 0 { 29 | config.Source.Retries = 3 30 | } 31 | 32 | if !strings.Contains(config.Source.Format, "json") && 33 | !strings.Contains(config.Source.Format, "yaml") { 34 | return config, errors.New("format provided is not supported. supported output formats are : \"json\" or \"yaml\"") 35 | } 36 | 37 | if len(config.Source.VaultToken) <= 0 && len(config.Source.SecretID) <= 0 { 38 | config.Source.VaultToken = os.Getenv("VAULT_TOKEN") 39 | if len(config.Source.VaultToken) <= 0 { 40 | return config, errors.New("vault_token was not provided") 41 | } 42 | } 43 | 44 | return config, nil 45 | } 46 | -------------------------------------------------------------------------------- /cmd/in/in.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "encoding/json" 5 | "fmt" 6 | "math/rand" 7 | "os" 8 | "time" 9 | 10 | "github.com/rs/zerolog" 11 | 12 | "github.com/comcast/concourse-vault-resource/pkg/resource" 13 | "github.com/comcast/concourse-vault-resource/pkg/resource/models" 14 | ) 15 | 16 | func main() { 17 | logger := zerolog.New(os.Stderr).With().Timestamp().Logger() 18 | 19 | zerolog.TimeFieldFormat = "" 20 | zerolog.SetGlobalLevel(zerolog.InfoLevel) 21 | 22 | var request models.Request 23 | if err := json.NewDecoder(os.Stdin).Decode(&request); err != nil { 24 | logger.Fatal().Err(err). 25 | Msg("error reading from stdin") 26 | } 27 | 28 | rand.Seed(time.Now().UTC().UnixNano()) 29 | version := request.Version.Version 30 | if len(request.Version.Version) <= 0 { 31 | version = fmt.Sprintf("%d", rand.Intn(100)) 32 | } 33 | 34 | response := models.Response{ 35 | Metadata: nil, 36 | Version: models.Version{ 37 | Version: version, 38 | }, 39 | } 40 | 41 | // first argument on stdin is the working directory 42 | vault, err := resource.New(os.Args[1], request, logger) 43 | if err != nil { 44 | logger.Fatal().Err(err). 45 | Msg("error creating resource client") 46 | } 47 | 48 | err = vault.In() 49 | if err != nil { 50 | logger.Fatal().Err(err). 51 | Msg("error running file for write") 52 | } 53 | 54 | if err := json.NewEncoder(os.Stdout).Encode(response); err != nil { 55 | logger.Fatal().Err(err). 56 | Msg("writing response") 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /pkg/resource/models/source.go: -------------------------------------------------------------------------------- 1 | package models 2 | 3 | // Source - source configuration for the resource 4 | type Source struct { 5 | // VaultPaths - the path(s) to the secrets in vault. 6 | VaultPaths map[string]int `json:"vault_paths"` 7 | 8 | // Format - the desired output format. Supported formats are yaml or json. 9 | Format string `json:"format"` 10 | 11 | // Prefix - a desired prefix to prepend to a secret key. 12 | Prefix string `json:"prefix"` 13 | 14 | // RoleID - the role_id for approle authentication. 15 | RoleID string `json:"role_id"` 16 | 17 | // RoleName - the role_name for approle authentication. 18 | RoleName string `json:"role_name"` 19 | 20 | // SecretID - the secret_id for approle authentication. 21 | SecretID string `json:"secret_id"` 22 | 23 | // VaultAddr - the address to the vault server. 24 | VaultAddr string `json:"vault_addr"` 25 | 26 | // VaultToken - the token to use to authenticate to vault. 27 | VaultToken string `json:"vault_token"` 28 | 29 | // Retries - the amount of times to try to read a secret from vault. 30 | Retries int `json:"retries"` 31 | 32 | // Debug - enable debug logging. 33 | Debug bool `json:"debug"` 34 | 35 | // Sanitize - convert dashes and dots to underscores in vault keys. 36 | Sanitize bool `json:"sanitize"` 37 | 38 | // Upcase - conver the vault keys to uppercase. 39 | Upcase bool `json:"upcase"` 40 | 41 | // VaultInsecure - connect the the vault server with insecure. 42 | VaultInsecure bool `json:"vault_insecure"` 43 | } 44 | -------------------------------------------------------------------------------- /test/resource_suite_test.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "fmt" 5 | "io" 6 | "os" 7 | "os/exec" 8 | "testing" 9 | 10 | . "github.com/onsi/ginkgo" 11 | . "github.com/onsi/gomega" 12 | 13 | "github.com/onsi/gomega/gexec" 14 | ) 15 | 16 | var ( 17 | checkPath string 18 | inPath string 19 | vaultAddr string 20 | vaultToken string 21 | ) 22 | 23 | func TestResource(t *testing.T) { 24 | RegisterFailHandler(Fail) 25 | RunSpecs(t, "Resource Suite") 26 | } 27 | 28 | var _ = BeforeSuite(func() { 29 | var err error 30 | 31 | By("Getting VAULT_ADDR from environment variables") 32 | vaultAddr = os.Getenv("VAULT_ADDR") 33 | Expect(vaultAddr).NotTo(BeEmpty(), "$VAULT_ADDR must be provided") 34 | 35 | By("Getting VAULT_TOKEN from environment variables") 36 | vaultToken = os.Getenv("VAULT_TOKEN") 37 | Expect(vaultAddr).NotTo(BeEmpty(), "$VAULT_TOKEN must be provided") 38 | 39 | By("Compiling check binary") 40 | checkPath, err = gexec.Build("github.com/comcast/concourse-vault-resource/cmd/check", "-race") 41 | Expect(err).NotTo(HaveOccurred()) 42 | 43 | By("Compiling in binary") 44 | inPath, err = gexec.Build("github.com/comcast/concourse-vault-resource/cmd/in", "-race") 45 | Expect(err).NotTo(HaveOccurred()) 46 | }) 47 | 48 | var _ = AfterSuite(func() { 49 | gexec.CleanupBuildArtifacts() 50 | }) 51 | 52 | func run(command *exec.Cmd, stdinContents []byte) *gexec.Session { 53 | fmt.Fprintf(GinkgoWriter, "input: %s\n", stdinContents) 54 | 55 | stdin, err := command.StdinPipe() 56 | Expect(err).ShouldNot(HaveOccurred()) 57 | 58 | session, err := gexec.Start(command, GinkgoWriter, GinkgoWriter) 59 | Expect(err).NotTo(HaveOccurred()) 60 | 61 | _, err = io.WriteString(stdin, string(stdinContents)) 62 | Expect(err).ShouldNot(HaveOccurred()) 63 | 64 | err = stdin.Close() 65 | Expect(err).ShouldNot(HaveOccurred()) 66 | 67 | return session 68 | } 69 | -------------------------------------------------------------------------------- /test/vault_test.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "bytes" 5 | "encoding/json" 6 | 7 | . "github.com/onsi/ginkgo" 8 | . "github.com/onsi/gomega" 9 | 10 | "github.com/comcast/concourse-vault-resource/pkg/resource/models" 11 | "github.com/comcast/concourse-vault-resource/test/fakes" 12 | ) 13 | 14 | var _ = Describe("Vault", func() { 15 | var ( 16 | check []models.Version 17 | err error 18 | request models.Request 19 | stdin *bytes.Buffer 20 | v *fakes.FakeVault 21 | ) 22 | 23 | BeforeEach(func() { 24 | v = new(fakes.FakeVault) 25 | check = make([]models.Version, 0) 26 | stdin = &bytes.Buffer{} 27 | request = models.Request{ 28 | Source: models.Source{ 29 | VaultPaths: map[string]int{ 30 | "kv2/data/foo/bar": 1, 31 | }, 32 | VaultAddr: "http://vault.example.com", 33 | VaultToken: "faKev4ultT0k3n", 34 | }, 35 | } 36 | 37 | err = json.NewEncoder(stdin).Encode(request) 38 | Expect(err).ShouldNot(HaveOccurred()) 39 | }) 40 | 41 | Describe("when Check() is called", func() { 42 | Context("checks the resource for versions and a version is found", func() { 43 | It("should return []models.Version containing a new version", func() { 44 | check = append(check, models.Version{ 45 | Version: "1", 46 | }) 47 | v.CheckReturns(check) 48 | Expect(v.Check()).To(Equal(check)) 49 | }) 50 | }) 51 | 52 | Context("checks the resource for versions and no version is found", func() { 53 | It("should return an empty []models.Version", func() { 54 | v.CheckReturns(check) 55 | Expect(v.Check()).To(Equal(check)) 56 | }) 57 | }) 58 | }) 59 | 60 | Describe("when In() is called", func() { 61 | Context("retrieves a secret(s) from vault", func() { 62 | It("should write the secret(s) to resource/secrets and no error should occur", func() { 63 | v.InReturns(err) 64 | Expect(v.In()).ShouldNot(HaveOccurred()) 65 | }) 66 | }) 67 | }) 68 | }) 69 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # PROJECT_NAME - the name of the project 2 | PROJECT_NAME := concourse-vault-resource 3 | 4 | # PROJECT_DIR - the project directory in the $GOPATH 5 | PROJECT_DIR := $(GOPATH)/src/github.com/comcast/$(PROJECT_NAME) 6 | 7 | # OUTPUT_DIR - the output directory for the binary builds. 8 | # also the output directory in the Dockerfile 9 | OUTPUT_DIR := /opt/resource 10 | 11 | # GIT_COMMIT - the git commit 12 | GIT_COMMIT := $(shell git rev-parse --short HEAD) 13 | 14 | # VERSION - the version as read from branch version file version 15 | VERSION := $(shell git show version:version) 16 | 17 | # DOCKER_IMAGE - the docker image repository and name 18 | DOCKER_IMAGE ?= hub.example.com/foo/concourse-vault-resource 19 | 20 | # GOLANG SPECIFICS - the variables with ?= are sane defaults should they not 21 | # already be set 22 | GOVERSION := 1.11.5 23 | GOMAXPROCS ?= 4 24 | GO111MODULE ?= on 25 | GOPATH ?= $(shell go env GOPATH) 26 | GOTAGS ?= 27 | LD_FLAGS ?= \ 28 | -s \ 29 | -w \ 30 | -extldflags "-static" \ 31 | -X $(PROJECT_DIR)/version.Name=$(PROJECT_NAME) \ 32 | -X $(PROJECT_DIR)/version.GitCommit=$(GIT_COMMIT) 33 | 34 | # Concourse Vault Resource Variables 35 | VAULT_ADDR ?= https://vault.example.com:8200 36 | VAULT_TOKEN := $(shell echo $$VAULT_TOKEN) 37 | 38 | all: usage 39 | usage: Makefile 40 | @echo 41 | @echo "$(PROJECT_NAME) supports the following:" 42 | @echo 43 | @sed -n 's/^##//p' $< | column -t -s ':' | sed -e 's/^/ /' 44 | @echo 45 | .PHONY: usage 46 | 47 | 48 | ## build - build the binaries 49 | build: lint test 50 | @echo "Building binaries with LD_FLAGS \"$(LD_FLAGS)\"" 51 | @for b in "check" "in" "out"; do \ 52 | go build -a \ 53 | -ldflags "$(LD_FLAGS)" \ 54 | -o $(OUTPUT_DIR)/$$b \ 55 | -tags "$(GOTAGS)" \ 56 | cmd/$$b/$$b.go; \ 57 | done 58 | .PHONY: build 59 | 60 | ## deps - will download dependencies 61 | deps: 62 | export GO111MODULE=$(GO111MODULE) 63 | go mod download 64 | go mod vendor 65 | 66 | ## fmt - will execute go fmt 67 | fmt: 68 | go fmt ./... 69 | 70 | ## image - will build the docker image 71 | image: 72 | docker build \ 73 | --build-arg OUTPUT_DIR=$(OUTPUT_DIR) \ 74 | --build-arg VAULT_ADDR=$(VAULT_ADDR)\ 75 | --build-arg VAULT_TOKEN=$(VAULT_TOKEN) \ 76 | -f build/Dockerfile --rm -t $(DOCKER_IMAGE) . 77 | 78 | ## install - will install the binary 79 | install: 80 | go install -v 81 | 82 | ## lint - will lint the code 83 | lint: 84 | @curl -s -L https://git.io/vp6lP | sh -s -- -b $(GOPATH)/bin 85 | gometalinter --config=.gometalinter.json \ 86 | --fast --deadline=90s --vendor --errors ./... 87 | 88 | ## push - will push the docker image to the docker repository 89 | push: 90 | docker push $(DOCKER_IMAGE) 91 | 92 | ## test - will execute any tests 93 | test: 94 | go test -v ./... 95 | .PHONY: test 96 | -------------------------------------------------------------------------------- /test/in_test.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "encoding/json" 5 | "io/ioutil" 6 | "os/exec" 7 | "time" 8 | 9 | . "github.com/onsi/ginkgo" 10 | . "github.com/onsi/gomega" 11 | 12 | "github.com/comcast/concourse-vault-resource/pkg/resource/models" 13 | "github.com/onsi/gomega/gbytes" 14 | "github.com/onsi/gomega/gexec" 15 | ) 16 | 17 | const ( 18 | inTimeout = 40 * time.Second 19 | ) 20 | 21 | var _ = Describe("In", func() { 22 | var ( 23 | command *exec.Cmd 24 | inRequest models.Request 25 | stdinContents []byte 26 | destDirectory string 27 | ) 28 | 29 | BeforeEach(func() { 30 | var err error 31 | 32 | By("Creating temp directory") 33 | destDirectory, err = ioutil.TempDir("", "concourse-vault-resource") 34 | Expect(err).NotTo(HaveOccurred()) 35 | 36 | By("Creating command object") 37 | command = exec.Command(inPath, destDirectory) 38 | 39 | By("Creating default request") 40 | inRequest = models.Request{ 41 | Source: models.Source{ 42 | VaultPaths: map[string]int{ 43 | "kv2/data/atu/foo": 2, 44 | }, 45 | VaultAddr: vaultAddr, 46 | VaultToken: vaultToken, 47 | }, 48 | } 49 | 50 | stdinContents, err = json.Marshal(inRequest) 51 | Expect(err).ShouldNot(HaveOccurred()) 52 | }) 53 | 54 | Describe("successful behavior", func() { 55 | It("writes secret(s) to destination file", func() { 56 | By("Running the command") 57 | session := run(command, stdinContents) 58 | 59 | Eventually(session, inTimeout).Should(gexec.Exit(0)) 60 | 61 | files, err := ioutil.ReadDir(destDirectory) 62 | Expect(err).NotTo(HaveOccurred()) 63 | 64 | Expect(len(files)).To(BeNumerically(">", 0)) 65 | for _, file := range files { 66 | Expect(file.Name()).To(MatchRegexp("secrets")) 67 | Expect(file.Size()).To(BeNumerically(">", 0)) 68 | } 69 | }) 70 | 71 | It("returns valid json", func() { 72 | By("Running the command") 73 | session := run(command, stdinContents) 74 | Eventually(session, inTimeout).Should(gexec.Exit(0)) 75 | 76 | By("Outputting a valid json rsponse") 77 | response := models.Response{} 78 | err := json.Unmarshal(session.Out.Contents(), &response) 79 | Expect(err).ShouldNot(HaveOccurred()) 80 | 81 | By("Validating output contains versions") 82 | Expect(len(response.Version.Version)).To(BeNumerically(">", 0)) 83 | Expect(response.Version.Version).NotTo(BeEmpty()) 84 | }) 85 | 86 | }) 87 | 88 | Context("when validation fails", func() { 89 | BeforeEach(func() { 90 | inRequest.Source.VaultPaths = make(map[string]int, 0) 91 | 92 | var err error 93 | stdinContents, err = json.Marshal(inRequest) 94 | Expect(err).ShouldNot(HaveOccurred()) 95 | }) 96 | 97 | It("exits with error", func() { 98 | By("Running the command") 99 | session := run(command, stdinContents) 100 | 101 | By("Validating command exited with error") 102 | Eventually(session, inTimeout).Should(gexec.Exit(1)) 103 | Expect(session.Err).Should(gbytes.Say("error validating resource configuration")) 104 | }) 105 | }) 106 | }) 107 | -------------------------------------------------------------------------------- /pkg/resource/auth.go: -------------------------------------------------------------------------------- 1 | package resource 2 | 3 | import ( 4 | "errors" 5 | "fmt" 6 | ) 7 | 8 | // getRoleID - gets a role_id from a role_name 9 | func (r *Resource) getRoleID() error { 10 | if len(r.config.Source.RoleName) <= 0 { 11 | return errors.New("no role_name provided") 12 | } 13 | resp, err := r.client.Logical().Read( 14 | fmt.Sprintf( 15 | "auth/approle/role/%s/role-id", 16 | r.config.Source.RoleName, 17 | ), 18 | ) 19 | if err != nil { 20 | return err 21 | } 22 | 23 | if roleID, ok := resp.Data["role_id"]; ok { 24 | r.roleID = roleID.(string) 25 | r.logger.Debug().Msg("role_id success") 26 | return nil 27 | } 28 | 29 | return errors.New("no role_id returned") 30 | } 31 | 32 | // getSecretID - gets a secret_id for a role_id 33 | func (r *Resource) getSecretID() error { 34 | if len(r.roleID) <= 0 { 35 | return errors.New("no role_id provided") 36 | } 37 | resp, err := r.client.Logical().Write( 38 | fmt.Sprintf( 39 | "auth/approle/role/%s/secret-id", 40 | r.config.Source.RoleName, 41 | ), 42 | nil, 43 | ) 44 | if err != nil { 45 | return err 46 | } 47 | 48 | if secretID, ok := resp.Data["secret_id"]; ok { 49 | r.secretID = secretID.(string) 50 | r.logger.Debug().Msg("secret_id success") 51 | return nil 52 | } 53 | 54 | return errors.New("no secret_id returned") 55 | } 56 | 57 | // loginWithAppRole - login via approle 58 | func (r *Resource) loginWithAppRole() error { 59 | if len(r.roleID) <= 0 && len(r.secretID) <= 0 { 60 | return errors.New("role_id or secret_id not provided when authenticating") 61 | } 62 | 63 | resp, err := r.client.Logical().Write( 64 | "auth/approle/login", 65 | map[string]interface{}{ 66 | "role_id": r.roleID, 67 | "secret_id": r.secretID, 68 | }, 69 | ) 70 | if err != nil { 71 | return err 72 | } 73 | 74 | if resp.Auth == nil { 75 | return errors.New("no authentication returned") 76 | } 77 | 78 | r.client.SetToken(resp.Auth.ClientToken) 79 | return nil 80 | } 81 | 82 | // renewToken - renews a token 83 | func (r *Resource) renewToken() error { 84 | if len(r.config.Source.VaultToken) <= 0 { 85 | return errors.New("error renewing vault client token, no vault_token provided") 86 | } 87 | 88 | r.logger.Debug().Msg("attempting renewal of token") 89 | 90 | resp, err := r.client.Logical().Write("auth/token/renew-self", nil) 91 | if err != nil { 92 | return err 93 | } 94 | if resp.Auth != nil { 95 | r.client.SetToken(resp.Auth.ClientToken) 96 | r.logger.Debug().Msg("succesfully renewed token") 97 | return nil 98 | } 99 | 100 | return errors.New("error renewing token") 101 | } 102 | 103 | // setToken - sets the vault client token 104 | func (r *Resource) setToken() error { 105 | if len(r.config.Source.RoleName) > 0 { 106 | err := r.getRoleID() 107 | if err != nil { 108 | return err 109 | } 110 | 111 | err = r.getSecretID() 112 | if err != nil { 113 | return err 114 | } 115 | 116 | err = r.loginWithAppRole() 117 | if err != nil { 118 | return err 119 | } 120 | return nil 121 | } 122 | 123 | if len(r.config.Source.RoleID) > 0 && len(r.config.Source.SecretID) > 0 { 124 | r.roleID = r.config.Source.RoleID 125 | r.secretID = r.config.Source.SecretID 126 | err := r.loginWithAppRole() 127 | if err != nil { 128 | return err 129 | } 130 | return nil 131 | } 132 | 133 | return nil 134 | } 135 | -------------------------------------------------------------------------------- /test/check_test.go: -------------------------------------------------------------------------------- 1 | package test 2 | 3 | import ( 4 | "encoding/json" 5 | "os" 6 | "os/exec" 7 | "time" 8 | 9 | "github.com/comcast/concourse-vault-resource/pkg/resource/models" 10 | . "github.com/onsi/ginkgo" 11 | . "github.com/onsi/gomega" 12 | "github.com/onsi/gomega/gbytes" 13 | "github.com/onsi/gomega/gexec" 14 | ) 15 | 16 | const ( 17 | checkTimeout = 40 * time.Second 18 | ) 19 | 20 | var _ = Describe("Check()", func() { 21 | var ( 22 | command *exec.Cmd 23 | checkRequest models.Request 24 | err error 25 | stdinContents []byte 26 | ) 27 | 28 | BeforeEach(func() { 29 | By("Creating command object") 30 | command = exec.Command(checkPath) 31 | 32 | By("Creating default request") 33 | checkRequest = models.Request{ 34 | Source: models.Source{ 35 | VaultPaths: map[string]int{ 36 | "kv2/data/atu/foo": 2, 37 | }, 38 | VaultAddr: vaultAddr, 39 | VaultToken: vaultToken, 40 | }, 41 | } 42 | 43 | stdinContents, err = json.Marshal(checkRequest) 44 | Expect(err).ShouldNot(HaveOccurred()) 45 | }) 46 | 47 | Describe("successful behavior", func() { 48 | It("returns secret(s) without error", func() { 49 | By("Running the Check() command") 50 | session := run(command, stdinContents) 51 | 52 | By("Validating command exited without error") 53 | Eventually(session, checkTimeout).Should(gexec.Exit(0)) 54 | 55 | var resp []models.Version 56 | err := json.Unmarshal(session.Out.Contents(), &resp) 57 | Expect(err).NotTo(HaveOccurred()) 58 | 59 | Expect(len(resp)).To(BeNumerically(">", 0)) 60 | Expect(resp).NotTo(BeEmpty()) 61 | }) 62 | 63 | Context("vault address not provided", func() { 64 | BeforeEach(func() { 65 | err = os.Setenv("VAULT_ADDR", checkRequest.Source.VaultAddr) 66 | Expect(err).ShouldNot(HaveOccurred()) 67 | 68 | checkRequest.Source.VaultAddr = "" 69 | 70 | stdinContents, err = json.Marshal(checkRequest) 71 | Expect(err).ShouldNot(HaveOccurred()) 72 | }) 73 | }) 74 | 75 | Context("vault token not provided", func() { 76 | BeforeEach(func() { 77 | err = os.Setenv("VAULT_TOKEN", checkRequest.Source.VaultToken) 78 | Expect(err).ShouldNot(HaveOccurred()) 79 | 80 | checkRequest.Source.VaultToken = "" 81 | 82 | stdinContents, err = json.Marshal(checkRequest) 83 | Expect(err).ShouldNot(HaveOccurred()) 84 | }) 85 | }) 86 | 87 | It("returns secret(s) without error", func() { 88 | By("Running the command") 89 | session := run(command, stdinContents) 90 | 91 | By("Validating command exited without error") 92 | Eventually(session, checkTimeout).Should(gexec.Exit(0)) 93 | 94 | var resp []models.Version 95 | err := json.Unmarshal(session.Out.Contents(), &resp) 96 | Expect(err).NotTo(HaveOccurred()) 97 | }) 98 | }) 99 | 100 | Context("when resource configuration validation fails", func() { 101 | BeforeEach(func() { 102 | checkRequest.Source.VaultPaths = make(map[string]int, 0) 103 | stdinContents, err = json.Marshal(checkRequest) 104 | Expect(err).ShouldNot(HaveOccurred()) 105 | }) 106 | 107 | It("exits with error", func() { 108 | By("Running the command") 109 | session := run(command, stdinContents) 110 | 111 | By("Validating command exited with error") 112 | Eventually(session, checkTimeout).Should(gexec.Exit(1)) 113 | Expect(session.Err).Should(gbytes.Say("error validating resource configuration")) 114 | }) 115 | }) 116 | }) 117 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Vault Resource 2 | Reads secrets from [Vault](https://www.vaultproject.io/). This resource supports [KV1](https://www.vaultproject.io/docs/secrets/kv/index.html#kv-version-1) and [KV2](https://www.vaultproject.io/docs/secrets/kv/index.html#kv-version-2) and can check for new versions or specific versions if using KV2. 3 | 4 | ## Source Configuration 5 | * `vault_addr`: *Required.* The location of the Vault server. `https://vault.example.com:8200`. 6 | 7 | * `vault_token`: *Required. if secret_id and role_id are not set* The token to use for authentication. `abc123f4k3T0k3n!&`. 8 | 9 | * `vault_paths`: *Required.* A list of paths:version to secrets in vault. You can place this in the source configuration or you may pass it a parameter when fetching the resource. 10 | 11 | ```yaml 12 | vault_paths: 13 | path/to/secret: -1 # -1 means latest 14 | path/to/secret/w/version: 1 # grab version 1 15 | ``` 16 | 17 | *AppRole Authentication* 18 | * `role_name`: *Optional.* If set, `vault_token` is required. Resource will use the `vault_token` and `role_name` to obtain a `role_id` and `secret_id` and use that to authenticate the approle. 19 | 20 | * `role_id`: *Optional.* The role_id to authenticate with. Must be used with `secret_id`. 21 | 22 | * `secret_id`: *Optional.* The secret_id to authenticate with. must be used with `role_id` 23 | 24 | 25 | *General Parameters* 26 | * `debug`: *Optional.* Print debug information. Will not expose secrets 27 | 28 | * `format`: *Optional.* Choose output format of either `json` or `yaml`. Default: `json` 29 | 30 | * `prefix`: *Optional.* Prepends a prefix to the secret key 31 | 32 | * `retries`: *Optional.* The amount of retries. Default: 3 33 | 34 | * `upcase`: *Optional.* Converts all secret keys to UPPERCASE 35 | 36 | * `sanitize`: *Optional.* Converts dots and dashes in a secret key to underscores 37 | 38 | * `vault_insecure`: *Optional.* Skips Vault SSL verification 39 | 40 | ### Example 41 | Resource configuration 42 | 43 | ``` yaml 44 | resource_types: 45 | - name: vault 46 | type: docker-image 47 | source: 48 | repository: hub.example.com/foo/concourse-vault-resource 49 | tag: latest 50 | 51 | resources: 52 | - name: vault 53 | type: vault 54 | source: 55 | vault_addr: https://vault.example.com:8200 56 | vault_token: {{token}} 57 | ``` 58 | 59 | Resource configuration with AppRole 60 | 61 | ``` yaml 62 | resource_types: 63 | - name: vault 64 | type: docker-image 65 | source: 66 | repository: hub.example.com/foo/concourse-vault-resource 67 | tag: latest 68 | 69 | resources: 70 | - name: vault 71 | type: vault 72 | source: 73 | vault_addr: https://vault.example.com:8200 74 | vault_token: {{token}} 75 | role_name: atu_vault-admins_approle 76 | ``` 77 | 78 | Resource configuration with AppRole using `role_id` and `secret_id` 79 | 80 | ``` yaml 81 | resource_types: 82 | - name: vault 83 | type: docker-image 84 | source: 85 | repository: hub.example.com/foo/concourse-vault-resource 86 | tag: latest 87 | 88 | resources: 89 | - name: vault 90 | type: vault 91 | source: 92 | vault_addr: https://vault.example.com:8200 93 | role_id: 123456zzxROLE_IDjhdjkfafpfwefwa 94 | secret_id: faffdsfafdSECRET_IDdsfsdfadfd 95 | ``` 96 | 97 | Fetching secrets: 98 | 99 | ``` yaml 100 | - get: vault 101 | params: 102 | vault_paths: 103 | # KV1 Engine Test 104 | secret/foo: -1 105 | # KV2 Engine Test 106 | kv2/data/foo/bar: 2 107 | ``` 108 | 109 | ## Behavior 110 | 111 | ### `check`: Check for new versions. 112 | 113 | ### `in`: Read secrets from Vault 114 | Reads secrets from Vault and stores them in /opt/resource/secrets as JSON or YAML. 115 | -------------------------------------------------------------------------------- /test/fakes/fake_vault.go: -------------------------------------------------------------------------------- 1 | // Code generated by counterfeiter. DO NOT EDIT. 2 | package fakes 3 | 4 | import ( 5 | "sync" 6 | 7 | "github.com/comcast/concourse-vault-resource/pkg/resource" 8 | "github.com/comcast/concourse-vault-resource/pkg/resource/models" 9 | ) 10 | 11 | type FakeVault struct { 12 | CheckStub func() []models.Version 13 | checkMutex sync.RWMutex 14 | checkArgsForCall []struct { 15 | } 16 | checkReturns struct { 17 | result1 []models.Version 18 | } 19 | checkReturnsOnCall map[int]struct { 20 | result1 []models.Version 21 | } 22 | InStub func() error 23 | inMutex sync.RWMutex 24 | inArgsForCall []struct { 25 | } 26 | inReturns struct { 27 | result1 error 28 | } 29 | inReturnsOnCall map[int]struct { 30 | result1 error 31 | } 32 | invocations map[string][][]interface{} 33 | invocationsMutex sync.RWMutex 34 | } 35 | 36 | func (fake *FakeVault) Check() []models.Version { 37 | fake.checkMutex.Lock() 38 | ret, specificReturn := fake.checkReturnsOnCall[len(fake.checkArgsForCall)] 39 | fake.checkArgsForCall = append(fake.checkArgsForCall, struct { 40 | }{}) 41 | fake.recordInvocation("Check", []interface{}{}) 42 | fake.checkMutex.Unlock() 43 | if fake.CheckStub != nil { 44 | return fake.CheckStub() 45 | } 46 | if specificReturn { 47 | return ret.result1 48 | } 49 | fakeReturns := fake.checkReturns 50 | return fakeReturns.result1 51 | } 52 | 53 | func (fake *FakeVault) CheckCallCount() int { 54 | fake.checkMutex.RLock() 55 | defer fake.checkMutex.RUnlock() 56 | return len(fake.checkArgsForCall) 57 | } 58 | 59 | func (fake *FakeVault) CheckCalls(stub func() []models.Version) { 60 | fake.checkMutex.Lock() 61 | defer fake.checkMutex.Unlock() 62 | fake.CheckStub = stub 63 | } 64 | 65 | func (fake *FakeVault) CheckReturns(result1 []models.Version) { 66 | fake.checkMutex.Lock() 67 | defer fake.checkMutex.Unlock() 68 | fake.CheckStub = nil 69 | fake.checkReturns = struct { 70 | result1 []models.Version 71 | }{result1} 72 | } 73 | 74 | func (fake *FakeVault) CheckReturnsOnCall(i int, result1 []models.Version) { 75 | fake.checkMutex.Lock() 76 | defer fake.checkMutex.Unlock() 77 | fake.CheckStub = nil 78 | if fake.checkReturnsOnCall == nil { 79 | fake.checkReturnsOnCall = make(map[int]struct { 80 | result1 []models.Version 81 | }) 82 | } 83 | fake.checkReturnsOnCall[i] = struct { 84 | result1 []models.Version 85 | }{result1} 86 | } 87 | 88 | func (fake *FakeVault) In() error { 89 | fake.inMutex.Lock() 90 | ret, specificReturn := fake.inReturnsOnCall[len(fake.inArgsForCall)] 91 | fake.inArgsForCall = append(fake.inArgsForCall, struct { 92 | }{}) 93 | fake.recordInvocation("In", []interface{}{}) 94 | fake.inMutex.Unlock() 95 | if fake.InStub != nil { 96 | return fake.InStub() 97 | } 98 | if specificReturn { 99 | return ret.result1 100 | } 101 | fakeReturns := fake.inReturns 102 | return fakeReturns.result1 103 | } 104 | 105 | func (fake *FakeVault) InCallCount() int { 106 | fake.inMutex.RLock() 107 | defer fake.inMutex.RUnlock() 108 | return len(fake.inArgsForCall) 109 | } 110 | 111 | func (fake *FakeVault) InCalls(stub func() error) { 112 | fake.inMutex.Lock() 113 | defer fake.inMutex.Unlock() 114 | fake.InStub = stub 115 | } 116 | 117 | func (fake *FakeVault) InReturns(result1 error) { 118 | fake.inMutex.Lock() 119 | defer fake.inMutex.Unlock() 120 | fake.InStub = nil 121 | fake.inReturns = struct { 122 | result1 error 123 | }{result1} 124 | } 125 | 126 | func (fake *FakeVault) InReturnsOnCall(i int, result1 error) { 127 | fake.inMutex.Lock() 128 | defer fake.inMutex.Unlock() 129 | fake.InStub = nil 130 | if fake.inReturnsOnCall == nil { 131 | fake.inReturnsOnCall = make(map[int]struct { 132 | result1 error 133 | }) 134 | } 135 | fake.inReturnsOnCall[i] = struct { 136 | result1 error 137 | }{result1} 138 | } 139 | 140 | func (fake *FakeVault) Invocations() map[string][][]interface{} { 141 | fake.invocationsMutex.RLock() 142 | defer fake.invocationsMutex.RUnlock() 143 | fake.checkMutex.RLock() 144 | defer fake.checkMutex.RUnlock() 145 | fake.inMutex.RLock() 146 | defer fake.inMutex.RUnlock() 147 | copiedInvocations := map[string][][]interface{}{} 148 | for key, value := range fake.invocations { 149 | copiedInvocations[key] = value 150 | } 151 | return copiedInvocations 152 | } 153 | 154 | func (fake *FakeVault) recordInvocation(key string, args []interface{}) { 155 | fake.invocationsMutex.Lock() 156 | defer fake.invocationsMutex.Unlock() 157 | if fake.invocations == nil { 158 | fake.invocations = map[string][][]interface{}{} 159 | } 160 | if fake.invocations[key] == nil { 161 | fake.invocations[key] = [][]interface{}{} 162 | } 163 | fake.invocations[key] = append(fake.invocations[key], args) 164 | } 165 | 166 | var _ resource.Vault = new(FakeVault) 167 | -------------------------------------------------------------------------------- /go.sum: -------------------------------------------------------------------------------- 1 | github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310/go.mod h1:ufUuZ+zHj4x4TnLV4JWEpy2hxWSpsRywHrMgIH9cCH8= 2 | github.com/bgentry/speakeasy v0.1.0/go.mod h1:+zsyZBPWlz7T6j88CTgSN5bM796AkVf0kBD4zp0CCIs= 3 | github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= 4 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= 5 | github.com/fatih/color v1.7.0/go.mod h1:Zm6kSWBoL9eyXnKyktHP6abPY2pDugNf5KwzbycvMj4= 6 | github.com/fsnotify/fsnotify v1.4.7 h1:IXs+QLmnXW2CcXuY+8Mzv/fWEsPGWxqefPtCP5CnV9I= 7 | github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo= 8 | github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= 9 | github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= 10 | github.com/golang/snappy v0.0.1 h1:Qgr9rKW7uDUkrbSmQeiDsGa8SjGyCOGtuasMWwvp2P4= 11 | github.com/golang/snappy v0.0.1/go.mod h1:/XxbfmMg8lxefKM7IXC3fBNl/7bRcc72aCRzEWrmP2Q= 12 | github.com/hashicorp/errwrap v1.0.0 h1:hLrqtEDnRye3+sgx6z4qVLNuviH3MR5aQ0ykNJa/UYA= 13 | github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4= 14 | github.com/hashicorp/go-cleanhttp v0.5.0/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= 15 | github.com/hashicorp/go-cleanhttp v0.5.1 h1:dH3aiDG9Jvb5r5+bYHsikaOUIpcM0xvgMXVoDkXMzJM= 16 | github.com/hashicorp/go-cleanhttp v0.5.1/go.mod h1:JpRdi6/HCYpAwUzNwuwqhbovhLtngrth3wmdIIUrZ80= 17 | github.com/hashicorp/go-multierror v1.0.0 h1:iVjPR7a6H0tWELX5NxNe7bYopibicUzc7uPribsnS6o= 18 | github.com/hashicorp/go-multierror v1.0.0/go.mod h1:dHtQlpGsu+cZNNAkkCN/P3hoUDHhCYQXV3UM06sGGrk= 19 | github.com/hashicorp/go-retryablehttp v0.5.3 h1:QlWt0KvWT0lq8MFppF9tsJGF+ynG7ztc2KIPhzRGk7s= 20 | github.com/hashicorp/go-retryablehttp v0.5.3/go.mod h1:9B5zBasrRhHXnJnui7y6sL7es7NDiJgTc6Er0maI1Xs= 21 | github.com/hashicorp/go-rootcerts v1.0.0 h1:Rqb66Oo1X/eSV1x66xbDccZjhJigjg0+e82kpwzSwCI= 22 | github.com/hashicorp/go-rootcerts v1.0.0/go.mod h1:K6zTfqpRlCUIjkwsN4Z+hiSfzSTQa6eBIzfwKfwNnHU= 23 | github.com/hashicorp/go-sockaddr v1.0.2 h1:ztczhD1jLxIRjVejw8gFomI1BQZOe2WoVOu0SyteCQc= 24 | github.com/hashicorp/go-sockaddr v1.0.2/go.mod h1:rB4wwRAUzs07qva3c5SdrY/NEtAUjGlgmH/UkBUC97A= 25 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4= 26 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ= 27 | github.com/hashicorp/vault v1.1.0 h1:v79NUgO5xCZnXVzUkIqFOXtP8YhpnHAi1fk3eo9cuOE= 28 | github.com/hashicorp/vault v1.1.0/go.mod h1:KfSyffbKxoVyspOdlaGVjIuwLobi07qD1bAbosPMpP0= 29 | github.com/hpcloud/tail v1.0.0 h1:nfCOvKYfkgYP8hkirhJocXT2+zOD8yUNjXaWfTlyFKI= 30 | github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpOxQnU= 31 | github.com/mattn/go-colorable v0.0.9/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU= 32 | github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4= 33 | github.com/mitchellh/cli v1.0.0/go.mod h1:hNIlj7HEI86fIcpObd7a0FcrxTWetlwJDGcceTlRvqc= 34 | github.com/mitchellh/go-homedir v1.0.0 h1:vKb8ShqSby24Yrqr/yDYkuFz8d0WUjys40rvnGC8aR0= 35 | github.com/mitchellh/go-homedir v1.0.0/go.mod h1:SfyaCUpYCn1Vlf4IUYiD9fPX4A5wJrkLzIz1N1q0pr0= 36 | github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo= 37 | github.com/mitchellh/mapstructure v1.1.2 h1:fmNYVwqnSfB9mZU6OS2O6GsXM+wcskZDuKQzvN1EDeE= 38 | github.com/mitchellh/mapstructure v1.1.2/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y= 39 | github.com/onsi/ginkgo v1.6.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 40 | github.com/onsi/ginkgo v1.8.0 h1:VkHVNpR4iVnU8XQR6DBm8BqYjN7CRzw+xKUbVVbbW9w= 41 | github.com/onsi/ginkgo v1.8.0/go.mod h1:lLunBs/Ym6LB5Z9jYTR76FiuTmxDTDusOGeTQH+WWjE= 42 | github.com/onsi/gomega v1.5.0 h1:izbySO9zDPmjJ8rDjLvkA2zJHIo+HkYXHnf7eN7SSyo= 43 | github.com/onsi/gomega v1.5.0/go.mod h1:ex+gbHU/CVuBBDIJjb2X0qEXbFg53c61hWP/1CpauHY= 44 | github.com/pierrec/lz4 v2.0.5+incompatible h1:2xWsjqPFWcplujydGg4WmhC/6fZqK42wMM8aXeqhl0I= 45 | github.com/pierrec/lz4 v2.0.5+incompatible/go.mod h1:pdkljMzZIN41W+lC3N2tnIh5sFi+IEE17M5jbnwPHcY= 46 | github.com/posener/complete v1.1.1/go.mod h1:em0nMJCgc9GFtwrmVmEMR/ZL6WyhyjMBndrE9hABlRI= 47 | github.com/rs/zerolog v1.13.0 h1:hSNcYHyxDWycfePW7pUI8swuFkcSMPKh3E63Pokg1Hk= 48 | github.com/rs/zerolog v1.13.0/go.mod h1:YbFCdg8HfsridGWAh22vktObvhZbQsZXe4/zB0OKkWU= 49 | github.com/ryanuber/columnize v2.1.0+incompatible/go.mod h1:sm1tb6uqfes/u+d4ooFouqFdy9/2g9QGwK3SQygK0Ts= 50 | github.com/ryanuber/go-glob v1.0.0 h1:iQh3xXAumdQ+4Ufa5b25cRpC5TYKlno6hsv6Cb3pkBk= 51 | github.com/ryanuber/go-glob v1.0.0/go.mod h1:807d1WSdnB0XRJzKNil9Om6lcp/3a0v4qIHxIXzX/Yc= 52 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd h1:nTDtHvHSdCn1m6ITfMRqtOd/9+7a3s8RBNOZ3eYZzJA= 53 | golang.org/x/net v0.0.0-20180906233101-161cd47e91fd/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= 54 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f h1:wMNYb4v58l5UBM7MYRLPG6ZhfOqbKu7X5eyFl8ZhKvA= 55 | golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= 56 | golang.org/x/sys v0.0.0-20180823144017-11551d06cbcc/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 57 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e h1:o3PsSEY8E4eXWkXrIP9YJALUkVZqzHJT5DOasTyn8Vs= 58 | golang.org/x/sys v0.0.0-20180909124046-d0be0721c37e/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY= 59 | golang.org/x/text v0.3.0 h1:g61tztE5qeGQ89tm6NTjjM9VPIm088od1l6aSorWRWg= 60 | golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= 61 | golang.org/x/time v0.0.0-20190308202827-9d24e82272b4 h1:SvFZT6jyqRaOeXpc5h/JSfZenJ2O330aBsf7JfSUXmQ= 62 | golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= 63 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405 h1:yhCVgyC4o1eVCa2tZl7eS0r+SDo693bJlVdllGtEeKM= 64 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= 65 | gopkg.in/fsnotify.v1 v1.4.7 h1:xOHLXZwVvI9hhs+cLKq5+I5onOuwQLhQwiu63xxlHs4= 66 | gopkg.in/fsnotify.v1 v1.4.7/go.mod h1:Tz8NjZHkW78fSQdbUxIjBTcgA1z1m8ZHf0WmKUhAMys= 67 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ= 68 | gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw= 69 | gopkg.in/yaml.v2 v2.2.1/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 70 | gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw= 71 | gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI= 72 | -------------------------------------------------------------------------------- /pkg/resource/vault.go: -------------------------------------------------------------------------------- 1 | package resource 2 | 3 | import ( 4 | "crypto/tls" 5 | "encoding/json" 6 | "errors" 7 | "fmt" 8 | "net/http" 9 | "os" 10 | "strings" 11 | 12 | "github.com/hashicorp/vault/api" 13 | "github.com/rs/zerolog" 14 | yaml "gopkg.in/yaml.v2" 15 | 16 | "github.com/comcast/concourse-vault-resource/pkg/resource/models" 17 | ) 18 | 19 | // Vault - the vault resource interface 20 | type Vault interface { 21 | Check() []models.Version 22 | In() error 23 | } 24 | 25 | // Resource - the vault resource 26 | type Resource struct { 27 | client *api.Client 28 | logger zerolog.Logger 29 | config models.Request 30 | secrets map[string]interface{} 31 | workDir string 32 | roleID string 33 | secretID string 34 | } 35 | 36 | // New - returns a vault client for interaction with the vault API 37 | func New( 38 | workDir string, 39 | config models.Request, 40 | logger zerolog.Logger, 41 | ) (*Resource, error) { 42 | var err error 43 | 44 | if config.Source.Debug { 45 | zerolog.SetGlobalLevel(zerolog.DebugLevel) 46 | logger = logger.With().Caller().Logger() 47 | } 48 | 49 | config, err = validate(config) 50 | if err != nil { 51 | logger.Fatal().Err(err). 52 | Msg("error validating resource configuration") 53 | } 54 | 55 | c, err := api.NewClient( 56 | &api.Config{ 57 | Address: config.Source.VaultAddr, 58 | HttpClient: &http.Client{ 59 | Transport: &http.Transport{ 60 | TLSClientConfig: &tls.Config{ 61 | InsecureSkipVerify: config.Source.VaultInsecure, 62 | }, 63 | }, 64 | }, 65 | MaxRetries: config.Source.Retries, 66 | }, 67 | ) 68 | if err != nil { 69 | logger.Fatal().AnErr("err", err). 70 | Msg("error occured creating client") 71 | } 72 | 73 | if len(config.Source.VaultToken) > 0 { 74 | c.SetToken(config.Source.VaultToken) 75 | } 76 | 77 | r := &Resource{ 78 | client: c, 79 | config: config, 80 | logger: logger, 81 | workDir: workDir, 82 | secrets: make(map[string]interface{}, 0), 83 | } 84 | 85 | err = r.setToken() 86 | if err != nil { 87 | r.logger.Fatal().Err(err). 88 | Msg("error logging into vault") 89 | } 90 | 91 | return r, nil 92 | } 93 | 94 | // Check - checks vault for new secret version 95 | func (r Resource) Check() []models.Version { 96 | err := r.renewToken() 97 | if err != nil { 98 | r.logger.Fatal().AnErr("err", err). 99 | Msg("error occured renewing token") 100 | } 101 | 102 | var versions []models.Version 103 | for p, ver := range r.config.Source.VaultPaths { 104 | if ver > 0 || ver == -1 { 105 | s, err := r.client.Logical().Read( 106 | strings.Replace(p, "data", "metadata", 1), 107 | ) 108 | if err != nil { 109 | r.logger.Fatal().AnErr("err", err). 110 | Msg("error occured reading paths") 111 | } 112 | 113 | if s != nil { 114 | versions = append(versions, models.Version{ 115 | Path: p, 116 | Version: fmt.Sprintf( 117 | "%v", s.Data["current_version"], 118 | ), 119 | }) 120 | } 121 | } else { 122 | versions = append(versions, models.Version{ 123 | Path: p, 124 | Version: "1", 125 | }) 126 | } 127 | } 128 | 129 | return versions 130 | } 131 | 132 | // In - executes the resource 133 | func (r *Resource) In() error { 134 | err := r.renewToken() 135 | if err != nil { 136 | r.logger.Fatal().AnErr("err", err). 137 | Msg("error occured renewing token") 138 | } 139 | 140 | err = r.read() 141 | if err != nil { 142 | r.logger.Fatal().Err(err). 143 | Msg("error reading secrets") 144 | } 145 | 146 | r.prefix() 147 | 148 | r.sanitize() 149 | 150 | r.upcase() 151 | 152 | err = r.format() 153 | if err != nil { 154 | r.logger.Fatal().Err(err). 155 | Msg("error formatting secrets") 156 | } 157 | 158 | return nil 159 | } 160 | 161 | // format - formats the output in either json or yaml 162 | func (r Resource) format() error { 163 | var ( 164 | b []byte 165 | err error 166 | ) 167 | 168 | switch f := strings.ToLower(r.config.Source.Format); f { 169 | case "json": 170 | b, err = json.Marshal(r.secrets) 171 | if err != nil { 172 | return err 173 | } 174 | 175 | case "yaml": 176 | b, err = yaml.Marshal(r.secrets) 177 | if err != nil { 178 | return err 179 | } 180 | 181 | default: 182 | b, err = json.Marshal(r.secrets) 183 | if err != nil { 184 | return err 185 | } 186 | } 187 | 188 | if len(b) <= 0 { 189 | return errors.New("no secrets found to write to file") 190 | } 191 | 192 | err = r.write(b) 193 | if err != nil { 194 | return err 195 | } 196 | 197 | return nil 198 | } 199 | 200 | // prefix - adds a custom prefix to each key 201 | func (r *Resource) prefix() { 202 | if len(r.config.Source.Prefix) <= 0 { 203 | return 204 | } 205 | 206 | s := make(map[string]interface{}, 0) 207 | for k, v := range r.secrets { 208 | s[fmt.Sprintf("%s_%s", r.config.Source.Prefix, k)] = v 209 | } 210 | r.secrets = s 211 | } 212 | 213 | // read - reads vault for a secret at a given path 214 | func (r *Resource) read() error { 215 | var ( 216 | s *api.Secret 217 | err error 218 | result = make(map[string]interface{}, 0) 219 | ) 220 | 221 | for p, ver := range r.config.Source.VaultPaths { 222 | if ver > 0 { 223 | s, err = r.client.Logical().ReadWithData(p, map[string][]string{ 224 | "version": []string{fmt.Sprintf("%d", ver)}, 225 | }) 226 | } else { 227 | s, err = r.client.Logical().Read(p) 228 | } 229 | if err != nil { 230 | r.logger.Fatal().AnErr("err", err). 231 | Msg("error occured reading paths") 232 | } 233 | 234 | if s != nil { 235 | // KV2 236 | if d, ok := s.Data["data"]; ok { 237 | switch t := d.(type) { 238 | case map[string]interface{}: 239 | for k, v := range t { 240 | result[k] = v 241 | } 242 | default: 243 | r.logger.Debug().Msg("could not determine secret type") 244 | } 245 | } else { 246 | // KV1 247 | for k, v := range s.Data { 248 | result[k] = v 249 | } 250 | } 251 | } 252 | } 253 | 254 | if r.config.Source.Debug { 255 | var s []string 256 | for k := range result { 257 | s = append(s, k) 258 | } 259 | r.logger.Debug().Strs("secret_keys", s). 260 | Msg("secret(s) found, value(s) not shown") 261 | } 262 | 263 | r.secrets = result 264 | 265 | return nil 266 | } 267 | 268 | // sanitize - sanitizes keys converting dashes(-) and dots(.) to underscores 269 | func (r *Resource) sanitize() { 270 | if !r.config.Source.Sanitize { 271 | return 272 | } 273 | 274 | s := make(map[string]interface{}, 0) 275 | for k, v := range r.secrets { 276 | k = strings.Replace(k, "-", "_", -1) 277 | k = strings.Replace(k, ".", "_", -1) 278 | s[k] = v 279 | } 280 | r.secrets = s 281 | } 282 | 283 | // upcase - converts keys to UPPERCASE 284 | func (r *Resource) upcase() { 285 | if !r.config.Source.Upcase { 286 | return 287 | } 288 | 289 | s := make(map[string]interface{}, 0) 290 | for k, v := range r.secrets { 291 | s[strings.ToUpper(k)] = v 292 | } 293 | r.secrets = s 294 | } 295 | 296 | // write - writes the secrets to a file 297 | func (r Resource) write(b []byte) error { 298 | f, err := os.OpenFile( 299 | fmt.Sprintf("%s/secrets", r.workDir), 300 | os.O_CREATE|os.O_WRONLY, 0644, 301 | ) 302 | if err != nil { 303 | r.logger.Fatal().Err(err). 304 | Msg("error opening file for write") 305 | } 306 | defer f.Close() 307 | 308 | if _, err := f.Write(b); err != nil { 309 | r.logger.Fatal().Err(err). 310 | Msg("error writing to destination file") 311 | } 312 | 313 | return nil 314 | } 315 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | --------------------------------------------------------------------------------