-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathmain.go
248 lines (226 loc) · 6.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
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
package main
import (
"context"
"encoding/json"
"fmt"
"log"
"os"
"cloud.google.com/go/storage"
"github.com/drone-plugins/drone-gcs/internal/gcp"
"github.com/pkg/errors"
"github.com/urfave/cli"
"golang.org/x/oauth2"
"golang.org/x/oauth2/google"
"google.golang.org/api/option"
)
var (
version = "unknown"
)
func main() {
app := cli.NewApp()
app.Name = "gcs plugin"
app.Usage = "gcs plugin"
app.Action = run
app.Version = version
app.Flags = []cli.Flag{
cli.StringFlag{
Name: "token",
Usage: "google auth key",
EnvVar: "PLUGIN_TOKEN,GOOGLE_CREDENTIALS,TOKEN",
},
cli.StringFlag{
Name: "json-key",
Usage: "google json keys",
EnvVar: "PLUGIN_JSON_KEY",
},
cli.StringSliceFlag{
Name: "acl",
Usage: "a list of access rules applied to the uploaded files, in a form of entity:role",
EnvVar: "PLUGIN_ACL",
},
cli.StringFlag{
Name: "source",
Usage: "location of files to upload",
EnvVar: "PLUGIN_SOURCE",
},
cli.StringFlag{
Name: "ignore",
Usage: "skip files matching this pattern, relative to source",
EnvVar: "PLUGIN_IGNORE",
},
cli.StringFlag{
Name: "target",
Usage: "destination to copy files to, including bucket name",
EnvVar: "PLUGIN_TARGET",
},
cli.BoolFlag{
Name: "download",
Usage: "switch to download mode, which will fetch `source`'s files from GCS",
EnvVar: "PLUGIN_DOWNLOAD",
},
cli.StringSliceFlag{
Name: "gzip",
Usage: `files with the specified extensions will be gzipped and uploaded with "gzip" Content-Encoding header`,
EnvVar: "PLUGIN_GZIP",
},
cli.StringFlag{
Name: "cache-control",
Usage: "Cache-Control header",
EnvVar: "PLUGIN_CACHE_CONTROL",
},
cli.StringFlag{
Name: "metadata",
Usage: "an arbitrary dictionary with custom metadata applied to all objects",
EnvVar: "PLUGIN_METADATA",
},
cli.StringFlag{
Name: "oidc-poo-id",
Usage: "OIDC WORKLOAD POOL ID",
EnvVar: "PLUGIN_POOL_ID",
},
cli.StringFlag{
Name: "oidc-provider-id",
Usage: "OIDC Provider Id",
EnvVar: "PLUGIN_PROVIDER_ID",
},
cli.StringFlag{
Name: "oidc-project-number",
Usage: "OIDC project Number ID",
EnvVar: "PLUGIN_PROJECT_NUMBER",
},
cli.StringFlag{
Name: "oidc-service-account-email",
Usage: "OIDC Service Account Email",
EnvVar: "PLUGIN_SERVICE_ACCOUNT_EMAIL",
},
cli.StringFlag{
Name: "oidc-token-id",
Usage: "OIDC GCP Token",
EnvVar: "PLUGIN_OIDC_TOKEN_ID",
},
}
if err := app.Run(os.Args); err != nil {
log.Fatal(err)
}
}
func run(c *cli.Context) error {
plugin := Plugin{
Config: Config{
Token: c.String("token"),
ACL: c.StringSlice("acl"),
Source: c.String("source"),
Target: c.String("target"),
Download: c.Bool("download"),
Ignore: c.String("ignore"),
Gzip: c.StringSlice("gzip"),
CacheControl: c.String("cache-control"),
workloadPoolId: c.String("oidc-poo-id"),
providerId: c.String("oidc-provider-id"),
gcpProjectId: c.String("oidc-project-number"),
serviceAccountEmail: c.String("oidc-service-account-email"),
OidcIdToken: c.String("oidc-token-id"),
},
}
if m := c.String("metadata"); m != "" {
var metadata map[string]string
if err := json.Unmarshal([]byte(m), &metadata); err != nil {
return errors.Wrap(err, "error parsing metadata field")
}
plugin.Config.Metadata = metadata
}
if !plugin.Config.Download {
if plugin.Config.Target == "" {
return errors.New("Missing target")
}
}
if plugin.Config.Source == "" {
return errors.New("Missing source")
}
var client *storage.Client
var err error
if plugin.Config.workloadPoolId != "" && plugin.Config.gcpProjectId != "" && plugin.Config.providerId != "" && plugin.Config.OidcIdToken != "" && plugin.Config.serviceAccountEmail != "" {
client, err = gcsClientWithOIDC(plugin.Config.workloadPoolId, plugin.Config.providerId, plugin.Config.gcpProjectId, plugin.Config.serviceAccountEmail, plugin.Config.OidcIdToken)
if err != nil {
return err
}
} else if plugin.Config.Token != "" {
client, err = gcsClientWithToken(plugin.Config.Token)
if err != nil {
return err
}
} else if c.String("json-key") != "" {
err := os.MkdirAll(os.TempDir(), 0600)
if err != nil {
return errors.Wrap(err, "failed to create temporary directory")
}
tmpfile, err := os.CreateTemp("", "")
if err != nil {
return errors.Wrap(err, "failed to create temporary file")
}
defer os.Remove(tmpfile.Name()) // clean up
client, err = gcsClientWithJSONKey(c.String("json-key"), tmpfile)
if err != nil {
return err
}
} else {
client, err = gcsClientApplicationDefaultCredentials()
if err != nil {
return err
}
}
return plugin.Exec(client)
}
func gcsClientWithToken(token string) (*storage.Client, error) {
auth, err := google.JWTConfigFromJSON([]byte(token), storage.ScopeFullControl)
if err != nil {
return nil, errors.Wrap(err, "failed to authenticate token")
}
ctx := context.Background()
client, err := storage.NewClient(ctx, option.WithTokenSource(auth.TokenSource(ctx)))
if err != nil {
return nil, errors.Wrap(err, "failed to initialize storage")
}
return client, nil
}
func gcsClientWithJSONKey(jsonKey string, credFile *os.File) (*storage.Client, error) {
if _, err := credFile.Write([]byte(jsonKey)); err != nil {
return nil, errors.Wrap(err, "failed to write gcs credentials to file")
}
if err := credFile.Close(); err != nil {
return nil, errors.Wrap(err, "failed to close gcs credentials file")
}
ctx := context.Background()
client, err := storage.NewClient(ctx, option.WithCredentialsFile(credFile.Name()))
if err != nil {
return nil, errors.Wrap(err, "failed to initialize storage")
}
return client, nil
}
func gcsClientApplicationDefaultCredentials() (*storage.Client, error) {
ctx := context.Background()
client, err := storage.NewClient(ctx)
if err != nil {
return nil, errors.Wrap(err, "failed to initialize storage")
}
return client, nil
}
func gcsClientWithOIDC(workloadPoolId string, providerId string, gcpProjectId string, serviceAccountEmail string, OidcIdToken string) (*storage.Client, error) {
federalToken, err := gcp.GetFederalToken(OidcIdToken, gcpProjectId, workloadPoolId, providerId)
if err != nil {
return nil, fmt.Errorf("OIDC token retrieval failed: %w", err)
}
oidcToken, err := gcp.GetGoogleCloudAccessToken(federalToken, serviceAccountEmail)
if err != nil {
return nil, fmt.Errorf("error getting Google Cloud Access Token: %w", err)
}
tokenSource := oauth2.StaticTokenSource(&oauth2.Token{
AccessToken: oidcToken,
TokenType: "Bearer",
})
ctx := context.Background()
client, err := storage.NewClient(ctx, option.WithTokenSource(tokenSource))
if err != nil {
return nil, errors.Wrap(err, "failed to initialize storage")
}
return client, nil
}