Skip to content

Commit

Permalink
(ref) #26 adds tests for schema_v1
Browse files Browse the repository at this point in the history
  • Loading branch information
benammann committed Sep 3, 2022
1 parent 312429d commit 6f7bd09
Show file tree
Hide file tree
Showing 22 changed files with 307 additions and 48 deletions.
12 changes: 6 additions & 6 deletions cmd/add.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ var addCmd = &cobra.Command{
var addContextCmd = &cobra.Command{
Use: "context",
Short: "Add a context to the config file",
Example: "git-secrets add context <contextName>",
Example: "git secrets add context <contextName>",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cobra.CheckErr(projectCfgError)
},
Expand All @@ -30,8 +30,8 @@ var addContextCmd = &cobra.Command{
cobra.CheckErr(errAdd)
fmt.Printf("The context %s has been added to your config file\n", contextToAdd)
fmt.Printf("Now use it using the --context %s or -c %s flag\n", contextToAdd, contextToAdd)
fmt.Printf("Add a config to this context: git-secrets set config <configKey> <configValue> -c %s\n", contextToAdd)
fmt.Printf("Add a secret to this context: git-secrets set secret <secretKey> -c %s\n", contextToAdd)
fmt.Printf("Add a config to this context: git secrets set config <configKey> <configValue> -c %s\n", contextToAdd)
fmt.Printf("Add a secret to this context: git secrets set secret <secretKey> -c %s\n", contextToAdd)
},
}

Expand All @@ -40,8 +40,8 @@ var addFileCmd = &cobra.Command{
Use: "file",
Short: "Add a file to the rendering engine",
Example: `
git-secrets add file <fileIn> <fileOut>
git-secrets add file <fileIn> <fileOut> -c prod
git secrets add file <fileIn> <fileOut>
git secrets add file <fileIn> <fileOut> -c prod
`,
Args: cobra.ExactArgs(2),
PersistentPreRun: func(cmd *cobra.Command, args []string) {
Expand All @@ -56,7 +56,7 @@ git-secrets add file <fileIn> <fileOut> -c prod
configWrite := projectCfg.GetConfigWriter()
cobra.CheckErr(configWrite.AddFileToRender(targetName, fileIn, fileOut))
fmt.Printf("Render File %s/%s has been added to your config file.\n", fileIn, fileOut)
fmt.Printf("To render the file use: git-secrets render %s or git-secrets render %s -c <contextName>\n", targetName, targetName)
fmt.Printf("To render the file use: git secrets render %s or git secrets render %s -c <contextName>\n", targetName, targetName)
},
}

