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 6 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.
```
Loading