Skip to content

Commit

Permalink
refactor: beautify code and split some packages
Browse files Browse the repository at this point in the history
Signed-off-by: thomasgouveia <[email protected]>
  • Loading branch information
thomasgouveia committed Jun 12, 2023
1 parent a652d14 commit 12a4515
Show file tree
Hide file tree
Showing 9 changed files with 376 additions and 156 deletions.
35 changes: 21 additions & 14 deletions cmd/root.go
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
package cmd

import (
"encoding/json"
"errors"
"fmt"
"os"
"time"

"github.com/hashicorp/vault-client-go"
"github.com/spf13/cobra"
"github.com/thomasgouveia/vault-aws-credentials-helper/pkg/credentials"
"github.com/thomasgouveia/vault-aws-credentials-helper/pkg/resolver"
"github.com/thomasgouveia/vault-aws-credentials-helper/pkg/vaultauth"
)

var rootCmd = &cobra.Command{
Expand All @@ -31,28 +31,33 @@ var rootCmd = &cobra.Command{
return err
}

// Fetch authentication credentials
cfg := &credentials.FetchCredentialConfig{
AuthMethod: vaultAuthMethod,
MountPath: awsMountPath,
Role: awsRole,
TTL: awsTtl,
// Define options for resolving credentials
resolveOpts := []resolver.ResolveOption{
resolver.WithCommand(cmd),
resolver.WithClient(client),
resolver.WithAuthMethod(vaultauth.AuthMethod(vaultAuthMethod)),
resolver.WithMountPath(awsMountPath),
resolver.WithRole(awsRole),
resolver.WithTTL(awsTtl),
}

creds, err := credentials.Fetch(cmd, client, cfg)
// Login to Vault, and then issue the credentials
// by calling the correct endpoint depending on
// the given options.
creds, err := resolver.ResolveCredentials(resolveOpts...)
if err != nil {
if errors.Is(err, credentials.ErrVaultRoleEmpty) {
if errors.Is(err, resolver.ErrVaultRoleEmpty) {
return fmt.Errorf("you must provide a Vault role configured in your AWS backend to generate credentials using --aws.role")
}
return err
}

by, err := json.MarshalIndent(creds, "", " ")
out, err := creds.JSONString()
if err != nil {
return err
}

fmt.Println(string(by))
fmt.Println(out)
return nil
},
}
Expand All @@ -67,8 +72,10 @@ func init() {
rootCmd.PersistentFlags().String("aws.role", "", "The name of the Vault role to use to generate credentials on the AWS backend.")
rootCmd.PersistentFlags().String("aws.ttl", "15m", "The TTL of the Vault lease for the AWS generated credentials.")

// Authentication methods flags
credentials.ConfigureAuthFlags(rootCmd)
// Bind authentication methods flags
if err := vaultauth.MapAuthMethodsConfigToCommandFlags(rootCmd); err != nil {
panic(err)
}
}

// This is called by main.main(). It only needs to happen once to the rootCmd.
Expand Down
86 changes: 86 additions & 0 deletions pkg/awscreds/awscreds.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
package awscreds

import (
"encoding/json"
"time"
)

// AWSCredentials represents the JSON structure that the
// vault-aws-credentials-helper should output to STDOUT to allow
// the AWS CLI to autoconfigure with the generated credentials.
//
// See https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-sourcing-external.html
type AWSCredentials struct {
// Version must be set to 1 by default. This might increment over
// time if the AWS credentials structure evolves.
Version int `json:"Version"`
// AccessKeyId the access key generated.
AccessKeyId string `json:"AccessKeyId,omitempty"`
// SecretAccessKey the secret access key generated.
SecretAccessKey string `json:"SecretAccessKey,omitempty"`
// SessionToken the AWS session token for temporary credentials
SessionToken string `json:"SessionToken,omitempty"`
// Expiration should be an ISO8601 formatted timestamp.
// If the Expiration key is not present in the output, the AWS CLI
// will assume that the credentials are long-term credentials that do not refresh.
// Otherwise the credentials are considered temporary credentials and are refreshed
// automatically by rerunning the credential_process command before they expire.
Expiration string `json:"Expiration,omitempty"`
}

type AWSCredentialOption func(c *AWSCredentials) error

// New initializes a new AWS credentials with the default configuration.
func New(opts ...AWSCredentialOption) (*AWSCredentials, error) {
creds := &AWSCredentials{Version: 1}

// Apply all options
for _, opt := range opts {
if err := opt(creds); err != nil {
return nil, err
}
}

return creds, nil
}

// JSONString returns a pretty JSON string representation of the credentials.
func (c *AWSCredentials) JSONString() (string, error) {
by, err := json.MarshalIndent(c, "", " ")
if err != nil {
return "", err
}
return string(by), nil
}

// WithAccessKeyId specifies the AWS access key id for this pair of credentials.
func WithAccessKeyId(accessKeyId string) AWSCredentialOption {
return func(c *AWSCredentials) error {
c.AccessKeyId = accessKeyId
return nil
}
}

// WithSecretAccessKey specifies the AWS secret access key id for this pair of credentials.
func WithSecretAccessKey(secretAccessKey string) AWSCredentialOption {
return func(c *AWSCredentials) error {
c.SecretAccessKey = secretAccessKey
return nil
}
}

// WithSessionToken specifies the AWS session token this pair of credentials.
func WithSessionToken(sessionToken string) AWSCredentialOption {
return func(c *AWSCredentials) error {
c.SessionToken = sessionToken
return nil
}
}

// WithExpiration sets the expiration of this pair of credentials.
func WithExpiration(exp time.Time) AWSCredentialOption {
return func(c *AWSCredentials) error {
c.Expiration = exp.Format("2006-01-02T15:04:05.000Z")
return nil
}
}
132 changes: 0 additions & 132 deletions pkg/credentials/credentials.go

This file was deleted.

Loading

0 comments on commit 12a4515

Please sign in to comment.