Skip to content

Commit f589acc

Browse files
commit111lionello
andauthored
Add --random flag for generating random config values (#1040)
* add random config generator * refine else if statement * take out interactive prompt * add test for CreateRandomConfigValue() * add go mod and go sum * edit vendor hash * edit detector to use logic instead of json * edit entropy comment * edit flag description * Update src/go.mod --------- Co-authored-by: Lio李歐 <[email protected]>
1 parent 8d1be6e commit f589acc

File tree

3 files changed

+78
-0
lines changed

3 files changed

+78
-0
lines changed

src/cmd/cli/command/commands.go

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -223,6 +223,7 @@ func SetupCommands(ctx context.Context, version string) {
223223
// Config Command (was: secrets)
224224
configSetCmd.Flags().BoolP("name", "n", false, "name of the config (backwards compat)")
225225
configSetCmd.Flags().BoolP("env", "e", false, "set the config from an environment variable")
226+
configSetCmd.Flags().Bool("random", false, "set a secure randomly generated value for config")
226227
_ = configSetCmd.Flags().MarkHidden("name")
227228

228229
configCmd.AddCommand(configSetCmd)
@@ -699,6 +700,7 @@ var configSetCmd = &cobra.Command{
699700
Short: "Adds or updates a sensitive config value",
700701
RunE: func(cmd *cobra.Command, args []string) error {
701702
fromEnv, _ := cmd.Flags().GetBool("env")
703+
random, _ := cmd.Flags().GetBool("random")
702704

703705
// Make sure we have a project to set config for before asking for a value
704706
loader := configureLoader(cmd)
@@ -749,6 +751,10 @@ var configSetCmd = &cobra.Command{
749751
}
750752
// Trim the newline at the end because single line values are common
751753
value = strings.TrimSuffix(string(bytes), "\n")
754+
} else if random {
755+
// Generate a random value for the config
756+
value = CreateRandomConfigValue()
757+
term.Info("Generated random value: " + value)
752758
} else {
753759
// Prompt for sensitive value
754760
var sensitivePrompt = &survey.Password{
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
package command
2+
3+
import (
4+
"crypto/rand"
5+
"encoding/base64"
6+
"regexp"
7+
)
8+
9+
func CreateRandomConfigValue() string {
10+
// Note that no error handling is necessary, as Read always succeeds.
11+
key := make([]byte, 32)
12+
rand.Read(key)
13+
str := base64.StdEncoding.EncodeToString(key)
14+
re := regexp.MustCompile("[+/=]")
15+
str = re.ReplaceAllString(str, "")
16+
return str
17+
}
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
package command
2+
3+
import (
4+
"testing"
5+
6+
"github.com/DefangLabs/secret-detector/pkg/scanner"
7+
)
8+
9+
func TestCreateRandomConfigValue(t *testing.T) {
10+
// create a scanner config
11+
cfg := scanner.NewConfigWithDefaults()
12+
13+
// adjust the entropy threshold value for the "high_entropy_string" detector.
14+
// this will affect the level of randomness that is tolerated in a string
15+
// (0 = low entropy, 4+ = very high entropy)
16+
cfg.DetectorConfigs["high_entropy_string"] = []string{"3"}
17+
18+
// create the scanner based on scanner config
19+
scannerClient, err := scanner.NewScannerFromConfig(cfg)
20+
if err != nil {
21+
t.Fatalf("Failed to make a config detector: " + err.Error())
22+
}
23+
24+
// a map for storing generated results to check if they are unique
25+
var uniqueConfigList = make(map[string]bool)
26+
27+
var testIterations = 5
28+
for range testIterations {
29+
// call the function to create a random config
30+
randomConfig := CreateRandomConfigValue()
31+
32+
// store generated configs as unique keys in a map
33+
uniqueConfigList[randomConfig] = true
34+
35+
// scan the config
36+
ds, err := scannerClient.Scan(randomConfig)
37+
if err != nil {
38+
t.Fatalf("Failed to scan input: " + err.Error())
39+
}
40+
41+
// the length of ds (detected secrets) should be one
42+
for _, d := range ds {
43+
// check if the config meets the threshold for high entropy (randomness)
44+
if d.Type != "High entropy string" {
45+
t.Errorf("did not meet the entropy threshold: generated value of %q", randomConfig)
46+
}
47+
}
48+
}
49+
50+
// check if the length of the map matches the number of test iterations (should be equal if all keys are unique)
51+
numOfUniqueConfigs := len(uniqueConfigList)
52+
if numOfUniqueConfigs < testIterations {
53+
t.Errorf("generated result was not unique: expected numOfUniqueConfigs to be %d, but got %d", testIterations, numOfUniqueConfigs)
54+
}
55+
}

0 commit comments

Comments
 (0)