certificates/cas/vaultcas/auth/approle/approle.go

68 lines
1.9 KiB
Go
Raw Normal View History

2022-05-09 13:27:37 +02:00
package approle
import (
"encoding/json"
2022-05-15 17:42:08 +02:00
"errors"
2022-05-09 13:27:37 +02:00
"fmt"
"github.com/hashicorp/vault/api/auth/approle"
)
// AuthOptions defines the configuration options added using the
// VaultOptions.AuthOptions field when AuthType is approle
type AuthOptions struct {
RoleID string `json:"roleID,omitempty"`
SecretID string `json:"secretID,omitempty"`
2022-05-15 17:42:08 +02:00
SecretIDFile string `json:"secretIDFile,omitempty"`
SecretIDEnv string `json:"secretIDEnv,omitempty"`
2022-05-09 13:27:37 +02:00
IsWrappingToken bool `json:"isWrappingToken,omitempty"`
}
func NewApproleAuthMethod(mountPath string, options json.RawMessage) (*approle.AppRoleAuth, error) {
var opts *AuthOptions
err := json.Unmarshal(options, &opts)
if err != nil {
return nil, fmt.Errorf("error decoding AppRole auth options: %w", err)
}
var approleAuth *approle.AppRoleAuth
var loginOptions []approle.LoginOption
if mountPath != "" {
loginOptions = append(loginOptions, approle.WithMountPath(mountPath))
}
if opts.IsWrappingToken {
loginOptions = append(loginOptions, approle.WithWrappingToken())
}
2022-05-15 17:42:08 +02:00
if opts.RoleID == "" {
return nil, errors.New("you must set roleID")
}
var sid approle.SecretID
2022-05-17 22:13:11 +02:00
switch {
case opts.SecretID != "" && opts.SecretIDFile == "" && opts.SecretIDEnv == "":
2022-05-15 17:42:08 +02:00
sid = approle.SecretID{
FromString: opts.SecretID,
}
2022-05-17 22:13:11 +02:00
case opts.SecretIDFile != "" && opts.SecretID == "" && opts.SecretIDEnv == "":
2022-05-15 17:42:08 +02:00
sid = approle.SecretID{
FromFile: opts.SecretIDFile,
}
2022-05-17 22:13:11 +02:00
case opts.SecretIDEnv != "" && opts.SecretIDFile == "" && opts.SecretID == "":
2022-05-15 17:42:08 +02:00
sid = approle.SecretID{
FromEnv: opts.SecretIDEnv,
}
2022-05-17 22:13:11 +02:00
default:
2022-05-15 17:42:08 +02:00
return nil, errors.New("you must set one of secretID, secretIDFile or secretIDEnv")
2022-05-09 13:27:37 +02:00
}
approleAuth, err = approle.NewAppRoleAuth(opts.RoleID, &sid, loginOptions...)
if err != nil {
return nil, fmt.Errorf("unable to initialize Kubernetes auth method: %w", err)
}
return approleAuth, nil
}