forked from hashicorp/terraform-provider-google
-
Notifications
You must be signed in to change notification settings - Fork 0
/
data_source_storage_object_signed_url.go
368 lines (314 loc) · 9.47 KB
/
data_source_storage_object_signed_url.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
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
package google
import (
"bytes"
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"log"
"net/url"
"os"
"strconv"
"strings"
"time"
"sort"
"github.com/hashicorp/errwrap"
"github.com/hashicorp/terraform/helper/pathorcontents"
"github.com/hashicorp/terraform/helper/schema"
"golang.org/x/oauth2/google"
"golang.org/x/oauth2/jwt"
)
const gcsBaseUrl = "https://storage.googleapis.com"
const googleCredentialsEnvVar = "GOOGLE_APPLICATION_CREDENTIALS"
func dataSourceGoogleSignedUrl() *schema.Resource {
return &schema.Resource{
Read: dataSourceGoogleSignedUrlRead,
Schema: map[string]*schema.Schema{
"bucket": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"content_md5": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "",
},
"content_type": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "",
},
"credentials": &schema.Schema{
Type: schema.TypeString,
Optional: true,
},
"duration": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "1h",
},
"extension_headers": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
Elem: schema.TypeString,
ValidateFunc: validateExtensionHeaders,
},
"http_method": &schema.Schema{
Type: schema.TypeString,
Optional: true,
Default: "GET",
ValidateFunc: validateHttpMethod,
},
"path": &schema.Schema{
Type: schema.TypeString,
Required: true,
},
"signed_url": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
},
}
}
func validateExtensionHeaders(v interface{}, k string) (ws []string, errors []error) {
hdrMap := v.(map[string]interface{})
for k, _ := range hdrMap {
if !strings.HasPrefix(strings.ToLower(k), "x-goog-") {
errors = append(errors, fmt.Errorf(
"extension_header (%s) not valid, header name must begin with 'x-goog-'", k))
}
}
return
}
func validateHttpMethod(v interface{}, k string) (ws []string, errs []error) {
value := v.(string)
value = strings.ToUpper(value)
if value != "GET" && value != "HEAD" && value != "PUT" && value != "DELETE" {
errs = append(errs, errors.New("http_method must be one of [GET|HEAD|PUT|DELETE]"))
}
return
}
func dataSourceGoogleSignedUrlRead(d *schema.ResourceData, meta interface{}) error {
config := meta.(*Config)
// Build UrlData object from data source attributes
urlData := &UrlData{}
// HTTP Method
if method, ok := d.GetOk("http_method"); ok {
urlData.HttpMethod = method.(string)
}
// convert duration to an expiration datetime (unix time in seconds)
durationString := "1h"
if v, ok := d.GetOk("duration"); ok {
durationString = v.(string)
}
duration, err := time.ParseDuration(durationString)
if err != nil {
return errwrap.Wrapf("could not parse duration: {{err}}", err)
}
expires := time.Now().Unix() + int64(duration.Seconds())
urlData.Expires = int(expires)
// content_md5 is optional
if v, ok := d.GetOk("content_md5"); ok {
urlData.ContentMd5 = v.(string)
}
// content_type is optional
if v, ok := d.GetOk("content_type"); ok {
urlData.ContentType = v.(string)
}
// extension_headers (x-goog-* HTTP headers) are optional
if v, ok := d.GetOk("extension_headers"); ok {
hdrMap := v.(map[string]interface{})
if len(hdrMap) > 0 {
urlData.HttpHeaders = make(map[string]string, len(hdrMap))
for k, v := range hdrMap {
urlData.HttpHeaders[k] = v.(string)
}
}
}
urlData.Path = fmt.Sprintf("/%s/%s", d.Get("bucket").(string), d.Get("path").(string))
// Load JWT Config from Google Credentials
jwtConfig, err := loadJwtConfig(d, config)
if err != nil {
return err
}
urlData.JwtConfig = jwtConfig
// Construct URL
signedUrl, err := urlData.SignedUrl()
if err != nil {
return err
}
// Success
d.Set("signed_url", signedUrl)
encodedSig, err := urlData.EncodedSignature()
if err != nil {
return err
}
d.SetId(encodedSig)
return nil
}
// loadJwtConfig looks for credentials json in the following places,
// in order of preference:
// 1. `credentials` attribute of the datasource
// 2. `credentials` attribute in the provider definition.
// 3. A JSON file whose path is specified by the
// GOOGLE_APPLICATION_CREDENTIALS environment variable.
func loadJwtConfig(d *schema.ResourceData, meta interface{}) (*jwt.Config, error) {
config := meta.(*Config)
credentials := ""
if v, ok := d.GetOk("credentials"); ok {
log.Println("[DEBUG] using data source credentials to sign URL")
credentials = v.(string)
} else if config.Credentials != "" {
log.Println("[DEBUG] using provider credentials to sign URL")
credentials = config.Credentials
} else if filename := os.Getenv(googleCredentialsEnvVar); filename != "" {
log.Println("[DEBUG] using env GOOGLE_APPLICATION_CREDENTIALS credentials to sign URL")
credentials = filename
}
if strings.TrimSpace(credentials) != "" {
contents, _, err := pathorcontents.Read(credentials)
if err != nil {
return nil, errwrap.Wrapf("Error loading credentials: {{err}}", err)
}
cfg, err := google.JWTConfigFromJSON([]byte(contents), "")
if err != nil {
return nil, errwrap.Wrapf("Error parsing credentials: {{err}}", err)
}
return cfg, nil
}
return nil, errors.New("Credentials not found in datasource, provider configuration or GOOGLE_APPLICATION_CREDENTIALS environment variable.")
}
// parsePrivateKey converts the binary contents of a private key file
// to an *rsa.PrivateKey. It detects whether the private key is in a
// PEM container or not. If so, it extracts the the private key
// from PEM container before conversion. It only supports PEM
// containers with no passphrase.
// copied from golang.org/x/oauth2/internal
func parsePrivateKey(key []byte) (*rsa.PrivateKey, error) {
block, _ := pem.Decode(key)
if block != nil {
key = block.Bytes
}
parsedKey, err := x509.ParsePKCS8PrivateKey(key)
if err != nil {
parsedKey, err = x509.ParsePKCS1PrivateKey(key)
if err != nil {
return nil, errwrap.Wrapf("private key should be a PEM or plain PKSC1 or PKCS8; parse error: {{err}}", err)
}
}
parsed, ok := parsedKey.(*rsa.PrivateKey)
if !ok {
return nil, errors.New("private key is invalid")
}
return parsed, nil
}
// UrlData stores the values required to create a Signed Url
type UrlData struct {
JwtConfig *jwt.Config
ContentMd5 string
ContentType string
HttpMethod string
Expires int
HttpHeaders map[string]string
Path string
}
// SigningString creates a string representation of the UrlData in a form ready for signing:
// see https://cloud.google.com/storage/docs/access-control/create-signed-urls-program
// Example output:
// -------------------
// GET
//
//
// 1388534400
// bucket/objectname
// -------------------
func (u *UrlData) SigningString() []byte {
var buf bytes.Buffer
// HTTP Verb
buf.WriteString(u.HttpMethod)
buf.WriteString("\n")
// Content MD5 (optional, always add new line)
buf.WriteString(u.ContentMd5)
buf.WriteString("\n")
// Content Type (optional, always add new line)
buf.WriteString(u.ContentType)
buf.WriteString("\n")
// Expiration
buf.WriteString(strconv.Itoa(u.Expires))
buf.WriteString("\n")
// Extra HTTP headers (optional)
// Must be sorted in lexigraphical order
var keys []string
for k := range u.HttpHeaders {
keys = append(keys, strings.ToLower(k))
}
sort.Strings(keys)
// Write sorted headers to signing string buffer
for _, k := range keys {
buf.WriteString(fmt.Sprintf("%s:%s\n", k, u.HttpHeaders[k]))
}
// Storate Object path (includes bucketname)
buf.WriteString(u.Path)
return buf.Bytes()
}
func (u *UrlData) Signature() ([]byte, error) {
// Sign url data
signature, err := SignString(u.SigningString(), u.JwtConfig)
if err != nil {
return nil, err
}
return signature, nil
}
// EncodedSignature returns the Signature() after base64 encoding and url escaping
func (u *UrlData) EncodedSignature() (string, error) {
signature, err := u.Signature()
if err != nil {
return "", err
}
// base64 encode signature
encoded := base64.StdEncoding.EncodeToString(signature)
// encoded signature may include /, = characters that need escaping
encoded = url.QueryEscape(encoded)
return encoded, nil
}
// SignedUrl constructs the final signed URL a client can use to retrieve storage object
func (u *UrlData) SignedUrl() (string, error) {
encodedSig, err := u.EncodedSignature()
if err != nil {
return "", err
}
// build url
// https://cloud.google.com/storage/docs/access-control/create-signed-urls-program
var urlBuffer bytes.Buffer
urlBuffer.WriteString(gcsBaseUrl)
urlBuffer.WriteString(u.Path)
urlBuffer.WriteString("?GoogleAccessId=")
urlBuffer.WriteString(u.JwtConfig.Email)
urlBuffer.WriteString("&Expires=")
urlBuffer.WriteString(strconv.Itoa(u.Expires))
urlBuffer.WriteString("&Signature=")
urlBuffer.WriteString(encodedSig)
return urlBuffer.String(), nil
}
// SignString calculates the SHA256 signature of the input string
func SignString(toSign []byte, cfg *jwt.Config) ([]byte, error) {
// Parse private key
pk, err := parsePrivateKey(cfg.PrivateKey)
if err != nil {
return nil, errwrap.Wrapf("failed to sign string, could not parse key: {{err}}", err)
}
// Hash string
hasher := sha256.New()
hasher.Write(toSign)
// Sign string
signed, err := rsa.SignPKCS1v15(rand.Reader, pk, crypto.SHA256, hasher.Sum(nil))
if err != nil {
return nil, errwrap.Wrapf("failed to sign string, an error occurred: {{err}}", err)
}
return signed, nil
}