This repository has been archived by the owner on Apr 7, 2020. It is now read-only.
forked from istio/istio
-
Notifications
You must be signed in to change notification settings - Fork 152
/
list.go
390 lines (326 loc) · 9.79 KB
/
list.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
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
// Copyright 2017 Istio Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// nolint: lll
//go:generate $GOPATH/src/istio.io/istio/bin/mixer_codegen.sh -a mixer/adapter/list/config/config.proto -x "-n listchecker -t listentry"
// Package list provides an adapter that implements the listEntry
// template to enable blacklist / whitelist checking of values.
package list // import "istio.io/istio/mixer/adapter/list"
import (
"context"
"crypto/sha1"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"regexp"
"strings"
"sync"
"time"
"github.com/gogo/googleapis/google/rpc"
"istio.io/api/policy/v1beta1"
"istio.io/istio/mixer/adapter/list/config"
"istio.io/istio/mixer/pkg/adapter"
"istio.io/istio/mixer/pkg/status"
"istio.io/istio/mixer/template/listentry"
)
type (
handler struct {
log adapter.Logger
closing chan bool
refreshTicker *time.Ticker
purgeTimer *time.Timer
config config.Params
lock sync.Mutex
list list
lastFetchError error
latestSHA [sha1.Size]byte
// indirection to enable fault injection
readAll func(io.Reader) ([]byte, error)
}
// a specific list we use to check against
list interface {
checkList(symbol string) (bool, error)
numEntries() int
}
)
///////////////// Runtime Methods ///////////////
func (h *handler) HandleListEntry(_ context.Context, entry *listentry.Instance) (adapter.CheckResult, error) {
h.lock.Lock()
l := h.list
err := h.lastFetchError
h.lock.Unlock()
if l == nil {
// no valid list
return adapter.CheckResult{}, err
}
var value string
switch entryVal := entry.Value.(type) {
case *v1beta1.Value:
strVal := entryVal.GetStringValue()
ipVal := entryVal.GetIpAddressValue()
if strVal != "" {
value = strVal
} else if ipVal != nil {
// IP_ADDRESS comes in as byte array.
value = net.IP(ipVal.Value).String()
} else {
return getCheckResult(h.config, rpc.INVALID_ARGUMENT, fmt.Sprintf("%v is not a valid string or IP address", entryVal)), nil
}
case string:
value = entryVal
case []byte:
value = net.IP(entryVal).String()
default:
return getCheckResult(h.config, rpc.INVALID_ARGUMENT, fmt.Sprintf("%v is not a valid string or IP address", entryVal)), nil
}
found, err := l.checkList(value)
code := rpc.OK
msg := ""
if err != nil {
code = rpc.INVALID_ARGUMENT
msg = err.Error()
} else if h.config.Blacklist {
if found {
code = rpc.PERMISSION_DENIED
msg = fmt.Sprintf("%s is blacklisted", value)
}
} else if !found {
code = rpc.PERMISSION_DENIED
msg = fmt.Sprintf("%s is not whitelisted", value)
}
return getCheckResult(h.config, code, msg), nil
}
func (h *handler) Close() error {
close(h.closing)
if h.refreshTicker != nil {
h.refreshTicker.Stop()
h.purgeTimer.Stop()
}
return nil
}
// listRefresher updates the list by polling from the provider on a fixed interval
func (h *handler) listRefresher() {
for {
select {
case <-h.refreshTicker.C:
h.fetchList()
case <-h.purgeTimer.C:
h.purgeList()
case <-h.closing:
return
}
}
}
// fetchList retrieves and prepares an updated list
//
// TODO: This should implement some more aggressive retry mechanism.
// Right now, it a fetch fails, the code will just punt and wait
// until the next refresh timer tick to try again. When a failure
// happens, the code should switch to a more aggressive incremental
// backoff approach so that an updated list can be gotten as soon as
// things are back online.
func (h *handler) fetchList() {
buf := []byte{}
sha := h.latestSHA
var err error
if h.config.ProviderUrl != "" {
h.log.Infof("Fetching list from %s", h.config.ProviderUrl)
var resp *http.Response
resp, err = http.Get(h.config.ProviderUrl)
if err != nil || resp.StatusCode != http.StatusOK {
if err != nil {
err = h.log.Errorf("could not fetch list from %s: %v", h.config.ProviderUrl, err)
} else {
err = h.log.Errorf("could not fetch list from %s: %v", h.config.ProviderUrl, resp.StatusCode)
}
h.lock.Lock()
h.lastFetchError = err
h.lock.Unlock()
return
}
// TODO: could lead to OOM since this is unbounded
buf, err = h.readAll(resp.Body)
if err != nil {
err = h.log.Errorf("Could not read from %s: %v", h.config.ProviderUrl, err)
h.lock.Lock()
h.lastFetchError = err
h.lock.Unlock()
return
}
// determine whether the list has changed since the last fetch
sha = sha1.Sum(buf)
if sha == h.latestSHA && h.list != nil {
// the list hasn't changed since last time
h.log.Infof("Fetched list is unchanged")
h.resetPurgeTimer()
return
}
}
var l list
switch h.config.EntryType {
case config.STRINGS:
l = parseStringList(buf, h.config.Overrides)
case config.CASE_INSENSITIVE_STRINGS:
l = parseCaseInsensitiveStringList(buf, h.config.Overrides)
case config.IP_ADDRESSES:
l, err = parseIPList(buf, h.config.Overrides)
if err != nil {
err = h.log.Errorf("Could not parse data from %s: %v", h.config.ProviderUrl, err)
h.lock.Lock()
h.lastFetchError = err
h.lock.Unlock()
return
}
case config.REGEX:
l, err = parseRegexList(buf, h.config.Overrides)
if err != nil {
err = h.log.Errorf("Could not parse data from %s: %v", h.config.ProviderUrl, err)
h.lock.Lock()
h.lastFetchError = err
h.lock.Unlock()
return
}
}
// install the new list
h.log.Infof("Installing updated list with %d entries", l.numEntries())
h.lock.Lock()
h.list = l
h.lastFetchError = nil
h.lock.Unlock()
h.latestSHA = sha
h.resetPurgeTimer()
}
func (h *handler) resetPurgeTimer() {
if h.purgeTimer == nil {
return
}
// prevent the next purge from happening
h.purgeTimer.Stop()
// clean up the channel in case a message is already pending
select {
case <-h.purgeTimer.C:
default:
}
// setup the purge timer to clean up the list if it doesn't get refreshed soon enough
h.purgeTimer.Reset(h.config.Ttl)
}
func (h *handler) purgeList() {
h.log.Warningf("Purging list due to inability to refresh it in time")
h.lock.Lock()
h.list = nil
h.lock.Unlock()
}
func (h *handler) hasData() (bool, error) {
h.lock.Lock()
result := h.list != nil
err := h.lastFetchError
h.lock.Unlock()
return result, err
}
func getCheckResult(config config.Params, code rpc.Code, msg string) adapter.CheckResult {
return adapter.CheckResult{
Status: status.WithMessage(code, msg),
ValidDuration: config.CachingInterval,
ValidUseCount: config.CachingUseCount,
}
}
///////////////// Bootstrap ///////////////
// GetInfo returns the Info associated with this adapter implementation.
func GetInfo() adapter.Info {
return adapter.Info{
Name: "listchecker",
Impl: "istio.io/istio/mixer/adapter/list",
Description: "Checks whether an entry is present in a list",
SupportedTemplates: []string{listentry.TemplateName},
DefaultConfig: &config.Params{
RefreshInterval: 60 * time.Second,
Ttl: 300 * time.Second,
CachingInterval: 300 * time.Second,
CachingUseCount: 10000,
EntryType: config.STRINGS,
Blacklist: false,
},
NewBuilder: func() adapter.HandlerBuilder { return &builder{} },
}
}
type builder struct {
adapterConfig *config.Params
}
func (*builder) SetListEntryTypes(map[string]*listentry.Type) {}
func (b *builder) SetAdapterConfig(cfg adapter.Config) { b.adapterConfig = cfg.(*config.Params) }
func (b *builder) Validate() (ce *adapter.ConfigErrors) {
ac := b.adapterConfig
if ac.ProviderUrl != "" {
u, err := url.Parse(ac.ProviderUrl)
if err != nil {
ce = ce.Append("providerUrl", err)
} else if u.Scheme == "" || u.Host == "" {
ce = ce.Appendf("providerUrl", "URL scheme and host cannot be empty")
}
if ac.RefreshInterval < 1*time.Second {
ce = ce.Appendf("refreshInterval", "refresh interval must be at least 1 second, it is %v", ac.RefreshInterval)
}
if ac.Ttl < ac.RefreshInterval {
ce = ce.Appendf("ttl", "ttl must be > refreshInterval, ttl is %v and refreshInterval is %v", ac.Ttl, ac.RefreshInterval)
}
}
if ac.CachingInterval < 0 {
ce = ce.Appendf("cachingInterval", "caching interval must be >= 0, it is %v", ac.CachingInterval)
}
if ac.CachingUseCount < 0 {
ce = ce.Appendf("cachingUseCount", "caching use count must be >= 0, it is %v", ac.CachingUseCount)
}
if ac.EntryType == config.IP_ADDRESSES {
for _, ip := range ac.Overrides {
orig := ip
if !strings.Contains(ip, "/") {
ip += "/32"
}
_, _, err := net.ParseCIDR(ip)
if err != nil {
ce = ce.Appendf("overrides", "could not parse ip address override %s: %v", orig, err)
}
}
}
if ac.EntryType == config.REGEX {
for _, regex := range ac.Overrides {
if _, err := regexp.Compile(regex); err != nil {
ce = ce.Appendf("overrides", "could not parse regex override %s: %v", regex, err)
}
}
}
return
}
func (b *builder) Build(context context.Context, env adapter.Env) (adapter.Handler, error) {
ac := b.adapterConfig
h := &handler{
log: env.Logger(),
closing: make(chan bool),
config: *ac,
readAll: ioutil.ReadAll,
}
if ac.ProviderUrl != "" {
h.refreshTicker = time.NewTicker(ac.RefreshInterval)
h.purgeTimer = time.NewTimer(ac.Ttl)
}
// Load up the list synchronously so we're ready to accept traffic immediately.
h.fetchList()
if ac.ProviderUrl != "" {
// goroutine to periodically refresh the list
env.ScheduleDaemon(h.listRefresher)
}
return h, nil
}