Debian Codegraph @

runtimevar/filevar/filevar_test.go

raw
1 // Copyright 2018 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package filevar
16
17 import (
18 "context"
19 "errors"
20 "net/url"
21 "os"
22 "path/filepath"
23 "strings"
24 "testing"
25 "time"
26
27 "github.com/google/go-cmp/cmp"
28 "gocloud.dev/runtimevar"
29 "gocloud.dev/runtimevar/driver"
30 "gocloud.dev/runtimevar/drivertest"
31 "gocloud.dev/secrets"
32 _ "gocloud.dev/secrets/localsecrets"
33 )
34
35 type harness struct {
36 dir string
37 closer func()
38 }
39
40 func newHarness(t *testing.T) (drivertest.Harness, error) {
41 t.Helper()
42
43 dir := t.TempDir()
44
45 return &harness{
46 dir: dir,
47 closer: func() { _ = os.RemoveAll(dir) },
48 }, nil
49 }
50
51 func (h *harness) MakeWatcher(ctx context.Context, name string, decoder *runtimevar.Decoder) (driver.Watcher, error) {
52 // filevar uses a goroutine in the background that poll every WaitDuration if
53 // the file is deleted. Make this fast for tests.
54 return newWatcher(filepath.Join(h.dir, name), decoder, &Options{WaitDuration: 1 * time.Millisecond})
55 }
56
57 func (h *harness) CreateVariable(ctx context.Context, name string, val []byte) error {
58 // Write to a temporary file and rename; otherwise,
59 // Watch can read an empty file during the write.
60 tmp, err := os.CreateTemp(h.dir, "tmp")
61 if err != nil {
62 return err
63 }
64 if _, err := tmp.Write(val); err != nil {
65 tmp.Close()
66 return err
67 }
68 tmp.Close()
69 return os.Rename(tmp.Name(), filepath.Join(h.dir, name))
70 }
71
72 func (h *harness) UpdateVariable(ctx context.Context, name string, val []byte) error {
73 return h.CreateVariable(ctx, name, val)
74 }
75
76 func (h *harness) DeleteVariable(ctx context.Context, name string) error {
77 path := filepath.Join(h.dir, name)
78 return os.Remove(path)
79 }
80
81 func (h *harness) Close() {
82 h.closer()
83 }
84
85 func (h *harness) Mutable() bool { return true }
86
87 func TestConformance(t *testing.T) {
88 drivertest.RunConformanceTests(t, newHarness, []drivertest.AsTest{verifyAs{}})
89 }
90
91 type verifyAs struct{}
92
93 func (verifyAs) Name() string {
94 return "verify As"
95 }
96
97 func (verifyAs) SnapshotCheck(s *runtimevar.Snapshot) error {
98 var ss string
99 if s.As(&ss) {
100 return errors.New("Snapshot.As expected to fail")
101 }
102 return nil
103 }
104
105 func (verifyAs) ErrorCheck(v *runtimevar.Variable, err error) error {
106 var ss string
107 if v.ErrorAs(err, &ss) {
108 return errors.New("runtimevar.ErrorAs expected to fail")
109 }
110 return nil
111 }
112
113 // Filevar-specific tests.
114
115 func TestOpenVariable(t *testing.T) {
116 dir := t.TempDir()
117
118 tests := []struct {
119 description string
120 path string
121 decoder *runtimevar.Decoder
122 want string
123 wantErr bool
124 }{
125 {
126 description: "empty path results in error",
127 decoder: runtimevar.StringDecoder,
128 wantErr: true,
129 },
130 {
131 description: "empty decoder results in error",
132 path: filepath.Join(dir, "foo.txt"),
133 wantErr: true,
134 },
135 {
136 description: "basic path works",
137 path: filepath.Join(dir, "foo.txt"),
138 decoder: runtimevar.StringDecoder,
139 want: filepath.Join(dir, "foo.txt"),
140 },
141 {
142 description: "path with extra relative dirs works and is cleaned up",
143 path: filepath.Join(dir, "bar/../foo.txt"),
144 decoder: runtimevar.StringDecoder,
145 want: filepath.Join(dir, "foo.txt"),
146 },
147 }
148
149 for _, test := range tests {
150 t.Run(test.description, func(t *testing.T) {
151 // Create driver impl.
152 drv, err := newWatcher(test.path, test.decoder, nil)
153 if (err != nil) != test.wantErr {
154 t.Errorf("got err %v want error %v", err, test.wantErr)
155 }
156 if drv != nil {
157 if drv.path != test.want {
158 t.Errorf("got %q want %q", drv.path, test.want)
159 }
160 drv.Close()
161 }
162
163 // Create portable type.
164 w, err := OpenVariable(test.path, test.decoder, nil)
165 if (err != nil) != test.wantErr {
166 t.Errorf("got err %v want error %v", err, test.wantErr)
167 }
168 if w != nil {
169 w.Close()
170 }
171 })
172 }
173 }
174
175 func TestOpenVariableURL(t *testing.T) {
176 dir := t.TempDir()
177
178 jsonPath := filepath.Join(dir, "myvar.json")
179 if err := os.WriteFile(jsonPath, []byte(`{"Foo": "Bar"}`), 0o666); err != nil {
180 t.Fatal(err)
181 }
182 txtPath := filepath.Join(dir, "myvar.txt")
183 if err := os.WriteFile(txtPath, []byte("hello world!"), 0o666); err != nil {
184 t.Fatal(err)
185 }
186 nonexistentPath := filepath.Join(dir, "filenotfound")
187 ctx := context.Background()
188 secretsPath := filepath.Join(dir, "mysecret.txt")
189 cleanup, err := setupTestSecrets(ctx, dir, secretsPath)
190 if err != nil {
191 t.Fatal(err)
192 }
193 defer cleanup()
194
195 // Convert paths to a URL path, adding a leading "/" if needed on Windows
196 // (on Unix, dirpath already has a leading "/").
197 jsonPath = filepath.ToSlash(jsonPath)
198 txtPath = filepath.ToSlash(txtPath)
199 nonexistentPath = filepath.ToSlash(nonexistentPath)
200 secretsPath = filepath.ToSlash(secretsPath)
201 if os.PathSeparator != '/' {
202 if !strings.HasPrefix(jsonPath, "/") {
203 jsonPath = "/" + jsonPath
204 }
205 if !strings.HasPrefix(txtPath, "/") {
206 txtPath = "/" + txtPath
207 }
208 if !strings.HasPrefix(nonexistentPath, "/") {
209 nonexistentPath = "/" + nonexistentPath
210 }
211 if !strings.HasPrefix(secretsPath, "/") {
212 secretsPath = "/" + secretsPath
213 }
214 }
215
216 tests := []struct {
217 URL string
218 WantErr bool
219 WantWatchErr bool
220 Want any
221 }{
222 // Variable construction succeeds, but the file does not exist.
223 {"file://" + nonexistentPath, false, true, nil},
224 // Variable construction fails due to invalid decoder arg.
225 {"file://" + txtPath + "?decoder=notadecoder", true, false, nil},
226 // Variable construction fails due to invalid arg.
227 {"file://" + txtPath + "?param=value", true, false, nil},
228 // Working example with default decoder.
229 {"file://" + txtPath, false, false, []byte("hello world!")},
230 // Working example with string decoder.
231 {"file://" + txtPath + "?decoder=string", false, false, "hello world!"},
232 // Working example with JSON decoder.
233 {"file://" + jsonPath + "?decoder=jsonmap", false, false, &map[string]any{"Foo": "Bar"}},
234 // Working example with decrypt (default) decoder.
235 {"file://" + secretsPath + "?decoder=decrypt", false, false, []byte(`{"Foo":"Bar"}`)},
236 // Working example with decrypt+bytes decoder.
237 {"file://" + secretsPath + "?decoder=decrypt+bytes", false, false, []byte(`{"Foo":"Bar"}`)},
238 // Working example with decrypt+json decoder.
239 {"file://" + secretsPath + "?decoder=decrypt+jsonmap", false, false, &map[string]any{"Foo": "Bar"}},
240 // Working example with escaped decrypt+json decoder
241 {"file://" + secretsPath + "?decoder=" + url.QueryEscape("decrypt+jsonmap"), false, false, &map[string]any{"Foo": "Bar"}},
242 // Setting wait.
243 {"file://" + txtPath + "?decoder=string&wait=1m", false, false, "hello world!"},
244 // Invalid wait.
245 {"file://" + txtPath + "?decoder=string&wait=xx", true, false, nil},
246 }
247
248 for _, test := range tests {
249 t.Run(test.URL, func(t *testing.T) {
250 v, err := runtimevar.OpenVariable(ctx, test.URL)
251 if (err != nil) != test.WantErr {
252 t.Errorf("%s: got error %v, want error %v", test.URL, err, test.WantErr)
253 }
254 if err != nil {
255 return
256 }
257 defer v.Close()
258 snapshot, err := v.Watch(ctx)
259 if (err != nil) != test.WantWatchErr {
260 t.Errorf("%s: got Watch error %v, want error %v", test.URL, err, test.WantWatchErr)
261 }
262 if err != nil {
263 return
264 }
265 if !cmp.Equal(snapshot.Value, test.Want) {
266 t.Errorf("%s: got snapshot value\n%v\n want\n%v", test.URL, snapshot.Value, test.Want)
267 }
268 })
269 }
270 }
271
272 func setupTestSecrets(ctx context.Context, dir, secretsPath string) (func(), error) {
273 const keeperEnv = "RUNTIMEVAR_KEEPER_URL"
274 const keeperURL = "base64key://smGbjm71Nxd1Ig5FS0wj9SlbzAIrnolCz9bQQ6uAhl4="
275 oldURL := os.Getenv(keeperEnv)
276 os.Setenv(keeperEnv, keeperURL)
277 cleanup := func() { os.Setenv(keeperEnv, oldURL) }
278
279 k, err := secrets.OpenKeeper(ctx, keeperURL)
280 if err != nil {
281 return cleanup, err
282 }
283 sc, err := k.Encrypt(ctx, []byte(`{"Foo":"Bar"}`))
284 if err != nil {
285 return cleanup, err
286 }
287 if err := os.WriteFile(secretsPath, sc, 0o666); err != nil {
288 return cleanup, err
289 }
290 return cleanup, nil
291 }