-
Notifications
You must be signed in to change notification settings - Fork 464
/
gcpcloudstorage.go
263 lines (217 loc) · 8.08 KB
/
gcpcloudstorage.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
package gcpcloudstorage
import (
"context"
"io"
"sync"
"cloud.google.com/go/storage"
"github.com/hashicorp/go-hclog"
"github.com/hashicorp/hcl"
"github.com/spiffe/spire-plugin-sdk/pluginsdk/support/bundleformat"
bundlepublisherv1 "github.com/spiffe/spire-plugin-sdk/proto/spire/plugin/server/bundlepublisher/v1"
"github.com/spiffe/spire-plugin-sdk/proto/spire/plugin/types"
configv1 "github.com/spiffe/spire-plugin-sdk/proto/spire/service/common/config/v1"
"github.com/spiffe/spire/pkg/common/catalog"
"github.com/spiffe/spire/pkg/common/telemetry"
"google.golang.org/api/option"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
"google.golang.org/protobuf/proto"
)
const (
pluginName = "gcp_cloudstorage"
)
type pluginHooks struct {
newGCSClientFunc func(ctx context.Context, opts ...option.ClientOption) (gcsService, error)
newStorageWriterFunc func(ctx context.Context, o *storage.ObjectHandle) io.WriteCloser
wroteObjectFunc func() // Test hook called when an object was written.
}
func BuiltIn() catalog.BuiltIn {
return builtin(New())
}
func New() *Plugin {
return newPlugin(newGCSClient, newStorageWriter)
}
// Config holds the configuration of the plugin.
type Config struct {
BucketName string `hcl:"bucket_name" json:"bucket_name"`
ObjectName string `hcl:"object_name" json:"object_name"`
Format string `hcl:"format" json:"format"`
ServiceAccountFile string `hcl:"service_account_file" json:"service_account_file"`
// bundleFormat is used to store the content of Format, parsed
// as bundleformat.Format.
bundleFormat bundleformat.Format
}
// Plugin is the main representation of this bundle publisher plugin.
type Plugin struct {
bundlepublisherv1.UnsafeBundlePublisherServer
configv1.UnsafeConfigServer
config *Config
configMtx sync.RWMutex
bundle *types.Bundle
bundleMtx sync.RWMutex
hooks pluginHooks
gcsClient gcsService
log hclog.Logger
}
// SetLogger sets a logger in the plugin.
func (p *Plugin) SetLogger(log hclog.Logger) {
p.log = log
}
// Configure configures the plugin.
func (p *Plugin) Configure(ctx context.Context, req *configv1.ConfigureRequest) (*configv1.ConfigureResponse, error) {
config, err := parseAndValidateConfig(req.HclConfiguration)
if err != nil {
return nil, err
}
var opts []option.ClientOption
if config.ServiceAccountFile != "" {
opts = append(opts, option.WithCredentialsFile(config.ServiceAccountFile))
}
gcsClient, err := p.hooks.newGCSClientFunc(ctx, opts...)
if err != nil {
return nil, status.Errorf(codes.Internal, "failed to create client: %v", err)
}
p.gcsClient = gcsClient
p.setConfig(config)
p.setBundle(nil)
return &configv1.ConfigureResponse{}, nil
}
// PublishBundle puts the bundle in the configured GCS bucket and object name.
func (p *Plugin) PublishBundle(ctx context.Context, req *bundlepublisherv1.PublishBundleRequest) (*bundlepublisherv1.PublishBundleResponse, error) {
config, err := p.getConfig()
if err != nil {
return nil, err
}
if req.Bundle == nil {
return nil, status.Error(codes.InvalidArgument, "missing bundle in request")
}
currentBundle := p.getBundle()
if proto.Equal(req.Bundle, currentBundle) {
// Bundle not changed. No need to publish.
return &bundlepublisherv1.PublishBundleResponse{}, nil
}
formatter := bundleformat.NewFormatter(req.Bundle)
bundleBytes, err := formatter.Format(config.bundleFormat)
if err != nil {
return nil, status.Errorf(codes.Internal, "could not format bundle: %v", err.Error())
}
bucketHandle := p.gcsClient.Bucket(config.BucketName)
if bucketHandle == nil { // Purely defensive, the Bucket function implemented in GCS always returns a BucketHandle.
return nil, status.Error(codes.Internal, "could not get bucket handle")
}
objectHandle := bucketHandle.Object(config.ObjectName)
if objectHandle == nil { // Purely defensive, the Object function implemented in GCS always returns an ObjectHandle.
return nil, status.Error(codes.Internal, "could not get object handle")
}
storageWriter := p.hooks.newStorageWriterFunc(ctx, objectHandle)
if storageWriter == nil { // Purely defensive, the NewWriter function implemented in GCS always returns a storage writer
return nil, status.Error(codes.Internal, "could not initialize storage writer")
}
log := p.log.With(
"bucket_name", config.BucketName,
"object_name", config.ObjectName)
_, err = storageWriter.Write(bundleBytes)
// The number of bytes written can be safely ignored. To determine if an
// object was successfully uploaded, we need to look at the error returned
// from storageWriter.Close().
if err != nil {
// Close the storage writer before returning.
if closeErr := storageWriter.Close(); closeErr != nil {
log.With(telemetry.Error, closeErr).Error("Failed to close storage writer")
}
return nil, status.Errorf(codes.Internal, "failed to write bundle: %v", err)
}
if err := storageWriter.Close(); err != nil {
return nil, status.Errorf(codes.Internal, "failed to close storage writer: %v", err)
}
if p.hooks.wroteObjectFunc != nil {
p.hooks.wroteObjectFunc()
}
p.setBundle(req.Bundle)
log.Debug("Bundle published")
return &bundlepublisherv1.PublishBundleResponse{}, nil
}
// Close is called when the plugin is unloaded. Closes the client.
func (p *Plugin) Close() error {
if p.gcsClient == nil {
return nil
}
p.log.Debug("Closing the connection to the Cloud Storage API service")
return p.gcsClient.Close()
}
// getBundle gets the latest bundle that the plugin has.
func (p *Plugin) getBundle() *types.Bundle {
p.configMtx.RLock()
defer p.configMtx.RUnlock()
return p.bundle
}
// getConfig gets the configuration of the plugin.
func (p *Plugin) getConfig() (*Config, error) {
p.configMtx.RLock()
defer p.configMtx.RUnlock()
if p.config == nil {
return nil, status.Error(codes.FailedPrecondition, "not configured")
}
return p.config, nil
}
// setBundle updates the current bundle in the plugin with the provided bundle.
func (p *Plugin) setBundle(bundle *types.Bundle) {
p.bundleMtx.Lock()
defer p.bundleMtx.Unlock()
p.bundle = bundle
}
// setConfig sets the configuration for the plugin.
func (p *Plugin) setConfig(config *Config) {
p.configMtx.Lock()
defer p.configMtx.Unlock()
p.config = config
}
// builtin creates a new BundlePublisher built-in plugin.
func builtin(p *Plugin) catalog.BuiltIn {
return catalog.MakeBuiltIn(pluginName,
bundlepublisherv1.BundlePublisherPluginServer(p),
configv1.ConfigServiceServer(p),
)
}
// newPlugin returns a new plugin instance.
func newPlugin(newGCSClientFunc func(ctx context.Context, opts ...option.ClientOption) (gcsService, error),
newStorageWriterFunc func(ctx context.Context, o *storage.ObjectHandle) io.WriteCloser) *Plugin {
return &Plugin{
hooks: pluginHooks{
newGCSClientFunc: newGCSClientFunc,
newStorageWriterFunc: newStorageWriterFunc,
},
}
}
// parseAndValidateConfig returns an error if any configuration provided does
// not meet acceptable criteria
func parseAndValidateConfig(c string) (*Config, error) {
config := new(Config)
if err := hcl.Decode(config, c); err != nil {
return nil, status.Errorf(codes.InvalidArgument, "unable to decode configuration: %v", err)
}
if config.BucketName == "" {
return nil, status.Error(codes.InvalidArgument, "configuration is missing the bucket name")
}
if config.ObjectName == "" {
return nil, status.Error(codes.InvalidArgument, "configuration is missing the object name")
}
if config.Format == "" {
return nil, status.Error(codes.InvalidArgument, "configuration is missing the bundle format")
}
bundleFormat, err := bundleformat.FromString(config.Format)
if err != nil {
return nil, status.Errorf(codes.InvalidArgument, "could not parse bundle format from configuration: %v", err)
}
// The bundleformat package may support formats that this plugin does not
// support. Validate that the format is a supported format in this plugin.
switch bundleFormat {
case bundleformat.JWKS:
case bundleformat.SPIFFE:
case bundleformat.PEM:
default:
return nil, status.Errorf(codes.InvalidArgument, "format not supported %q", config.Format)
}
config.bundleFormat = bundleFormat
return config, nil
}