NewManager creates a new credentials manager that uses Hashicorp Vault as backend Configured to write secrets in the KVv2 engine referenced by the provided mount path. SecretPrefix is used to namespace secrets in the KVv2 engine during write operations.
(opts *NewManagerOpts)
| 59 | // Configured to write secrets in the KVv2 engine referenced by the provided mount path. |
| 60 | // SecretPrefix is used to namespace secrets in the KVv2 engine during write operations. |
| 61 | func NewManager(opts *NewManagerOpts) (*Manager, error) { |
| 62 | if opts.AuthToken == "" || opts.Address == "" { |
| 63 | return nil, errors.New("auth token and instance address are required") |
| 64 | } |
| 65 | |
| 66 | config := vault.DefaultConfig() |
| 67 | config.Address = opts.Address |
| 68 | config.Timeout = 1 * time.Second |
| 69 | |
| 70 | client, err := vault.NewClient(config) |
| 71 | if err != nil { |
| 72 | return nil, err |
| 73 | } |
| 74 | |
| 75 | client.SetToken(opts.AuthToken) |
| 76 | |
| 77 | mountPath := defaultKVMountPath |
| 78 | if opts.MountPath != "" { |
| 79 | mountPath = opts.MountPath |
| 80 | } |
| 81 | |
| 82 | l := opts.Logger |
| 83 | if l == nil { |
| 84 | l = log.NewStdLogger(io.Discard) |
| 85 | } |
| 86 | |
| 87 | logger := servicelogger.ScopedHelper(l, "credentials/vault") |
| 88 | logger.Infow("msg", "configuring vault", "address", opts.Address, "mount_path", mountPath, "prefix", opts.SecretPrefix, "role", opts.Role) |
| 89 | |
| 90 | // Check address, token validity and mount path |
| 91 | kv := client.KVv2(mountPath) |
| 92 | if opts.Role == credentials.RoleReader { |
| 93 | if err := validateReaderClient(kv, opts.SecretPrefix); err != nil { |
| 94 | return nil, fmt.Errorf("validating client: %w", err) |
| 95 | } |
| 96 | } else { |
| 97 | if err := validateWriterClient(kv, opts.SecretPrefix); err != nil { |
| 98 | return nil, fmt.Errorf("validating client: %w", err) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | return &Manager{kv, opts.SecretPrefix, logger}, nil |
| 103 | } |
| 104 | |
| 105 | // validateWriterClient checks if the client is valid by writing and deleting a secret |
| 106 | // in the provided mount path. |