| 1 | // SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | |
| 3 | package specutil |
| 4 | |
| 5 | import ( |
| 6 | "fmt" |
| 7 | "regexp" |
| 8 | "strings" |
| 9 | |
| 10 | "github.com/netdata/netdata/go/plugins/plugin/agent/secrets/secretstore" |
| 11 | "github.com/netdata/netdata/go/plugins/plugin/agent/secrets/secretstore/internal/envx" |
| 12 | ) |
| 13 | |
| 14 | var reStoreName = regexp.MustCompile(`^[A-Za-z0-9_]+$`) |
| 15 | |
| 16 | func NormalizeStoreName(name string) (string, error) { |
| 17 | name = strings.TrimSpace(name) |
| 18 | if name == "" { |
| 19 | return "", fmt.Errorf("store name is required") |
| 20 | } |
| 21 | if !reStoreName.MatchString(name) { |
| 22 | return "", fmt.Errorf("store name '%s' must match %s", name, reStoreName.String()) |
| 23 | } |
| 24 | return name, nil |
| 25 | } |
| 26 | |
| 27 | func ValidateStoreKind(key string, kind, expected secretstore.StoreKind) error { |
| 28 | if !kind.IsValid() { |
| 29 | return fmt.Errorf("store '%s': invalid kind '%s'", key, kind) |
| 30 | } |
| 31 | if kind != expected { |
| 32 | return fmt.Errorf("store '%s': invalid kind '%s'", key, kind) |
| 33 | } |
| 34 | return nil |
| 35 | } |
| 36 | |
| 37 | func RequireEnvSelector(v, path string) (string, error) { |
| 38 | v = strings.TrimSpace(v) |
| 39 | if v == "" { |
| 40 | return "", fmt.Errorf("%s is required", path) |
| 41 | } |
| 42 | if err := envx.ValidateSelector(v, path); err != nil { |
| 43 | return "", err |
| 44 | } |
| 45 | return v, nil |
| 46 | } |
| 47 | |
| 48 | func OptionalEnvSelector(v, path string) (string, error) { |
| 49 | v = strings.TrimSpace(v) |
| 50 | if v == "" { |
| 51 | return "", nil |
| 52 | } |
| 53 | if err := envx.ValidateSelector(v, path); err != nil { |
| 54 | return "", err |
| 55 | } |
| 56 | return v, nil |
| 57 | } |