-
Notifications
You must be signed in to change notification settings - Fork 0
/
secrets.go
73 lines (59 loc) · 1.85 KB
/
secrets.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
package secrets
import (
"context"
"fmt"
"os"
secretmanager "cloud.google.com/go/secretmanager/apiv1"
"cloud.google.com/go/secretmanager/apiv1/secretmanagerpb"
"google.golang.org/api/option"
)
type SecretFetcher interface {
GetSecret(key string) (string, error)
}
type EnvVarSecretFetcher struct{}
func (f *EnvVarSecretFetcher) GetSecret(key string) (string, error) {
// Fetch secret from environment variable
return os.Getenv(key), nil
}
type GcpSecretManagerFetcher struct {
client *secretmanager.Client
projectID string
}
func NewGcpSecretManagerFetcher(projectID string, credentialsFile string) (*GcpSecretManagerFetcher, error) {
ctx := context.Background()
client, err := secretmanager.NewClient(ctx, option.WithCredentialsFile(credentialsFile))
if err != nil {
return nil, fmt.Errorf("failed to setup secret manager client: %v", err)
}
return &GcpSecretManagerFetcher{
client: client,
projectID: projectID,
}, nil
}
func (f *GcpSecretManagerFetcher) GetSecret(secretID string) (string, error) {
ctx := context.Background()
// Build the request.
accessRequest := &secretmanagerpb.AccessSecretVersionRequest{
Name: fmt.Sprintf("projects/%s/secrets/%s/versions/latest", f.projectID, secretID),
}
// Call the API.
result, err := f.client.AccessSecretVersion(ctx, accessRequest)
if err != nil {
return "", fmt.Errorf("failed to access secret version: %v", err)
}
// Return the secret payload as a string.
return string(result.Payload.Data), nil
}
func GetFetcher() SecretFetcher {
useSecretManager := os.Getenv("USE_SECRET_MANAGER")
if useSecretManager == "true" {
projectID := os.Getenv("GCP_PROJECT_ID")
credentialsFile := os.Getenv("GCP_CREDENTIALS_FILE")
fetcher, err := NewGcpSecretManagerFetcher(projectID, credentialsFile)
if err != nil {
// handle error
}
return fetcher
}
return &EnvVarSecretFetcher{}
}