forked from spiffe/spire
/
agent.go
367 lines (321 loc) · 10.9 KB
/
agent.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
package agent
import (
"context"
"errors"
"fmt"
"net/http"
_ "net/http/pprof" //nolint: gosec // import registers routes on DefaultServeMux
"runtime"
"sync"
"time"
"github.com/accuknox/go-spiffe/v2/workloadapi"
admin_api "github.com/accuknox/spire/pkg/agent/api"
node_attestor "github.com/accuknox/spire/pkg/agent/attestor/node"
workload_attestor "github.com/accuknox/spire/pkg/agent/attestor/workload"
"github.com/accuknox/spire/pkg/agent/catalog"
"github.com/accuknox/spire/pkg/agent/endpoints"
"github.com/accuknox/spire/pkg/agent/manager"
"github.com/accuknox/spire/pkg/agent/manager/storecache"
"github.com/accuknox/spire/pkg/agent/plugin/nodeattestor"
"github.com/accuknox/spire/pkg/agent/storage"
"github.com/accuknox/spire/pkg/agent/svid/store"
"github.com/accuknox/spire/pkg/common/diskutil"
"github.com/accuknox/spire/pkg/common/health"
"github.com/accuknox/spire/pkg/common/profiling"
"github.com/accuknox/spire/pkg/common/telemetry"
"github.com/accuknox/spire/pkg/common/uptime"
"github.com/accuknox/spire/pkg/common/util"
"github.com/hashicorp/hcl"
_ "golang.org/x/net/trace" // registers handlers on the DefaultServeMux
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
type Agent struct {
c *Config
}
// Config defines the configuration for the plugin.
type pluginConfig struct {
Namespace string `hcl:"namespace"`
SecretName string `hcl:"secretname"`
}
// Run the agent
// This method initializes the agent, including its plugins,
// and then blocks on the main event loop.
func (a *Agent) Run(ctx context.Context) error {
var sto storage.Storage
var err error
keyManager, ok := a.c.PluginConfigs.Find("KeyManager", "keymanager-k8s")
newConfig := new(pluginConfig)
if ok {
if err := hcl.Decode(newConfig, keyManager.Data); err != nil {
return fmt.Errorf("failed to decode configuration: %v", err)
}
}
if newConfig.Namespace != "" && newConfig.SecretName != "" {
a.c.Log.Infof("Starting agent with kubernetes secret store")
sto, err = storage.Open("", newConfig.Namespace, newConfig.SecretName)
} else {
a.c.Log.Infof("Starting agent with data directory: %q", a.c.DataDir)
if err := diskutil.CreateDataDirectory(a.c.DataDir); err != nil {
return err
}
sto, err = storage.Open(a.c.DataDir, "", "")
}
if err != nil {
return fmt.Errorf("failed to open storage: %w", err)
}
ctx, cancel := context.WithCancel(ctx)
defer cancel()
if a.c.ProfilingEnabled {
stopProfiling := a.setupProfiling(ctx)
defer stopProfiling()
}
metrics, err := telemetry.NewMetrics(&telemetry.MetricsConfig{
FileConfig: a.c.Telemetry,
Logger: a.c.Log.WithField(telemetry.SubsystemName, telemetry.Telemetry),
ServiceName: telemetry.SpireAgent,
})
if err != nil {
return err
}
telemetry.EmitVersion(metrics)
uptime.ReportMetrics(ctx, metrics)
cat, err := catalog.Load(ctx, catalog.Config{
Log: a.c.Log.WithField(telemetry.SubsystemName, telemetry.Catalog),
Metrics: metrics,
TrustDomain: a.c.TrustDomain,
PluginConfigs: a.c.PluginConfigs,
})
if err != nil {
return err
}
defer cat.Close()
healthChecker := health.NewChecker(a.c.HealthChecks, a.c.Log)
nodeAttestor := nodeattestor.JoinToken(a.c.Log, a.c.JoinToken)
if a.c.JoinToken == "" {
nodeAttestor = cat.GetNodeAttestor()
}
as, err := a.attest(ctx, sto, cat, metrics, nodeAttestor)
if err != nil {
return err
}
svidStoreCache := a.newSVIDStoreCache()
manager, err := a.newManager(ctx, sto, cat, metrics, as, svidStoreCache, nodeAttestor)
if err != nil {
return err
}
storeService := a.newSVIDStoreService(svidStoreCache, cat, metrics)
workloadAttestor := workload_attestor.New(&workload_attestor.Config{
Catalog: cat,
Log: a.c.Log.WithField(telemetry.SubsystemName, telemetry.WorkloadAttestor),
Metrics: metrics,
})
endpoints := a.newEndpoints(metrics, manager, workloadAttestor)
if err := healthChecker.AddCheck("agent", a); err != nil {
return fmt.Errorf("failed adding healthcheck: %w", err)
}
tasks := []func(context.Context) error{
manager.Run,
storeService.Run,
endpoints.RunTCPAgent,
endpoints.ListenAndServe,
metrics.ListenAndServe,
util.SerialRun(a.waitForTestDial, healthChecker.ListenAndServe),
}
if a.c.AdminBindAddress != nil {
adminEndpoints := a.newAdminEndpoints(manager, workloadAttestor, a.c.AuthorizedDelegates)
tasks = append(tasks, adminEndpoints.ListenAndServe)
}
if a.c.LogReopener != nil {
tasks = append(tasks, a.c.LogReopener)
}
err = util.RunTasks(ctx, tasks...)
if errors.Is(err, context.Canceled) {
err = nil
}
return err
}
func (a *Agent) setupProfiling(ctx context.Context) (stop func()) {
var wg sync.WaitGroup
ctx, cancel := context.WithCancel(ctx)
if runtime.MemProfileRate == 0 {
a.c.Log.Warn("Memory profiles are disabled")
}
if a.c.ProfilingPort > 0 {
grpc.EnableTracing = true
server := http.Server{
Addr: fmt.Sprintf("localhost:%d", a.c.ProfilingPort),
Handler: http.DefaultServeMux,
ReadHeaderTimeout: time.Second * 10,
}
// kick off a goroutine to serve the pprof endpoints and one to
// gracefully shut down the server when profiling is being torn down
wg.Add(1)
go func() {
defer wg.Done()
if err := server.ListenAndServe(); err != nil {
a.c.Log.WithError(err).Warn("Unable to serve profiling server")
}
}()
wg.Add(1)
go func() {
defer wg.Done()
<-ctx.Done()
if err := server.Shutdown(ctx); err != nil {
a.c.Log.WithError(err).Warn("Unable to shut down cleanly")
}
}()
}
if a.c.ProfilingFreq > 0 {
c := &profiling.Config{
Tag: "agent",
Frequency: a.c.ProfilingFreq,
DebugLevel: 0,
RunGCBeforeHeapProfile: true,
Profiles: a.c.ProfilingNames,
}
wg.Add(1)
go func() {
defer wg.Done()
if err := profiling.Run(ctx, c); err != nil {
a.c.Log.WithError(err).Warn("Failed to run profiling")
}
}()
}
return func() {
cancel()
wg.Wait()
}
}
func (a *Agent) attest(ctx context.Context, sto storage.Storage, cat catalog.Catalog, metrics telemetry.Metrics, na nodeattestor.NodeAttestor) (*node_attestor.AttestationResult, error) {
config := node_attestor.Config{
Catalog: cat,
Metrics: metrics,
JoinToken: a.c.JoinToken,
TrustDomain: a.c.TrustDomain,
TrustBundle: a.c.TrustBundle,
InsecureBootstrap: a.c.InsecureBootstrap,
Storage: sto,
Log: a.c.Log.WithField(telemetry.SubsystemName, telemetry.Attestor),
ServerAddress: a.c.ServerAddress,
NodeAttestor: na,
}
return node_attestor.New(&config).Attest(ctx)
}
func (a *Agent) newManager(ctx context.Context, sto storage.Storage, cat catalog.Catalog, metrics telemetry.Metrics, as *node_attestor.AttestationResult, cache *storecache.Cache, na nodeattestor.NodeAttestor) (manager.Manager, error) {
config := &manager.Config{
SVID: as.SVID,
SVIDKey: as.Key,
Bundle: as.Bundle,
Catalog: cat,
TrustDomain: a.c.TrustDomain,
ServerAddr: a.c.ServerAddress,
Log: a.c.Log.WithField(telemetry.SubsystemName, telemetry.Manager),
Metrics: metrics,
WorkloadKeyType: a.c.WorkloadKeyType,
Storage: sto,
SyncInterval: a.c.SyncInterval,
SVIDCacheMaxSize: a.c.X509SVIDCacheMaxSize,
SVIDStoreCache: cache,
NodeAttestor: na,
}
mgr := manager.New(config)
if err := mgr.Initialize(ctx); err != nil {
return nil, err
}
return mgr, nil
}
func (a *Agent) newSVIDStoreCache() *storecache.Cache {
config := &storecache.Config{
Log: a.c.Log.WithField(telemetry.SubsystemName, "svid_store_cache"),
TrustDomain: a.c.TrustDomain,
}
return storecache.New(config)
}
func (a *Agent) newSVIDStoreService(cache *storecache.Cache, cat catalog.Catalog, metrics telemetry.Metrics) *store.SVIDStoreService {
config := &store.Config{
Log: a.c.Log.WithField(telemetry.SubsystemName, "svid_store_service"),
TrustDomain: a.c.TrustDomain,
Cache: cache,
Catalog: cat,
Metrics: metrics,
}
return store.New(config)
}
func (a *Agent) newEndpoints(metrics telemetry.Metrics, mgr manager.Manager, attestor workload_attestor.Attestor) endpoints.Server {
return endpoints.New(endpoints.Config{
BindAddr: a.c.BindAddress,
AgentAddr: a.c.AgentAddress,
Attestor: attestor,
Manager: mgr,
Log: a.c.Log.WithField(telemetry.SubsystemName, telemetry.Endpoints),
Metrics: metrics,
DefaultSVIDName: a.c.DefaultSVIDName,
DefaultBundleName: a.c.DefaultBundleName,
DefaultAllBundlesName: a.c.DefaultAllBundlesName,
DisableSPIFFECertValidation: a.c.DisableSPIFFECertValidation,
AllowUnauthenticatedVerifiers: a.c.AllowUnauthenticatedVerifiers,
AllowedForeignJWTClaims: a.c.AllowedForeignJWTClaims,
TrustDomain: a.c.TrustDomain,
})
}
func (a *Agent) newAdminEndpoints(mgr manager.Manager, attestor workload_attestor.Attestor, authorizedDelegates []string) admin_api.Server {
config := &admin_api.Config{
BindAddr: a.c.AdminBindAddress,
Manager: mgr,
Log: a.c.Log.WithField(telemetry.SubsystemName, telemetry.DebugAPI),
TrustDomain: a.c.TrustDomain,
Uptime: uptime.Uptime,
Attestor: attestor,
AuthorizedDelegates: authorizedDelegates,
}
return admin_api.New(config)
}
// waitForTestDial calls health.WaitForTestDial to wait for a connection to the
// SPIRE Agent API socket. This function always returns nil, even if
// health.WaitForTestDial exited due to a timeout.
func (a *Agent) waitForTestDial(ctx context.Context) error {
health.WaitForTestDial(ctx, a.c.BindAddress)
return nil
}
// CheckHealth is used as a top-level health check for the agent.
func (a *Agent) CheckHealth() health.State {
err := a.checkWorkloadAPI()
// Both liveness and readiness checks are done by
// agents ability to create new Workload API client
// for the X509SVID service.
// TODO: Better live check for agent.
return health.State{
Ready: err == nil,
Live: err == nil,
ReadyDetails: agentHealthDetails{
WorkloadAPIErr: errString(err),
},
LiveDetails: agentHealthDetails{
WorkloadAPIErr: errString(err),
},
}
}
func (a *Agent) checkWorkloadAPI() error {
clientOption, err := util.GetWorkloadAPIClientOption(a.c.BindAddress)
if err != nil {
a.c.Log.WithError(err).Error("Failed to get Workload API client options for health check")
return err
}
_, err = workloadapi.FetchX509Bundles(context.TODO(), nil, clientOption)
if status.Code(err) == codes.Unavailable {
// Only an unavailable status fails the health check.
return errors.New("workload api is unavailable")
}
return nil
}
type agentHealthDetails struct {
WorkloadAPIErr string `json:"make_new_x509_err,omitempty"`
}
func errString(err error) string {
if err != nil {
return err.Error()
}
return ""
}