-
Notifications
You must be signed in to change notification settings - Fork 476
/
authorized_entryfetcher.go
265 lines (223 loc) · 8.28 KB
/
authorized_entryfetcher.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
package endpoints
import (
"context"
"errors"
"fmt"
"time"
"github.com/andres-erbsen/clock"
"github.com/sirupsen/logrus"
"github.com/spiffe/go-spiffe/v2/spiffeid"
"github.com/spiffe/spire-api-sdk/proto/spire/api/types"
"github.com/spiffe/spire/pkg/server/api"
"github.com/spiffe/spire/pkg/server/authorizedentries"
"github.com/spiffe/spire/pkg/server/datastore"
"google.golang.org/grpc/codes"
"google.golang.org/grpc/status"
)
var _ api.AuthorizedEntryFetcher = (*AuthorizedEntryFetcherWithEventsBasedCache)(nil)
const buildCachePageSize = 10000
type AuthorizedEntryFetcherWithEventsBasedCache struct {
cache *authorizedentries.Cache
clk clock.Clock
log logrus.FieldLogger
ds datastore.DataStore
cacheReloadInterval time.Duration
pruneEventsOlderThan time.Duration
lastRegistrationEntryEventID uint
lastAttestedNodeEventID uint
}
func NewAuthorizedEntryFetcherWithEventsBasedCache(ctx context.Context, log logrus.FieldLogger, clk clock.Clock, ds datastore.DataStore, cacheReloadInterval, pruneEventsOlderThan time.Duration) (*AuthorizedEntryFetcherWithEventsBasedCache, error) {
log.Info("Building event-based in-memory entry cache")
cache, lastRegistrationEntryEventID, lastAttestedNodeEventID, err := buildCache(ctx, ds, clk)
if err != nil {
return nil, err
}
log.Info("Completed building event-based in-memory entry cache")
return &AuthorizedEntryFetcherWithEventsBasedCache{
cache: cache,
clk: clk,
log: log,
ds: ds,
cacheReloadInterval: cacheReloadInterval,
pruneEventsOlderThan: pruneEventsOlderThan,
lastRegistrationEntryEventID: lastRegistrationEntryEventID,
lastAttestedNodeEventID: lastAttestedNodeEventID,
}, nil
}
func (a *AuthorizedEntryFetcherWithEventsBasedCache) FetchAuthorizedEntries(_ context.Context, agentID spiffeid.ID) ([]*types.Entry, error) {
return a.cache.GetAuthorizedEntries(agentID), nil
}
// RunUpdateCacheTask starts a ticker which rebuilds the in-memory entry cache.
func (a *AuthorizedEntryFetcherWithEventsBasedCache) RunUpdateCacheTask(ctx context.Context) error {
for {
select {
case <-ctx.Done():
a.log.Debug("Stopping in-memory entry cache hydrator")
return nil
case <-a.clk.After(a.cacheReloadInterval):
err := a.updateCache(ctx)
if err != nil {
a.log.WithError(err).Error("Failed to update entry cache")
}
}
}
}
// PruneEventsTask start a ticker which prunes old events
func (a *AuthorizedEntryFetcherWithEventsBasedCache) PruneEventsTask(ctx context.Context) error {
for {
select {
case <-ctx.Done():
a.log.Debug("Stopping event pruner")
return nil
case <-a.clk.After(a.pruneEventsOlderThan / 2):
a.log.Debug("Pruning events")
if err := a.pruneEvents(ctx, a.pruneEventsOlderThan); err != nil {
a.log.WithError(err).Error("Failed to prune events")
}
}
}
}
func (a *AuthorizedEntryFetcherWithEventsBasedCache) pruneEvents(ctx context.Context, olderThan time.Duration) error {
pruneRegistrationEntriesEventsErr := a.ds.PruneRegistrationEntriesEvents(ctx, olderThan)
pruneAttestedNodesEventsErr := a.ds.PruneAttestedNodesEvents(ctx, olderThan)
return errors.Join(pruneRegistrationEntriesEventsErr, pruneAttestedNodesEventsErr)
}
func (a *AuthorizedEntryFetcherWithEventsBasedCache) updateCache(ctx context.Context) error {
updateRegistrationEntriesCacheErr := a.updateRegistrationEntriesCache(ctx)
updateAttestedNodesCacheErr := a.updateAttestedNodesCache(ctx)
return errors.Join(updateRegistrationEntriesCacheErr, updateAttestedNodesCacheErr)
}
func (a *AuthorizedEntryFetcherWithEventsBasedCache) updateRegistrationEntriesCache(ctx context.Context) error {
req := &datastore.ListRegistrationEntriesEventsRequest{
GreaterThanEventID: a.lastRegistrationEntryEventID,
}
resp, err := a.ds.ListRegistrationEntriesEvents(ctx, req)
if err != nil {
return err
}
seenMap := map[string]struct{}{}
for _, event := range resp.Events {
// Skip fetching entries we've already fetched this call
if _, seen := seenMap[event.EntryID]; seen {
a.lastRegistrationEntryEventID = event.EventID
continue
}
seenMap[event.EntryID] = struct{}{}
commonEntry, err := a.ds.FetchRegistrationEntry(ctx, event.EntryID)
if err != nil {
return err
}
a.lastRegistrationEntryEventID = event.EventID
entry, err := api.RegistrationEntryToProto(commonEntry)
if err != nil {
a.cache.RemoveEntry(event.EntryID)
continue
}
a.cache.UpdateEntry(entry)
}
return nil
}
func (a *AuthorizedEntryFetcherWithEventsBasedCache) updateAttestedNodesCache(ctx context.Context) error {
req := &datastore.ListAttestedNodesEventsRequest{
GreaterThanEventID: a.lastAttestedNodeEventID,
}
resp, err := a.ds.ListAttestedNodesEvents(ctx, req)
if err != nil {
return err
}
seenMap := map[string]struct{}{}
for _, event := range resp.Events {
// Skip fetching entries we've already fetched this call
if _, seen := seenMap[event.SpiffeID]; seen {
a.lastAttestedNodeEventID = event.EventID
continue
}
seenMap[event.SpiffeID] = struct{}{}
node, err := a.ds.FetchAttestedNode(ctx, event.SpiffeID)
if err != nil {
return err
}
a.lastAttestedNodeEventID = event.EventID
if node == nil {
a.cache.RemoveAgent(event.SpiffeID)
continue
}
selectors, err := a.ds.GetNodeSelectors(ctx, event.SpiffeID, datastore.RequireCurrent)
if err != nil {
return err
}
node.Selectors = selectors
agentExpiresAt := time.Unix(node.CertNotAfter, 0)
if agentExpiresAt.Before(a.clk.Now()) {
a.cache.RemoveAgent(event.SpiffeID)
continue
}
a.cache.UpdateAgent(node.SpiffeId, agentExpiresAt, api.ProtoFromSelectors(node.Selectors))
}
return nil
}
func buildCache(ctx context.Context, ds datastore.DataStore, clk clock.Clock) (*authorizedentries.Cache, uint, uint, error) {
cache := authorizedentries.NewCache()
lastRegistrationEntryEventID, err := buildRegistrationEntriesCache(ctx, ds, cache, buildCachePageSize)
if err != nil {
return nil, 0, 0, err
}
lastAttestedNodeEventID, err := buildAttestedNodesCache(ctx, ds, clk, cache)
if err != nil {
return nil, 0, 0, err
}
return cache, lastRegistrationEntryEventID, lastAttestedNodeEventID, nil
}
// buildRegistrationEntriesCache Fetches all registration entries and adds them to the cache
func buildRegistrationEntriesCache(ctx context.Context, ds datastore.DataStore, cache *authorizedentries.Cache, pageSize int32) (uint, error) {
lastEventID, err := ds.GetLatestRegistrationEntryEventID(ctx)
if err != nil && status.Code(err) != codes.NotFound {
return 0, fmt.Errorf("failed to get latest registration entry event id: %w", err)
}
var token string
for {
resp, err := ds.ListRegistrationEntries(ctx, &datastore.ListRegistrationEntriesRequest{
DataConsistency: datastore.RequireCurrent, // preliminary loading should not be done via read-replicas
Pagination: &datastore.Pagination{
Token: token,
PageSize: pageSize,
},
})
if err != nil {
return 0, fmt.Errorf("failed to list registration entries: %w", err)
}
token = resp.Pagination.Token
if token == "" {
break
}
entries, err := api.RegistrationEntriesToProto(resp.Entries)
if err != nil {
return 0, fmt.Errorf("failed to convert registration entries: %w", err)
}
for _, entry := range entries {
cache.UpdateEntry(entry)
}
}
return lastEventID, nil
}
// buildAttestedNodesCache Fetches all attested nodes and adds the unexpired ones to the cache
func buildAttestedNodesCache(ctx context.Context, ds datastore.DataStore, clk clock.Clock, cache *authorizedentries.Cache) (uint, error) {
lastEventID, err := ds.GetLatestAttestedNodeEventID(ctx)
if err != nil && status.Code(err) != codes.NotFound {
return 0, fmt.Errorf("failed to get latest attested node event id: %w", err)
}
resp, err := ds.ListAttestedNodes(ctx, &datastore.ListAttestedNodesRequest{
FetchSelectors: true,
})
if err != nil {
return 0, fmt.Errorf("failed to list attested nodes: %w", err)
}
for _, node := range resp.Nodes {
agentExpiresAt := time.Unix(node.CertNotAfter, 0)
if agentExpiresAt.Before(clk.Now()) {
continue
}
cache.UpdateAgent(node.SpiffeId, agentExpiresAt, api.ProtoFromSelectors(node.Selectors))
}
return lastEventID, nil
}