Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Session tags and external id support for AWS Secrets #18813

Closed
wants to merge 7 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 38 additions & 1 deletion builtin/logical/aws/path_roles.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/aws/aws-sdk-go/aws/arn"
"github.com/hashicorp/go-multierror"
"github.com/hashicorp/go-secure-stdlib/strutil"

"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/consts"
"github.com/hashicorp/vault/sdk/logical"
Expand Down Expand Up @@ -115,7 +116,23 @@ delimited key pairs.`,
Value: "[key1=value1, key2=value2]",
},
},

"session_tags": {
Type: framework.TypeKVPairs,
Description: fmt.Sprintf(`Session tags to be set for %q creds created by this role. These must be presented
as Key-Value pairs. This can be represented as a map or a list of equal sign
delimited key pairs.`, assumedRoleCred),
DisplayAttrs: &framework.DisplayAttributes{
Name: "Session Tags",
Value: "[key1=value1, key2=value2]",
},
},
"external_id": {
Type: framework.TypeString,
Description: "External ID to set when assuming the role; only valid when credential_type is " + assumedRoleCred,
DisplayAttrs: &framework.DisplayAttributes{
Name: "External ID",
},
},
"default_sts_ttl": {
Type: framework.TypeDurationSecond,
Description: fmt.Sprintf("Default TTL for %s, %s, and %s credential types when no TTL is explicitly requested with the credentials", assumedRoleCred, federationTokenCred, sessionTokenCred),
Expand Down Expand Up @@ -341,6 +358,14 @@ func (b *backend) pathRolesWrite(ctx context.Context, req *logical.Request, d *f
roleEntry.SerialNumber = serialNumber.(string)
}

if sessionTags, ok := d.GetOk("session_tags"); ok {
roleEntry.SessionTags = sessionTags.(map[string]string)
}

if externalID, ok := d.GetOk("external_id"); ok {
roleEntry.ExternalID = externalID.(string)
}

if legacyRole != "" {
roleEntry = upgradeLegacyPolicyEntry(legacyRole)
if roleEntry.InvalidData != "" {
Expand Down Expand Up @@ -527,6 +552,8 @@ type awsRoleEntry struct {
PolicyDocument string `json:"policy_document"` // JSON-serialized inline policy to attach to IAM users and/or to specify as the Policy parameter in AssumeRole calls
IAMGroups []string `json:"iam_groups"` // Names of IAM groups that generated IAM users will be added to
IAMTags map[string]string `json:"iam_tags"` // IAM tags that will be added to the generated IAM users
SessionTags map[string]string `json:"session_tags"` // Session tags that will be added as Tags parameter in AssumedRole calls
ExternalID string `json:"external_id"` // External ID to added as ExternalID in AssumeRole calls
InvalidData string `json:"invalid_data,omitempty"` // Invalid role data. Exists to support converting the legacy role data into the new format
ProhibitFlexibleCredPath bool `json:"prohibit_flexible_cred_path,omitempty"` // Disallow accessing STS credentials via the creds path and vice verse
Version int `json:"version"` // Version number of the role format
Expand All @@ -545,6 +572,8 @@ func (r *awsRoleEntry) toResponseData() map[string]interface{} {
"policy_document": r.PolicyDocument,
"iam_groups": r.IAMGroups,
"iam_tags": r.IAMTags,
"session_tags": r.SessionTags,
"external_id": r.ExternalID,
"default_sts_ttl": int64(r.DefaultSTSTTL.Seconds()),
"max_sts_ttl": int64(r.MaxSTSTTL.Seconds()),
"user_path": r.UserPath,
Expand Down Expand Up @@ -612,6 +641,14 @@ func (r *awsRoleEntry) validate() error {
errors = multierror.Append(errors, fmt.Errorf("cannot supply role_arns when credential_type isn't %s", assumedRoleCred))
}

if len(r.SessionTags) > 0 && !strutil.StrListContains(r.CredentialTypes, assumedRoleCred) {
errors = multierror.Append(errors, fmt.Errorf("cannot supply session_tags when credential_type isn't %s", assumedRoleCred))
}

if r.ExternalID != "" && !strutil.StrListContains(r.CredentialTypes, assumedRoleCred) {
errors = multierror.Append(errors, fmt.Errorf("cannot supply external_id when credential_type isn't %s", assumedRoleCred))
}

return errors.ErrorOrNil()
}

Expand Down
80 changes: 70 additions & 10 deletions builtin/logical/aws/path_roles_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,14 @@ package aws

import (
"context"
"errors"
"reflect"
"strconv"
"strings"
"testing"

"github.com/hashicorp/go-multierror"

"github.com/hashicorp/vault/sdk/logical"
)

Expand Down Expand Up @@ -366,22 +369,74 @@ func TestRoleEntryValidationIamUserCred(t *testing.T) {
CredentialTypes: []string{iamUserCred},
RoleArns: []string{"arn:aws:iam::123456789012:role/SomeRole"},
}
if roleEntry.validate() == nil {
t.Errorf("bad: invalid roleEntry with invalid RoleArns parameter %#v passed validation", roleEntry)
}
assertMultiError(t, roleEntry.validate(),
[]error{
errors.New(
"cannot supply role_arns when credential_type isn't assumed_role",
),
})

roleEntry = awsRoleEntry{
CredentialTypes: []string{iamUserCred},
PolicyArns: []string{adminAccessPolicyARN},
DefaultSTSTTL: 1,
}
if roleEntry.validate() == nil {
t.Errorf("bad: invalid roleEntry with unrecognized DefaultSTSTTL %#v passed validation", roleEntry)
}
assertMultiError(t, roleEntry.validate(),
[]error{
errors.New(
"default_sts_ttl parameter only valid for assumed_role, federation_token, and session_token credential types",
),
})
roleEntry.DefaultSTSTTL = 0

roleEntry.MaxSTSTTL = 1
if roleEntry.validate() == nil {
t.Errorf("bad: invalid roleEntry with unrecognized MaxSTSTTL %#v passed validation", roleEntry)
assertMultiError(t, roleEntry.validate(),
[]error{
errors.New(
"max_sts_ttl parameter only valid for assumed_role, federation_token, and session_token credential types",
),
})
roleEntry.MaxSTSTTL = 0

roleEntry.SessionTags = map[string]string{
"Key1": "Value1",
"Key2": "Value2",
}
assertMultiError(t, roleEntry.validate(),
[]error{
errors.New(
"cannot supply session_tags when credential_type isn't assumed_role",
),
})
roleEntry.SessionTags = nil

roleEntry.ExternalID = "my-ext-id"
assertMultiError(t, roleEntry.validate(),
[]error{
errors.New(
"cannot supply external_id when credential_type isn't assumed_role"),
})
}

func assertMultiError(t *testing.T, err error, expected []error) {
t.Helper()

if err == nil {
t.Errorf("expected error, got nil")
return
}

var multiErr *multierror.Error
if errors.As(err, &multiErr) {
if multiErr.Len() != len(expected) {
t.Errorf("expected %d error, got %d", len(expected), multiErr.Len())
} else {
if !reflect.DeepEqual(expected, multiErr.Errors) {
t.Errorf("expected error %q, actual %q", expected, multiErr.Errors)
}
}
} else {
t.Errorf("expected multierror, got %T", err)
}
}

Expand All @@ -392,8 +447,13 @@ func TestRoleEntryValidationAssumedRoleCred(t *testing.T) {
RoleArns: []string{"arn:aws:iam::123456789012:role/SomeRole"},
PolicyArns: []string{adminAccessPolicyARN},
PolicyDocument: allowAllPolicyDocument,
DefaultSTSTTL: 2,
MaxSTSTTL: 3,
ExternalID: "my-ext-id",
SessionTags: map[string]string{
"Key1": "Value1",
"Key2": "Value2",
},
DefaultSTSTTL: 2,
MaxSTSTTL: 3,
}
if err := roleEntry.validate(); err != nil {
t.Errorf("bad: valid roleEntry %#v failed validation: %v", roleEntry, err)
Expand Down
2 changes: 1 addition & 1 deletion builtin/logical/aws/path_user.go
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ func (b *backend) pathCredsRead(ctx context.Context, req *logical.Request, d *fr
case !strutil.StrListContains(role.RoleArns, roleArn):
return logical.ErrorResponse(fmt.Sprintf("role_arn %q not in allowed role arns for Vault role %q", roleArn, roleName)), nil
}
return b.assumeRole(ctx, req.Storage, req.DisplayName, roleName, roleArn, role.PolicyDocument, role.PolicyArns, role.IAMGroups, ttl, roleSessionName)
return b.assumeRole(ctx, req.Storage, req.DisplayName, roleName, roleArn, role.PolicyDocument, role.PolicyArns, role.IAMGroups, ttl, roleSessionName, role.SessionTags, role.ExternalID)
case federationTokenCred:
return b.getFederationToken(ctx, req.Storage, req.DisplayName, roleName, role.PolicyDocument, role.PolicyArns, role.IAMGroups, ttl)
case sessionTokenCred:
Expand Down
16 changes: 15 additions & 1 deletion builtin/logical/aws/secret_access_keys.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"github.com/aws/aws-sdk-go/service/sts"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/go-secure-stdlib/awsutil"

"github.com/hashicorp/vault/sdk/framework"
"github.com/hashicorp/vault/sdk/helper/template"
"github.com/hashicorp/vault/sdk/logical"
Expand Down Expand Up @@ -238,7 +239,7 @@ func (b *backend) getSessionToken(ctx context.Context, s logical.Storage, serial

func (b *backend) assumeRole(ctx context.Context, s logical.Storage,
displayName, roleName, roleArn, policy string, policyARNs []string,
iamGroups []string, lifeTimeInSeconds int64, roleSessionName string) (*logical.Response, error,
iamGroups []string, lifeTimeInSeconds int64, roleSessionName string, sessionTags map[string]string, externalID string) (*logical.Response, error,
) {
// grab any IAM group policies associated with the vault role, both inline
// and managed
Expand Down Expand Up @@ -295,6 +296,19 @@ func (b *backend) assumeRole(ctx context.Context, s logical.Storage,
if len(policyARNs) > 0 {
assumeRoleInput.SetPolicyArns(convertPolicyARNs(policyARNs))
}
if externalID != "" {
assumeRoleInput.SetExternalId(externalID)
}
var tags []*sts.Tag
for k, v := range sessionTags {
tags = append(tags,
&sts.Tag{
Key: aws.String(k),
Value: aws.String(v),
},
)
}
assumeRoleInput.SetTags(tags)
tokenResp, err := stsClient.AssumeRoleWithContext(ctx, assumeRoleInput)
if err != nil {
return logical.ErrorResponse("Error assuming role: %s", err), awsutil.CheckAWSError(err)
Expand Down
5 changes: 5 additions & 0 deletions changelog/18813.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
```release-note:feature
**AWS secrets engine STS session tags support**: Adds support for setting STS
session tags when generating temporary credentials using the AWS secrets
engine.
```
19 changes: 13 additions & 6 deletions website/content/api-docs/secret/aws.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ files, or IAM/ECS instances.

- Static credentials provided to the API as a payload

- [Plugin workload identity federation](/vault/docs/secrets/aws#plugin-workload-identity-federation-wif)
- [Plugin workload identity federation](/vault/docs/secrets/aws#plugin-workload-identity-federation-wif)
credentials

- Credentials in the `AWS_ACCESS_KEY`, `AWS_SECRET_KEY`, and `AWS_REGION`
Expand Down Expand Up @@ -60,15 +60,15 @@ valid AWS credentials with proper permissions.
- `secret_key` `(string: "")` – Specifies the AWS secret access key. Must be provided with
`access_key`.

- `role_arn` `(string: "")` – <EnterpriseAlert product="vault" inline /> Role ARN to assume
- `role_arn` `(string: "")` – <EnterpriseAlert product="vault" inline /> Role ARN to assume
for plugin workload identity federation. Required with `identity_token_audience`.

- `identity_token_audience` `(string: "")` - <EnterpriseAlert product="vault" inline /> The
audience claim value for plugin identity tokens. Must match an allowed audience configured
- `identity_token_audience` `(string: "")` - <EnterpriseAlert product="vault" inline /> The
audience claim value for plugin identity tokens. Must match an allowed audience configured
for the target [IAM OIDC identity provider](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_providers_create_oidc.html#manage-oidc-provider-console).
Mutually exclusive with `access_key`.

- `identity_token_ttl` `(string/int: 3600)` - <EnterpriseAlert product="vault" inline /> The
- `identity_token_ttl` `(string/int: 3600)` - <EnterpriseAlert product="vault" inline /> The
TTL of generated tokens. Defaults to 1 hour. Uses [duration format strings](/vault/docs/concepts/duration-format).

- `region` `(string: <optional>)` – Specifies the AWS region. If not set it
Expand Down Expand Up @@ -316,6 +316,13 @@ updated with the new attributes.
TTL are capped to `max_sts_ttl`). Valid only when `credential_type` is one of
`assumed_role` or `federation_token`.

- `session_tags` `(list: [])` - The set of key-value pairs to be included as tags for the STS session.
Allowed formats are a map of strings or a list of strings in the format `key=value`.
Valid only when `credential_type` is set to `assumed_role`.

- `external_id` `(string)` - The external ID to use when assuming the role.
Valid only when `credential_type` is set to `assumed_role`.

- `user_path` `(string)` - The path for the user name. Valid only when
`credential_type` is `iam_user`. Default is `/`

Expand Down Expand Up @@ -645,7 +652,7 @@ $ curl \
"data": {
"access_key": "AKIA...",
"secret_key": "xlCs...",
"session_token": "FwoG...",
"session_token": "FwoG..."
}
}
```
Expand Down
Loading