Skip to content
This repository has been archived by the owner on Aug 29, 2024. It is now read-only.

Commit

Permalink
Add plain-text output
Browse files Browse the repository at this point in the history
  • Loading branch information
RomanCherednikov committed Mar 20, 2020
1 parent 211584b commit cb99bd5
Show file tree
Hide file tree
Showing 8 changed files with 79 additions and 58 deletions.
3 changes: 2 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
*.template
go.sum
rattus
rattus
rattus.upx
7 changes: 4 additions & 3 deletions Makefile
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
.DEFAULT_GOAL := build

install:
go install -v

build: install
DEBUG=false GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -a -v -o rattus
upx -9 --best --ultra-brute rattus

CGO_ENABLED=0 DEBUG=false GOOS=linux GOARCH=amd64 go build -ldflags="-s -w" -a -v -o rattus
upx -9 --best --ultra-brute --overlay=strip rattus
16 changes: 6 additions & 10 deletions aws.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
package main

import (
"encoding/json"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
Expand All @@ -25,11 +23,11 @@ func createAWSSession(AWSRegion, AWSKeyID, AWSKeySecret string) (*session.Sessio
return awsSession, err
}

func getAWSSecret(secretName, AWSRegion, AWSKeyID, AWSKeySecret string) (map[string]interface{}, error) {
var secrets map[string]interface{}
func getAWSSecretString(secretName, AWSRegion, AWSKeyID, AWSKeySecret string) (string, error) {
var secret string
awsSession, err := createAWSSession(AWSRegion, AWSKeyID, AWSKeySecret)
if err != nil {
return secrets, err
return secret, err
}

awsService := secretsmanager.New(awsSession)
Expand All @@ -40,12 +38,10 @@ func getAWSSecret(secretName, AWSRegion, AWSKeyID, AWSKeySecret string) (map[str

awsResponse, err := awsService.GetSecretValue(awsRequest)
if err != nil {
return secrets, err
return secret, err
}

if err := json.Unmarshal([]byte(*awsResponse.SecretString), &secrets); err != nil {
return secrets, err
}
secret = *awsResponse.SecretString

return secrets, err
return secret, err
}
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module keelson-key
module rattus

go 1.14

Expand Down
13 changes: 6 additions & 7 deletions kubernetes.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,10 @@ func getK8SServiceRole() (string, error) {
return token, nil
}

// K8SVaultLogin - login at vault and retrive vault auth token
func K8SVaultLogin(vaultSecretURL, authToken, authRole string) (string, error) {
// getVaultAuthToken - login at vault and retrive vault auth token
func getVaultAuthToken(vaultSecretURL, authToken, authRole string) (string, error) {
var token string
var responseJSON map[string]interface{}
var parsedResponse map[string]interface{}
var requstPayload = []byte(fmt.Sprintf(`{"jwt": "%s", "role": "%s"}`, authToken, authRole))

vaultLoginURL, err := getVaultLoginURL(vaultSecretURL)
Expand Down Expand Up @@ -78,12 +78,11 @@ func K8SVaultLogin(vaultSecretURL, authToken, authRole string) (string, error) {
return token, err
}

if err := json.Unmarshal(respBodyBytes, &responseJSON); err != nil {
if err := json.Unmarshal(respBodyBytes, &parsedResponse); err != nil {
return token, err
}

responseJSONAuth := responseJSON["auth"].(map[string]interface{})
token = responseJSONAuth["client_token"].(string)
token = parsedResponse["auth"].(map[string]interface{})["client_token"].(string)

return token, nil
}
Expand All @@ -100,7 +99,7 @@ func getK8SVaultToken(vaultSecretURL string) (string, error) {
return token, fmt.Errorf("failed to get k8s namespace - %s", err)
}

token, err = K8SVaultLogin(vaultSecretURL, serviceToken, serviceRole)
token, err = getVaultAuthToken(vaultSecretURL, serviceToken, serviceRole)
if err != nil {
return token, fmt.Errorf("failed to auth at vault - %s", err)
}
Expand Down
26 changes: 17 additions & 9 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@ type applicationConfig struct {
AWSRegion string
AWSKeyID string
AWSKeySecret string
Debug *bool
}

func initializeConfiguration() applicationConfig {
// default configuration
c := &applicationConfig{}
c.SecretProvider = "none"
c.AWSRegion = "us-east-1"

// cli arguments
argVaultSecret := flag.String("vault-secret", "", "Vault secret URL - https://vault.example.io/v1/storage/secret\nenv: VAULT_SECRET\n")
Expand All @@ -30,8 +34,11 @@ func initializeConfiguration() applicationConfig {
argAWSKeyID := flag.String("aws-key-id", "", "AWS account ID\nenv: AWS_ACCESS_KEY_ID\n")
argAWSKeySecret := flag.String("aws-key-secret", "", "AWS account secret\nAWS_SECRET_ACCESS_KEY\n")
argTemplatePath := flag.String("template", "", "Path to template file - /app/config/production.template\nenv: TEMPLATE_PATH\n")
c.Debug = flag.Bool("debug", false, "Enable debug information\n")

flag.Parse()


// vault secret
envVaultSecret := os.Getenv("VAULT_SECRET")
if envVaultSecret != "" {
Expand Down Expand Up @@ -70,9 +77,6 @@ func initializeConfiguration() applicationConfig {
if *argAWSRegion != "" {
c.AWSRegion = *argAWSRegion
}
if c.AWSRegion == "" {
c.AWSRegion = "us-east-1"
}

// aws id
envAWSKeyID := os.Getenv("AWS_ACCESS_KEY_ID")
Expand Down Expand Up @@ -106,10 +110,14 @@ func initializeConfiguration() applicationConfig {

func main() {
// initialize configuration
var secrets map[string]interface{}
var secrets string
var err error
config := initializeConfiguration()

if *config.Debug {
fmt.Printf("Secret provider: %s", config.SecretProvider)
}

// get secrets
switch config.SecretProvider {
case "vault":
Expand All @@ -120,21 +128,21 @@ func main() {
}

case "aws":
secrets, err = getAWSSecret(config.AWSSecretName, config.AWSRegion, config.AWSKeyID, config.AWSKeySecret)
secrets, err = getAWSSecretString(config.AWSSecretName, config.AWSRegion, config.AWSKeyID, config.AWSKeySecret)
if err != nil {
fmt.Printf("Error: %s\n", err)
os.Exit(1)
}
}

// generate output
output, err := renderOutput(secrets, config.TemplatePath)
// render output as template,json or text
secrets, err = renderOutput(secrets, config.TemplatePath)
if err != nil {
fmt.Printf("Error: %s\n", err)
os.Exit(1)
}

// show output and exit
fmt.Println(output)
// show secrets output and exit
fmt.Println(secrets)
os.Exit(0)
}
39 changes: 25 additions & 14 deletions template.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,32 +14,36 @@ func templateDatetime() string {
return timeNow.Format("2006-01-02-15:04:05")
}

// register custom go template functions
func registerTemplateFunctions() template.FuncMap {
return template.FuncMap{
"datetime": templateDatetime,
}
}

// render template
func generateTemplate(templatePath string, values map[string]interface{}) (string, error) {
var renderedTemplate string

templateFileContent, err := ioutil.ReadFile(templatePath)
if err != nil {
return "", err
return renderedTemplate, err
}

templateFunctions := registerTemplateFunctions()
templateRender, err := template.New("template").Funcs(templateFunctions).Parse(string(templateFileContent))
if err != nil {
return "", err
return renderedTemplate, err
}

templateRederBuffer := &bytes.Buffer{}
err = templateRender.Execute(templateRederBuffer, values)
if err != nil {
return "", err
return renderedTemplate, err
}
renderedTemplate = templateRederBuffer.String()

return templateRederBuffer.String(), nil
return renderedTemplate, nil
}

// convert map of interface to JSON
Expand All @@ -52,21 +56,28 @@ func mapToJSON(values map[string]interface{}) (string, error) {
return string(JSON), nil
}

func renderOutput(secrets map[string]interface{}, templatePath string) (string, error) {
var stdout string
// render template or return plain secrets text
func renderOutput(secretsString, templatePath string) (string, error) {
var secretsMap map[string]interface{}
var secretsOutput string
var err error

secretsOutput = secretsString

// try to convert json secrets to map interfaces or return plan secret value
err = json.Unmarshal([]byte(secretsString), &secretsMap)
if err != nil {
return secretsOutput, nil
}

// render secrets as template
if templatePath != "" {
stdout, err = generateTemplate(templatePath, secrets)
if err != nil {
return stdout, fmt.Errorf("failed to render secrets template - %s", err)
}
} else {
stdout, err = mapToJSON(secrets)
secretsOutput, err = generateTemplate(templatePath, secretsMap)
if err != nil {
return stdout, fmt.Errorf("failed to convert secrets at json - %s", err)
return secretsOutput, fmt.Errorf("failed to render secrets template - %s", err)
}
}

return stdout, nil
// return plain json
return secretsOutput, nil
}
31 changes: 18 additions & 13 deletions vault.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,15 +23,15 @@ func getVaultLoginURL(URL string) (string, error) {
if err != nil {
log.Fatal(err)
}
vaultAuthURL = fmt.Sprintf("%s%s%s", parsedURL.Scheme, parsedURL.Host, vaultAuthEndpoint)
vaultAuthURL = fmt.Sprintf("%s://%s%s", parsedURL.Scheme, parsedURL.Host, vaultAuthEndpoint)

return vaultAuthURL, nil
}

// get secret from vault
func getVaultSecret(URL, authToken string) (map[string]interface{}, error) {
var secrets map[string]interface{}
var responseJSON map[string]interface{}
func getVaultSecret(URL, authToken string) (string, error) {
var secrets string
var parsedResponse map[string]interface{}

http.DefaultTransport.(*http.Transport).TLSClientConfig = &tls.Config{InsecureSkipVerify: vaultSkipTLS}
client := &http.Client{
Expand Down Expand Up @@ -59,25 +59,30 @@ func getVaultSecret(URL, authToken string) (map[string]interface{}, error) {
return secrets, err
}

if err := json.Unmarshal(respBodyBytes, &responseJSON); err != nil {
if err := json.Unmarshal(respBodyBytes, &parsedResponse); err != nil {
return secrets, err
}

secrets = responseJSON["data"].(map[string]interface{})
secrets, err = mapToJSON(parsedResponse["data"].(map[string]interface{}))
if err != nil {
return secrets, nil
}

return secrets, nil
}

// get secret from vault
func vaultGetSecret(config applicationConfig) (map[string]interface{}, error) {
var secrets map[string]interface{}
var vaultToken string
func vaultGetSecret(config applicationConfig) (string, error) {
vaultToken := config.VaultToken
var secrets string
var err error

if config.VaultToken != "" {
vaultToken = config.VaultToken
} else {
vaultToken, _ = getK8SVaultToken(config.VaultSecretURL)
// issue new vault token if it was not set from config
if config.VaultToken == "" {
vaultToken, err = getK8SVaultToken(config.VaultSecretURL)
if err != nil {
return secrets, err
}
}

secrets, err = getVaultSecret(config.VaultSecretURL, vaultToken)
Expand Down

0 comments on commit cb99bd5

Please sign in to comment.