forked from open-policy-agent/opa
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathruntime_test.go
366 lines (293 loc) · 8.88 KB
/
runtime_test.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
// Copyright 2016 The OPA Authors. All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.
package runtime
import (
"bytes"
"context"
"encoding/json"
"io/ioutil"
"net/http"
"net/http/httptest"
"os"
"path"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"github.com/open-policy-agent/opa/internal/report"
"github.com/sirupsen/logrus"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/storage"
"github.com/open-policy-agent/opa/util"
"github.com/open-policy-agent/opa/util/test"
)
func TestWatchPaths(t *testing.T) {
fs := map[string]string{
"/foo/bar/baz.json": "true",
}
expected := []string{
".", "/foo", "/foo/bar",
}
test.WithTempFS(fs, func(rootDir string) {
paths, err := getWatchPaths([]string{"prefix:" + rootDir + "/foo"})
if err != nil {
t.Fatalf("Unexpected error: %v", err)
}
result := []string{}
for _, path := range paths {
result = append(result, filepath.Clean(strings.TrimPrefix(path, rootDir)))
}
if !reflect.DeepEqual(expected, result) {
t.Fatalf("Expected %q but got: %q", expected, result)
}
})
}
func TestRuntimeProcessWatchEvents(t *testing.T) {
testRuntimeProcessWatchEvents(t, false)
}
func TestRuntimeProcessWatchEventsWithBundle(t *testing.T) {
testRuntimeProcessWatchEvents(t, true)
}
func testRuntimeProcessWatchEvents(t *testing.T, asBundle bool) {
t.Helper()
ctx := context.Background()
fs := map[string]string{
"test/some/data.json": `{
"hello": "world"
}`,
}
test.WithTempFS(fs, func(rootDir string) {
// Prefix the directory intended to be watched with at least one
// directory to avoid permission issues on the local host. Otherwise we
// cannot always watch the tmp directory's parent.
rootDir = filepath.Join(rootDir, "test")
params := NewParams()
params.Paths = []string{rootDir}
params.BundleMode = asBundle
rt, err := NewRuntime(ctx, params)
if err != nil {
t.Fatal(err)
}
txn := storage.NewTransactionOrDie(ctx, rt.Store)
_, err = rt.Store.Read(ctx, txn, storage.MustParsePath("/system/version"))
if err != nil {
t.Fatal(err)
}
rt.Store.Abort(ctx, txn)
var buf bytes.Buffer
if err := rt.startWatcher(ctx, params.Paths, onReloadPrinter(&buf)); err != nil {
t.Fatalf("Unexpected watcher init error: %v", err)
}
expected := map[string]interface{}{
"hello": "world-2",
}
if err := ioutil.WriteFile(path.Join(rootDir, "some/data.json"), util.MustMarshalJSON(expected), 0644); err != nil {
panic(err)
}
t0 := time.Now()
path := storage.MustParsePath("/some")
// In practice, reload takes ~100us on development machine.
maxWaitTime := time.Second * 1
var val interface{}
for time.Since(t0) < maxWaitTime {
time.Sleep(1 * time.Millisecond)
txn := storage.NewTransactionOrDie(ctx, rt.Store)
var err error
val, err = rt.Store.Read(ctx, txn, path)
if err != nil {
panic(err)
}
// Ensure the update didn't overwrite the system version information
_, err = rt.Store.Read(ctx, txn, storage.MustParsePath("/system/version"))
if err != nil {
t.Fatal(err)
}
rt.Store.Abort(ctx, txn)
if reflect.DeepEqual(val, expected) {
return // success
}
}
t.Fatalf("Did not see expected change in %v, last value: %v, buf: %v", maxWaitTime, val, buf.String())
})
}
func TestRuntimeProcessWatchEventPolicyError(t *testing.T) {
testRuntimeProcessWatchEventPolicyError(t, false)
}
func TestRuntimeProcessWatchEventPolicyErrorWithBundle(t *testing.T) {
testRuntimeProcessWatchEventPolicyError(t, true)
}
func testRuntimeProcessWatchEventPolicyError(t *testing.T, asBundle bool) {
ctx := context.Background()
fs := map[string]string{
"test/x.rego": `package test
default x = 1
`,
}
test.WithTempFS(fs, func(rootDir string) {
// Prefix the directory intended to be watched with at least one
// directory to avoid permission issues on the local host. Otherwise we
// cannot always watch the tmp directory's parent.
rootDir = filepath.Join(rootDir, "test")
params := NewParams()
params.Paths = []string{rootDir}
params.BundleMode = asBundle
rt, err := NewRuntime(ctx, params)
if err != nil {
t.Fatal(err)
}
storage.Txn(ctx, rt.Store, storage.WriteParams, func(txn storage.Transaction) error {
return rt.Store.UpsertPolicy(ctx, txn, "out-of-band.rego", []byte(`package foo`))
})
ch := make(chan error)
testFunc := func(d time.Duration, err error) {
ch <- err
}
if err := rt.startWatcher(ctx, params.Paths, testFunc); err != nil {
t.Fatalf("Unexpected watcher init error: %v", err)
}
newModule := []byte(`package test
default x = 2`)
if err := ioutil.WriteFile(path.Join(rootDir, "y.rego"), newModule, 0644); err != nil {
t.Fatal(err)
}
// Wait for up to 1 second before considering test failed. On Linux we
// observe multiple events on write (e.g., create -> write) which
// triggers two errors instead of one, whereas on Darwin only a single
// event (e.g., create) is sent. Same as below.
maxWait := time.Second
timer := time.NewTimer(maxWait)
// Expect type error.
func() {
for {
select {
case result := <-ch:
if errs, ok := result.(ast.Errors); ok {
if errs[0].Code == ast.TypeErr {
err = nil
return
}
}
err = result
case <-timer.C:
return
}
}
}()
if err != nil {
t.Fatalf("Expected specific failure before %v. Last error: %v", maxWait, err)
}
if err := os.Remove(path.Join(rootDir, "x.rego")); err != nil {
t.Fatal(err)
}
timer = time.NewTimer(maxWait)
// Expect no error.
func() {
for {
select {
case result := <-ch:
if result == nil {
err = nil
return
}
err = result
case <-timer.C:
return
}
}
}()
if err != nil {
t.Fatalf("Expected result to succeed before %v. Last error: %v", maxWait, err)
}
})
}
func TestCheckOPAUpdateBadURL(t *testing.T) {
testCheckOPAUpdate(t, "http://foo:8112", nil)
}
func TestCheckOPAUpdateWithNewUpdate(t *testing.T) {
exp := &report.DataResponse{Latest: report.ReleaseDetails{
Download: "https://openpolicyagent.org/downloads/v100.0.0/opa_darwin_amd64",
ReleaseNotes: "https://github.com/open-policy-agent/opa/releases/tag/v100.0.0",
LatestRelease: "v100.0.0",
}}
// test server
baseURL, teardown := getTestServer(exp, http.StatusOK)
defer teardown()
testCheckOPAUpdate(t, baseURL, exp)
}
func TestCheckOPAUpdateLoopBadURL(t *testing.T) {
testCheckOPAUpdateLoop(t, "http://foo:8112", "Unable to send OPA version report")
}
func TestCheckOPAUpdateLoopNoUpdate(t *testing.T) {
exp := &report.DataResponse{Latest: report.ReleaseDetails{
OPAUpToDate: true,
}}
// test server
baseURL, teardown := getTestServer(exp, http.StatusOK)
defer teardown()
testCheckOPAUpdateLoop(t, baseURL, "OPA is up to date.")
}
func TestCheckOPAUpdateLoopWithNewUpdate(t *testing.T) {
exp := &report.DataResponse{Latest: report.ReleaseDetails{
Download: "https://openpolicyagent.org/downloads/v100.0.0/opa_darwin_amd64",
ReleaseNotes: "https://github.com/open-policy-agent/opa/releases/tag/v100.0.0",
LatestRelease: "v100.0.0",
OPAUpToDate: false,
}}
// test server
baseURL, teardown := getTestServer(exp, http.StatusOK)
defer teardown()
testCheckOPAUpdateLoop(t, baseURL, "OPA is out of date.")
}
func getTestServer(update interface{}, statusCode int) (baseURL string, teardownFn func()) {
mux := http.NewServeMux()
ts := httptest.NewServer(mux)
mux.HandleFunc("/v1/version", func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(statusCode)
bs, _ := json.Marshal(update)
w.Header().Set("Content-Type", "application/json")
w.Write(bs)
})
return ts.URL, ts.Close
}
func testCheckOPAUpdate(t *testing.T, url string, expected *report.DataResponse) {
t.Helper()
os.Setenv("OPA_TELEMETRY_SERVICE_URL", url)
ctx := context.Background()
rt := getTestRuntime(ctx, t)
result := rt.checkOPAUpdate(ctx)
if !reflect.DeepEqual(result, expected) {
t.Fatalf("Expected output:\"%v\" but got: \"%v\"", expected, result)
}
}
func testCheckOPAUpdateLoop(t *testing.T, url, expected string) {
t.Helper()
os.Setenv("OPA_TELEMETRY_SERVICE_URL", url)
ctx := context.Background()
rt := getTestRuntime(ctx, t)
var stdout bytes.Buffer
rt.Params.Output = &stdout
logrus.SetOutput(rt.Params.Output)
logrus.SetLevel(logrus.DebugLevel)
done := make(chan struct{})
go func() {
d := time.Duration(int64(time.Millisecond) * 1)
rt.checkOPAUpdateLoop(ctx, d, done)
}()
time.Sleep(2 * time.Millisecond)
done <- struct{}{}
if !strings.Contains(stdout.String(), expected) {
t.Fatalf("Expected output to contain: \"%v\" but got \"%v\"", expected, stdout.String())
}
}
func getTestRuntime(ctx context.Context, t *testing.T) *Runtime {
t.Helper()
params := NewParams()
params.EnableVersionCheck = true
rt, err := NewRuntime(ctx, params)
if err != nil {
t.Fatalf("Unexpected error %v", err)
}
return rt
}