Expand Down
8 changes: 4 additions & 4 deletions cmd/get.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ var getConfigCmd = &cobra.Command{
Use: "config",
Short: "Get a config entry from the config file",
Example: `
git-secrets get config <configKey>
git-secrets get config <configKey> -c prod
git secrets get config <configKey>
git secrets get config <configKey> -c prod
`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cobra.CheckErr(projectCfgError)
Expand All @@ -41,8 +41,8 @@ var getSecretCmd = &cobra.Command{
Use: "secret",
Short: "Get and decode a secret entry from the config file",
Example: `
git-secrets get secret <secretName>
git-secrets get secret <secretName> -c prod
git secrets get secret <secretName>
git secrets get secret <secretName> -c prod
`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cobra.CheckErr(projectCfgError)
Expand Down
8 changes: 4 additions & 4 deletions cmd/global_secrets.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ var getGlobalSecretsCmd = &cobra.Command{
Use: "global-secret",
Short: "Get or list a secret from the global configuration",
Example: `
git-secrets get global-secrets: get all global secret keys
git-secrets get global-secret <secretKey>: prints the global secret value
git secrets get global-secrets: get all global secret keys
git secrets get global-secret <secretKey>: prints the global secret value
`,
Aliases: []string{"global-secrets", "gs"},
Args: cobra.RangeArgs(0, 1),
Expand All @@ -39,8 +39,8 @@ var setGlobalSecretsCmd = &cobra.Command{
Use: "global-secret",
Short: "Write a secret to the global configuration",
Example: `
git-secrets set global-secret <secretKey>: sets the global secret from terminal input
git-secrets set global-secret <secretKey> --value $MY_SECRET_VALUE_STORED_IN_ENV: sets the global secret value from --value parameter (insecure)
git secrets set global-secret <secretKey>: sets the global secret from terminal input
git secrets set global-secret <secretKey> --value $MY_SECRET_VALUE_STORED_IN_ENV: sets the global secret value from --value parameter (insecure)
`,
Aliases: []string{"global-secrets", "gs"},
Args: cobra.ExactArgs(1),
Expand Down
6 changes: 3 additions & 3 deletions cmd/info.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,9 @@ var infoCmd = &cobra.Command{
Use: "info",
Short: "Get detailed information about the current configuration",
Example: `
git-secrets info
git-secrets info -d: Also decodes all secrets
git-secrets info -d -c prod: Decodes all secrets from the prod context
git secrets info
git secrets info -d: Also decodes all secrets
git secrets info -d -c prod: Decodes all secrets from the prod context
`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cobra.CheckErr(projectCfgError)
Expand Down
13 changes: 7 additions & 6 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@ import (
// initCmd represents the init command
var initCmd = &cobra.Command{
Use: "init",
Short: "Initializes a new .git-secrets.json Project",
Short: "Initializes a new .git-secrets.json project",
Example: `
git-secrets init
git secrets init
git secrets init -f custom-file-name.json
`,
Args: cobra.MaximumNArgs(1),
Run: func(cmd *cobra.Command, args []string) {
Expand Down Expand Up @@ -81,10 +82,10 @@ git-secrets init
}

fmt.Println(questionResponse.OutputFile, "written")
fmt.Println("Info: git-secrets info -d")
fmt.Println("Add Context: git-secrets add context <contextName>")
fmt.Println("Set Config: git-secrets set config <configKey> <configValue>")
fmt.Println("Set Secret: git-secrets set secret <secretKey>")
fmt.Println("Info: git secrets info -d")
fmt.Println("Add Context: git secrets add context <contextName>")
fmt.Println("Set Config: git secrets set config <configKey> <configValue>")
fmt.Println("Set Secret: git secrets set secret <secretKey>")

},
}
Expand Down
20 changes: 10 additions & 10 deletions cmd/render.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,17 +20,17 @@ var renderCmd = &cobra.Command{
Use: "render",
Short: "Render files using the go templating engine",
Example: `
git-secrets render <targetName>: Render from configuration
git-secrets render <targetName1>,<targetName2>,...: Renders multiple targets at once
git-secrets render <fileIn> <fileOut> --debug: Render a specific file instead of the configured ones
git-secrets render <targetName> -c prod: Render files for the prod context
git-secrets render <targetName> --dry-run: Render files and print them to the console
git-secrets render <targetName> --dry-run --debug: Dry run render and shows the rendering context
git-secrets render <targetName> --debug: Render and write the rendering target
git secrets render <targetName>: Render from configuration
git secrets render <targetName1>,<targetName2>,...: Renders multiple targets at once
git secrets render <fileIn> <fileOut> --debug: Render a specific file instead of the configured ones
git secrets render <targetName> -c prod: Render files for the prod context
git secrets render <targetName> --dry-run: Render files and print them to the console
git secrets render <targetName> --dry-run --debug: Dry run render and shows the rendering context
git secrets render <targetName> --debug: Render and write the rendering target
`,
Args: func(cmd *cobra.Command, args []string) error {
if !(len(args) == 0 || len(args) == 1 || len(args) == 2) {
return fmt.Errorf("usage: git-secrets render <target> or git-secrets render <file-in> <file-out>")
return fmt.Errorf("usage: git secrets render <target> or git secrets render <file-in> <file-out>")
}
return nil
},
Expand All @@ -44,8 +44,8 @@ git-secrets render <targetName> --debug: Render and write the rendering target

var filesToRender []*config_generic.FileToRender
if len(args) == 0 {
fmt.Println("Usage: git-secrets render <targetName1>,<targetName2>,...")
fmt.Println("Render using another context: git-secrets render <targetName> -c <contextName>")
fmt.Println("Usage: git secrets render <targetName1>,<targetName2>,...")
fmt.Println("Render using another context: git secrets render <targetName> -c <contextName>")
cobra.CheckErr(fmt.Errorf("You must specify a rendering context. Available targets: %s", strings.Join(projectCfg.RenderTargetNames(), ", ")))
} else if len(args) == 1 {

Expand Down
12 changes: 6 additions & 6 deletions cmd/set.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,8 @@ var setConfigCmd = &cobra.Command{
Use: "config",
Short: "Set a config entry",
Example: `
git-secrets set config <configKey> <configValue>
git-secrets set config <configKey> <configValue> -c prod
git secrets set config <configKey> <configValue>
git secrets set config <configKey> <configValue> -c prod
`,
PersistentPreRun: func(cmd *cobra.Command, args []string) {
cobra.CheckErr(projectCfgError)
Expand All @@ -33,7 +33,7 @@ git-secrets set config <configKey> <configValue> -c prod
configWrite := projectCfg.GetConfigWriter()
cobra.CheckErr(configWrite.SetConfig(projectCfg.GetCurrent().Name, configKey, configValue, force))
fmt.Printf("The config entry %s has been written\n", configKey)
fmt.Printf("Resolve the value: git-secrets get config %s\n", configKey)
fmt.Printf("Resolve the value: git secrets get config %s\n", configKey)
fmt.Printf("Use it in a template: MY_CONFIG_KEY={{.Configs.%s}}\n", configKey)
},
}
Expand All @@ -43,8 +43,8 @@ var setSecretCmd = &cobra.Command{
Use: "secret",
Short: "Encode and write a secret to the config file",
Example: `
git-secrets set secret <secretKey>: Encodes the secret using interactive ui and adds it to the git-secrets file
git-secrets set secret <secretKey> --value <plainValue>: INSECURE: Uses the value directly from the --value parameter
git secrets set secret <secretKey>: Encodes the secret using interactive ui and adds it to the git secrets file
git secrets set secret <secretKey> --value <plainValue>: INSECURE: Uses the value directly from the --value parameter
`,
Args: cobra.ExactArgs(1),
PersistentPreRun: func(cmd *cobra.Command, args []string) {
Expand All @@ -71,7 +71,7 @@ git-secrets set secret <secretKey> --value <plainValue>: INSECURE: Uses the valu
cobra.CheckErr(errWrite)

fmt.Printf("The secret %s has been written\n", secretKey)
fmt.Printf("Resolve the decoded value: git-secrets get secret %s\n", secretKey)
fmt.Printf("Resolve the decoded value: git secrets get secret %s\n", secretKey)
fmt.Printf("Use it in a template: MY_CONFIG_KEY={{.Secrets.%s}}\n", secretKey)

},
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ require (
github.com/mitchellh/mapstructure v1.4.3 // indirect
github.com/pelletier/go-toml v1.9.4 // indirect
github.com/pmezard/go-difflib v1.0.0 // indirect
github.com/spf13/afero v1.9.2 // indirect
github.com/spf13/cast v1.4.1 // indirect
github.com/spf13/jwalterweatherman v1.1.0 // indirect
github.com/spf13/pflag v1.0.5 // indirect
Expand All @@ -48,5 +47,6 @@ require (
require (
github.com/AlecAivazis/survey/v2 v2.3.4
github.com/onsi/gomega v1.19.0 // indirect
github.com/spf13/afero v1.9.2
github.com/tcnksm/go-gitconfig v0.1.2
)
1 change: 0 additions & 1 deletion go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,6 @@ github.com/sirupsen/logrus v1.2.0/go.mod h1:LxeOpSwHxABJmUn/MG1IvRgCAasNZTLOkJPx
github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE=
github.com/spaolacci/murmur3 v0.0.0-20180118202830-f09979ecbc72/go.mod h1:JwIasOWyU6f++ZhiEuf87xNszmSA2myDM2Kzu9HwQUA=
github.com/spf13/afero v1.3.3/go.mod h1:5KUK8ByomD5Ti5Artl0RtHeI5pTF7MIDuXL3yY520V4=
github.com/spf13/afero v1.6.0 h1:xoax2sJ2DT8S8xA2paPFjDCScCNeWsg75VG0DLRreiY=
github.com/spf13/afero v1.6.0/go.mod h1:Ai8FlHk4v/PARR026UzYexafAt9roJ7LcLMAmO6Z93I=
github.com/spf13/afero v1.9.2 h1:j49Hj62F0n+DaZ1dDCvhABaPNSGNkt32oRFxI33IEMw=
github.com/spf13/afero v1.9.2/go.mod h1:iUV7ddyEEZPO5gA3zD4fJt6iStLlL+Lg4m2cihcDf8Y=
Expand Down
3 changes: 3 additions & 0 deletions pkg/config/generic/repository_root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,13 @@ import (
//go:embed test_fs
var testFiles embed.FS

type TestFile string

const GlobalSecretKey = "gitSecretsTest"
const GlobalSecretValue = "eeSaoghoh8oi9leed7hai4looK3jae1N"

const TestFileBlankDefault = "generic_repository_test-blank-default.json"
const TestFileBlankDefaultFromEnv = "generic_repository_test-blank-default-from-env.json"
const TestFileBlankTwoContexts = "generic_repository_test-blank-two-contexts.json"
const TestFileBlankInvalidVersion = "generic_repository_test-generic_repository_test-invalid-version.json"
const TestFileConfigEntries = "generic_repository_test-config-entries.json"
Expand Down
7 changes: 2 additions & 5 deletions pkg/config/generic/schema_v1.go
Original file line number Diff line number Diff line change
Expand Up @@ -242,13 +242,10 @@ func ParseSchemaV1(jsonInput []byte, configFileUsed string, globalConfig *global
}

func getSecretResolverV1(val *V1DecryptSecret, defaultContext *Context, globalConfig *global_config.GlobalConfigProvider, overwrittenSecrets map[string]string) encryption.SecretResolver {
if val == nil {
return defaultContext.SecretResolver
}
if val.FromEnv != "" {
if val != nil && val.FromEnv != "" {
return encryption.NewEnvSecretResolver(val.FromEnv)
}
if val.FromName != "" {
if val != nil && val.FromName != "" {
return encryption.NewMergedSecretResolver(val.FromName, globalConfig, overwrittenSecrets)
}
return defaultContext.SecretResolver
Expand Down
87 changes: 85 additions & 2 deletions pkg/config/generic/schema_v1_test.go
Original file line number Diff line number Diff line change
@@ -1,21 +1,104 @@
package config_generic

import (
"encoding/json"
"fmt"
global_config "github.com/benammann/git-secrets/pkg/config/global"
"github.com/benammann/git-secrets/pkg/encryption"
"github.com/spf13/afero"
"github.com/stretchr/testify/assert"
"testing"
)

func TestIsSchemaV1(t *testing.T) {
func ParseAsSchemaV1(t *testing.T, fileName TestFile) V1Schema {
fs := afero.FromIOFS{
FS: testFiles,
}
fileBytes, errRead := afero.ReadFile(fs, fmt.Sprintf("test_fs/schema/v1/%s", fileName))
assert.NoError(t, errRead)

var Parsed V1Schema
errParse := json.Unmarshal(fileBytes, &Parsed)
assert.NoError(t, errParse)
return Parsed

}

func TestIsSchemaV1(t *testing.T) {
assert.True(t, IsSchemaV1(1))
assert.False(t, IsSchemaV1(2))
assert.False(t, IsSchemaV1(0))
}

func TestParseSchemaV1(t *testing.T) {

}

func TestV1Schema_validateSchemaV1(t *testing.T) {

t.Run("fail on unsupported versions", func(t *testing.T) {
parsed := ParseAsSchemaV1(t, "v2.json")
assert.Equal(t, parsed.Version, 2)
assert.Error(t, parsed.validateSchemaV1())
})
t.Run("fail if default ctx is missing", func(t *testing.T) {
parsed := ParseAsSchemaV1(t, "no-default-ctx.json")
assert.Error(t, parsed.validateSchemaV1())
})
t.Run("fail is multiple decrypt secret methods passed", func(t *testing.T) {
parsed := ParseAsSchemaV1(t, "many-decrypt-secrets.json")
assert.NotEqual(t, "", parsed.Context["default"].DecryptSecret.FromEnv)
assert.NotEqual(t, "", parsed.Context["default"].DecryptSecret.FromName)
assert.Error(t, parsed.validateSchemaV1())
})
t.Run("fail if no decrypt method on default ctx", func(t *testing.T) {
parsed := ParseAsSchemaV1(t, "no-decrypt-secret-on-default.json")
assert.Equal(t, "", parsed.Context["default"].DecryptSecret.FromEnv)
assert.Equal(t, "", parsed.Context["default"].DecryptSecret.FromName)
assert.Error(t, parsed.validateSchemaV1())
})
t.Run("fail if secret is defined in child but not in default context", func(t *testing.T) {
parsed := ParseAsSchemaV1(t, "secret-missing-in-default.json")
assert.Equal(t, "", parsed.Context["default"].Secrets["test"])
assert.NotEqual(t, "", parsed.Context["prod"].Secrets["test"])
assert.Error(t, parsed.validateSchemaV1())
})
t.Run("fail if config is defined in child but not in default context", func(t *testing.T) {
parsed := ParseAsSchemaV1(t, "config-missing-in-default.json")
assert.Equal(t, "", parsed.Context["default"].Configs["test"])
assert.NotEqual(t, "", parsed.Context["prod"].Configs["test"])
assert.Error(t, parsed.validateSchemaV1())
})
t.Run("do not fail if schema is valid", func(t *testing.T) {
parsed := ParseAsSchemaV1(t, "real-world.json")
assert.NoError(t, parsed.validateSchemaV1())
})
}

func Test_getSecretResolverV1(t *testing.T) {

globalConfig := global_config.NewGlobalConfigProvider(global_config.NewMemoryStorageProvider())
_ = globalConfig.SetSecret(GlobalSecretKey, GlobalSecretValue, false)
mergeGlobalSecrets := make(map[string]string)

t.Run("return secret resolver from default context if no config given", func(t *testing.T) {
repo := initRepository(t, TestFileBlankDefault, "default")
defaultCtx := repo.GetContext("default")
assert.NotNil(t, defaultCtx)
assert.NotNil(t, defaultCtx.SecretResolver)
assert.Equal(t, defaultCtx.SecretResolver, getSecretResolverV1(nil, defaultCtx, globalConfig, mergeGlobalSecrets))
})
t.Run("return from env secret resolver", func(t *testing.T) {
repo := initRepository(t, TestFileBlankDefaultFromEnv, "default")
defaultCtx := repo.GetContext("default")
assert.NotNil(t, defaultCtx)
assert.NotNil(t, defaultCtx.SecretResolver)
assert.IsType(t, &encryption.FromEnvSecretResolver{}, defaultCtx.SecretResolver)
})
t.Run("return from name secret resolver", func(t *testing.T) {
repo := initRepository(t, TestFileBlankDefault, "default")
defaultCtx := repo.GetContext("default")
assert.NotNil(t, defaultCtx)
assert.NotNil(t, defaultCtx.SecretResolver)
assert.IsType(t, &encryption.MergedSecretResolver{}, defaultCtx.SecretResolver)
})
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
{
"$schema": "https://raw.githubusercontent.com/benammann/git-secrets/dev-beta/schema/def/v1.json",
"version": 1,
"context": {
"default": {
"decryptSecret": {
"fromEnv": "GIT_SECRETS_TEST"
},
"secrets": {
"test": "l5sqnu8UkO+PdW2fZo7IMhfHng7lf6XNXEfRhQ/fvboP1HqcRFcu",
"test2": "jgsBrbR63TbR3gr7hqPcOdEhaCgooFy3rC6ezusRZnDZ"
}
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"$schema": "https://raw.githubusercontent.com/benammann/git-secrets/dev-beta/schema/def/v1.json",
"version": 1,
"context": {
"default": {
"decryptSecret": {
"fromName": "gitsecretstest"
},
"configs": {
}
},
"prod": {
"configs": {
"test": "test-value"
}
}
}
}
Loading

0 comments on commit 6f7bd09

Please sign in to comment.