aws.go 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. package aws
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "github.com/hashicorp/vault/api/auth/aws"
  6. )
  7. // AuthOptions defines the configuration options added using the
  8. // VaultOptions.AuthOptions field when AuthType is aws.
  9. // This maps directly to Vault's AWS Login options,
  10. // see: https://developer.hashicorp.com/vault/api-docs/auth/aws#login
  11. type AuthOptions struct {
  12. Role string `json:"role,omitempty"`
  13. Region string `json:"region,omitempty"`
  14. AwsAuthType string `json:"awsAuthType,omitempty"`
  15. // options specific to 'iam' auth type
  16. IamServerIDHeader string `json:"iamServerIdHeader"`
  17. // options specific to 'ec2' auth type
  18. SignatureType string `json:"signatureType,omitempty"`
  19. Nonce string `json:"nonce,omitempty"`
  20. }
  21. func NewAwsAuthMethod(mountPath string, options json.RawMessage) (*aws.AWSAuth, error) {
  22. var opts *AuthOptions
  23. err := json.Unmarshal(options, &opts)
  24. if err != nil {
  25. return nil, fmt.Errorf("error decoding AWS auth options: %w", err)
  26. }
  27. var awsAuth *aws.AWSAuth
  28. var loginOptions []aws.LoginOption
  29. if mountPath != "" {
  30. loginOptions = append(loginOptions, aws.WithMountPath(mountPath))
  31. }
  32. if opts.Role != "" {
  33. loginOptions = append(loginOptions, aws.WithRole(opts.Role))
  34. }
  35. if opts.Region != "" {
  36. loginOptions = append(loginOptions, aws.WithRegion(opts.Region))
  37. }
  38. switch opts.AwsAuthType {
  39. case "iam":
  40. loginOptions = append(loginOptions, aws.WithIAMAuth())
  41. if opts.IamServerIDHeader != "" {
  42. loginOptions = append(loginOptions, aws.WithIAMServerIDHeader(opts.IamServerIDHeader))
  43. }
  44. case "ec2":
  45. loginOptions = append(loginOptions, aws.WithEC2Auth())
  46. switch opts.SignatureType {
  47. case "pkcs7":
  48. loginOptions = append(loginOptions, aws.WithPKCS7Signature())
  49. case "identity":
  50. loginOptions = append(loginOptions, aws.WithIdentitySignature())
  51. case "rsa2048":
  52. loginOptions = append(loginOptions, aws.WithRSA2048Signature())
  53. case "":
  54. // no-op
  55. default:
  56. return nil, fmt.Errorf("unknown SignatureType type %q; valid options are 'pkcs7', 'identity' and 'rsa2048'", opts.SignatureType)
  57. }
  58. if opts.Nonce != "" {
  59. loginOptions = append(loginOptions, aws.WithNonce(opts.Nonce))
  60. }
  61. default:
  62. return nil, fmt.Errorf("unknown awsAuthType %q; valid options are 'iam' and 'ec2'", opts.AwsAuthType)
  63. }
  64. awsAuth, err = aws.NewAWSAuth(loginOptions...)
  65. if err != nil {
  66. return nil, fmt.Errorf("unable to initialize AWS auth method: %w", err)
  67. }
  68. return awsAuth, nil
  69. }