forked from legal90/awscurl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
200 lines (170 loc) · 5.83 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
package main
import (
"bufio"
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"strings"
"time"
"github.com/aws/aws-sdk-go-v2/aws"
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
"github.com/spf13/cobra"
)
type awsCURLFlags struct {
headers []string
method string
data string
awsAccessKey string
awsSecretKey string
awsSessionToken string
awsProfile string
awsService string
awsRegion string
insecure bool
}
var (
// Version and git commit SHA to include to the `--version` output
// These variables are supposed to be overriden on the build time using ldflags
version = "dev"
commit = "none"
flags awsCURLFlags
)
// rootCmd represents the base awscurl command when called without any subcommands (which we don't have here)
var rootCmd = &cobra.Command{
Use: "awscurl [URL]",
Short: "cURL with AWS request signing",
Long: `A simple CLI utility with cURL-like syntax allowing to send HTTP requests to AWS resources.
It automatically adds Siganture Version 4 to the request. More details:
https://docs.aws.amazon.com/general/latest/gr/signature-version-4.html
`,
Args: cobra.ExactArgs(1),
RunE: runCurl,
Version: fmt.Sprintf("%s, build %s", version, commit),
}
func main() {
if err := rootCmd.Execute(); err != nil {
os.Exit(1)
}
}
func init() {
rootCmd.PersistentFlags().StringVarP(&flags.method, "request", "X", "GET", "Custom request method to use")
rootCmd.PersistentFlags().StringVarP(&flags.data, "data", "d", "", `Data payload to send within a request. Could be also read from a file if prefixed with @, example: -d "@/path/to/file.json"`)
rootCmd.PersistentFlags().StringArrayVarP(&flags.headers, "header", "H", []string{},
`Extra HTTP header to include in the request. Example: -h "Content-Type: application/json". Could be used multiple times`)
rootCmd.PersistentFlags().StringVar(&flags.awsAccessKey, "access-key", "", "AWS Access Key ID to use for authentication")
rootCmd.PersistentFlags().StringVar(&flags.awsSecretKey, "secret-key", "", "AWS Secret Access Key to use for authentication")
rootCmd.PersistentFlags().StringVar(&flags.awsSessionToken, "session-token", "", "AWS Session Key to use for authentication")
rootCmd.PersistentFlags().StringVar(&flags.awsProfile, "profile", "", "AWS awsProfile to use for authentication")
rootCmd.PersistentFlags().StringVar(&flags.awsService, "service", "execute-api", "The name of AWS Service, used for signing the request")
rootCmd.PersistentFlags().StringVar(&flags.awsRegion, "region", "", "AWS region to use for the request")
rootCmd.PersistentFlags().BoolVarP(&flags.insecure, "insecure", "k", false, "Allow insecure server connections when using SSL")
rootCmd.Flags().SortFlags = false
}
func runCurl(cmd *cobra.Command, args []string) error {
// Suppress the usage info in case of errors happen below
// We do it here, after the init(), so the usage info is still printed for invalid args and flags.
cmd.SilenceUsage = true
if len(args) != 1 {
return fmt.Errorf("Error: Only one URL is expected, %d given", len(args))
}
cfg, err := getAWSConfig(flags)
if err != nil {
return err
}
var body io.Reader
if strings.HasPrefix(flags.data, "@") {
// Read data from file
fPath := flags.data[1:]
body, err = os.Open(fPath)
if err != nil {
return err
}
} else {
body = strings.NewReader(flags.data)
}
// Build the HTTP request
url := args[0]
req, err := http.NewRequest(flags.method, url, body)
if err != nil {
return err
}
for _, h := range flags.headers {
hParts := strings.Split(h, ":")
if len(hParts) != 2 {
return fmt.Errorf(`Error: Invalid header: %s. It should be in the format "Name: Value"`, h)
}
hKey := strings.TrimSpace(hParts[0])
hVal := strings.TrimSpace(hParts[1])
req.Header.Add(hKey, hVal)
}
// Sign the HTTP request. Special headers will be added to the given *http.Request
reqBody := readAndReplaceBody(req)
reqBodySHA256 := hashSHA256(reqBody)
signer := v4.NewSigner()
creds, err := cfg.Credentials.Retrieve(context.Background())
if err != nil {
return err
}
err = signer.SignHTTP(req.Context(), creds, req, reqBodySHA256, flags.awsService, cfg.Region, time.Now())
if err != nil {
return err
}
// Set TLS Client configuration
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: flags.insecure},
}
// Send the request and print the response
client := http.Client{Transport: tr}
response, err := client.Do(req)
if err != nil {
return err
}
defer response.Body.Close()
scanner := bufio.NewScanner(response.Body)
for scanner.Scan() {
fmt.Println(scanner.Text())
}
return nil
}
// getAWSConfig builgs the AWS Config based on the provided AWS-related flags
func getAWSConfig(f awsCURLFlags) (aws.Config, error) {
var cfg aws.Config
var cfgSources []func(*config.LoadOptions) error
if f.awsProfile != "" {
awsProfileLoader := config.WithSharedConfigProfile(f.awsProfile)
cfgSources = append(cfgSources, awsProfileLoader)
}
if f.awsAccessKey != "" && f.awsSecretKey != "" {
staticCredsLoader := config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(f.awsAccessKey, f.awsSecretKey, f.awsSessionToken))
cfgSources = append(cfgSources, staticCredsLoader)
}
cfg, err := config.LoadDefaultConfig(context.Background(), cfgSources...)
if err != nil {
return cfg, fmt.Errorf("Unable to load AWS config: %s", err)
}
if f.awsRegion != "" {
cfg.Region = f.awsRegion
}
return cfg, nil
}
func readAndReplaceBody(request *http.Request) []byte {
if request.Body == nil {
return []byte{}
}
payload, _ := ioutil.ReadAll(request.Body)
request.Body = ioutil.NopCloser(bytes.NewReader(payload))
return payload
}
func hashSHA256(content []byte) string {
h := sha256.New()
h.Write(content)
return fmt.Sprintf("%x", h.Sum(nil))
}