Skip to content

Commit

Permalink
add aws creds
Browse files Browse the repository at this point in the history
  • Loading branch information
Mike Christofilopoulos authored and mhristof committed Apr 7, 2020
1 parent 00b00bb commit f302f09
Show file tree
Hide file tree
Showing 3 changed files with 116 additions and 0 deletions.
57 changes: 57 additions & 0 deletions awscreds/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package awscreds

import (
"fmt"
"io/ioutil"
"os"
"regexp"
"strings"
)

func AWSCreds() string {
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
panic(err)
}
return convert(data)
}

func convert(lines []byte) string {

secretKey := findItem(string(lines), `"SecretAccessKey": "(?P<secret>.*)"`, "secret")
accessKey := findItem(string(lines), `"AccessKeyId": "(?P<access>.*)"`, "access")
sessionToken := findItem(string(lines), `"SessionToken": "(?P<token>.*)"`, "token")

ret := "export"
if secretKey != "" {
ret = fmt.Sprintf("%s AWS_SECRET_KEY_ID='%s'", ret, secretKey)
}

if accessKey != "" {
ret = fmt.Sprintf("%s AWS_ACCESS_KEY_ID='%s'", ret, accessKey)
}

if sessionToken != "" {
ret = fmt.Sprintf("%s AWS_SESSION_TOKEN='%s'", ret, sessionToken)
}

return ret
}

func findItem(lines string, regex string, name string) string {
secret := regexp.MustCompile(regex)
for _, line := range strings.Split(string(lines), "\n") {
fmt.Println("currently at:", string(line))
res := secret.FindStringSubmatch(string(line))
for i, thisName := range secret.SubexpNames() {
fmt.Println(i, thisName)
if len(res) < i {
break
}
if thisName == name {
return res[i]
}
}
}
return ""
}
35 changes: 35 additions & 0 deletions awscreds/main_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package awscreds

import (
"testing"

"github.com/MakeNowJust/heredoc"
"github.com/stretchr/testify/assert"
)

func TestConvert(t *testing.T) {
var cases = []struct {
name string
in []byte
out string
}{
{
name: "partial text from aws sts assume-role command",
in: []byte(heredoc.Doc(`
"SecretAccessKey": "secret",
"SessionToken": "token",
"AccessKeyId": "access"`,
)),
out: "export AWS_SECRET_KEY_ID='secret' AWS_ACCESS_KEY_ID='access' AWS_SESSION_TOKEN='token'",
},
}

for _, tt := range cases {
tt := tt
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
t.Log(tt.name)
assert.Equal(t, tt.out, convert(tt.in))
})
}
}
24 changes: 24 additions & 0 deletions cmd/aws.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
package cmd

import (
"fmt"

"github.com/mhristof/paste/awscreds"
"github.com/spf13/cobra"
)

var (
awscredsCmd = &cobra.Command{
Use: "awscreds",
Short: "Extract AWS creds from the text and coverte them to export stattements",
Long: "",
Run: func(cmd *cobra.Command, args []string) {
Verbose(cmd)
fmt.Print(awscreds.AWSCreds())
},
}
)

func init() {
rootCmd.AddCommand(awscredsCmd)
}

0 comments on commit f302f09

Please sign in to comment.