]> ruderich.org/simon Gitweb - nsscash/nsscash.git/blob - main_test.go
nsscash: main_test: add plain tests
[nsscash/nsscash.git] / main_test.go
1 // Copyright (C) 2019  Simon Ruderich
2 //
3 // This program is free software: you can redistribute it and/or modify
4 // it under the terms of the GNU Affero General Public License as published by
5 // the Free Software Foundation, either version 3 of the License, or
6 // (at your option) any later version.
7 //
8 // This program is distributed in the hope that it will be useful,
9 // but WITHOUT ANY WARRANTY; without even the implied warranty of
10 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11 // GNU Affero General Public License for more details.
12 //
13 // You should have received a copy of the GNU Affero General Public License
14 // along with this program.  If not, see <https://www.gnu.org/licenses/>.
15
16 package main
17
18 import (
19         "crypto/sha1"
20         "encoding/hex"
21         "fmt"
22         "io/ioutil"
23         "log"
24         "net/http"
25         "net/http/httptest"
26         "os"
27         "reflect"
28         "runtime"
29         "strings"
30         "testing"
31         "time"
32 )
33
34 const (
35         configPath = "testdata/config.toml"
36         statePath  = "testdata/state.json"
37         passwdPath = "testdata/passwd.nsscash"
38         plainPath  = "testdata/plain"
39         groupPath  = "testdata/group.nsscash"
40 )
41
42 type args struct {
43         t       *testing.T
44         url     string
45         handler *func(http.ResponseWriter, *http.Request)
46 }
47
48 // mustNotExist verifies that all given paths don't exist in the file system.
49 func mustNotExist(t *testing.T, paths ...string) {
50         for _, p := range paths {
51                 f, err := os.Open(p)
52                 if err != nil {
53                         if !os.IsNotExist(err) {
54                                 t.Errorf("path %q: unexpected error: %v",
55                                         p, err)
56                         }
57                 } else {
58                         t.Errorf("path %q exists", p)
59                         f.Close()
60                 }
61         }
62 }
63
64 // mustHaveHash checks if the given path content has the given SHA-1 string
65 // (in hex).
66 func mustHaveHash(t *testing.T, path string, hash string) {
67         x, err := ioutil.ReadFile(path)
68         if err != nil {
69                 t.Fatal(err)
70         }
71
72         h := sha1.New()
73         h.Write(x)
74         y := hex.EncodeToString(h.Sum(nil))
75
76         if y != hash {
77                 t.Errorf("%q has unexpected hash %q", path, y)
78         }
79 }
80
81 // mustBeErrorWithSubstring checks if the given error, represented as string,
82 // contains the given substring. This is somewhat ugly but the simplest way to
83 // check for proper errors.
84 func mustBeErrorWithSubstring(t *testing.T, err error, substring string) {
85         if err == nil {
86                 t.Errorf("err is nil")
87         } else if !strings.Contains(err.Error(), substring) {
88                 t.Errorf("err %q does not contain string %q", err, substring)
89         }
90 }
91
92 func mustWriteConfig(t *testing.T, config string) {
93         err := ioutil.WriteFile(configPath, []byte(config), 0644)
94         if err != nil {
95                 t.Fatal(err)
96         }
97 }
98
99 func mustWritePasswdConfig(t *testing.T, url string) {
100         mustWriteConfig(t, fmt.Sprintf(`
101 statepath = "%[1]s"
102
103 [[file]]
104 type = "passwd"
105 url = "%[2]s/passwd"
106 path = "%[3]s"
107 `, statePath, url, passwdPath))
108 }
109
110 func mustWriteGroupConfig(t *testing.T, url string) {
111         mustWriteConfig(t, fmt.Sprintf(`
112 statepath = "%[1]s"
113
114 [[file]]
115 type = "group"
116 url = "%[2]s/group"
117 path = "%[3]s"
118 `, statePath, url, groupPath))
119 }
120
121 // mustCreate creates a file, truncating it if it exists. It then changes the
122 // modification to be in the past.
123 func mustCreate(t *testing.T, path string) {
124         f, err := os.Create(path)
125         if err != nil {
126                 t.Fatal(err)
127         }
128         err = f.Close()
129         if err != nil {
130                 t.Fatal(err)
131         }
132
133         // Change modification time to the past to detect updates to the file
134         mustMakeOld(t, path)
135 }
136
137 // mustMakeOld change the modification time of all paths to be in the past.
138 func mustMakeOld(t *testing.T, paths ...string) {
139         old := time.Now().Add(-2 * time.Hour)
140         for _, p := range paths {
141                 err := os.Chtimes(p, old, old)
142                 if err != nil {
143                         t.Fatal(err)
144                 }
145         }
146 }
147
148 // mustMakeOld verifies that all paths have a modification time in the past,
149 // as set by mustMakeOld().
150 func mustBeOld(t *testing.T, paths ...string) {
151         for _, p := range paths {
152                 i, err := os.Stat(p)
153                 if err != nil {
154                         t.Fatal(err)
155                 }
156
157                 mtime := i.ModTime()
158                 now := time.Now()
159                 if now.Sub(mtime) < time.Hour {
160                         t.Errorf("%q was recently modified", p)
161                 }
162         }
163 }
164
165 // mustBeNew verifies that all paths have a modification time in the present.
166 func mustBeNew(t *testing.T, paths ...string) {
167         for _, p := range paths {
168                 i, err := os.Stat(p)
169                 if err != nil {
170                         t.Fatal(err)
171                 }
172
173                 mtime := i.ModTime()
174                 now := time.Now()
175                 if now.Sub(mtime) > time.Hour {
176                         t.Errorf("%q was not recently modified", p)
177                 }
178         }
179 }
180
181 func TestMainFetch(t *testing.T) {
182         // Suppress log messages
183         log.SetOutput(ioutil.Discard)
184         defer log.SetOutput(os.Stderr)
185
186         tests := []func(args){
187                 // Perform most tests with passwd for simplicity
188                 fetchPasswdCacheFileDoesNotExist,
189                 fetchPasswd404,
190                 fetchPasswdEmpty,
191                 fetchPasswdInvalid,
192                 fetchPasswdLimits,
193                 fetchPasswd,
194                 // Tests for plain
195                 fetchPlainEmpty,
196                 fetchPlain,
197                 // Special tests
198                 fetchNoConfig,
199         }
200
201         cleanup := []string{
202                 configPath,
203                 statePath,
204                 passwdPath,
205                 plainPath,
206                 groupPath,
207         }
208
209         for _, f := range tests {
210                 // NOTE: This is not guaranteed to work according to reflect's
211                 // documentation but seems to work reliable for normal
212                 // functions.
213                 fn := runtime.FuncForPC(reflect.ValueOf(f).Pointer())
214                 name := fn.Name()
215                 name = name[strings.LastIndex(name, ".")+1:]
216
217                 t.Run(name, func(t *testing.T) {
218                         // Preparation & cleanup
219                         for _, p := range cleanup {
220                                 err := os.Remove(p)
221                                 if err != nil && !os.IsNotExist(err) {
222                                         t.Fatal(err)
223                                 }
224                                 // Remove the file at the end of this test
225                                 // run, if it was created
226                                 defer os.Remove(p)
227                         }
228
229                         var handler func(http.ResponseWriter, *http.Request)
230                         ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
231                                 handler(w, r)
232                         }))
233                         defer ts.Close()
234
235                         f(args{
236                                 t:       t,
237                                 url:     ts.URL,
238                                 handler: &handler,
239                         })
240                 })
241         }
242 }
243
244 func fetchPasswdCacheFileDoesNotExist(a args) {
245         t := a.t
246         mustWritePasswdConfig(t, a.url)
247
248         err := mainFetch(configPath)
249         mustBeErrorWithSubstring(t, err,
250                 "file.path \""+passwdPath+"\" must exist")
251
252         mustNotExist(t, statePath, passwdPath, plainPath, groupPath)
253 }
254
255 func fetchPasswd404(a args) {
256         t := a.t
257         mustWritePasswdConfig(t, a.url)
258         mustCreate(t, passwdPath)
259
260         *a.handler = func(w http.ResponseWriter, r *http.Request) {
261                 // 404
262                 w.WriteHeader(http.StatusNotFound)
263         }
264
265         err := mainFetch(configPath)
266         mustBeErrorWithSubstring(t, err,
267                 "status code 404")
268
269         mustNotExist(t, statePath, plainPath, groupPath)
270         mustBeOld(a.t, passwdPath)
271 }
272
273 func fetchPasswdEmpty(a args) {
274         t := a.t
275         mustWritePasswdConfig(t, a.url)
276         mustCreate(t, passwdPath)
277
278         *a.handler = func(w http.ResponseWriter, r *http.Request) {
279                 // Empty response
280         }
281
282         err := mainFetch(configPath)
283         mustBeErrorWithSubstring(t, err,
284                 "refusing to use empty passwd file")
285
286         mustNotExist(t, statePath, plainPath, groupPath)
287         mustBeOld(t, passwdPath)
288 }
289
290 func fetchPasswdInvalid(a args) {
291         t := a.t
292         mustWritePasswdConfig(t, a.url)
293         mustCreate(t, passwdPath)
294
295         *a.handler = func(w http.ResponseWriter, r *http.Request) {
296                 if r.URL.Path != "/passwd" {
297                         return
298                 }
299
300                 fmt.Fprintln(w, "root:x:invalid:0:root:/root:/bin/bash")
301         }
302
303         err := mainFetch(configPath)
304         mustBeErrorWithSubstring(t, err,
305                 "invalid uid in line")
306
307         mustNotExist(t, statePath, plainPath, groupPath)
308         mustBeOld(t, passwdPath)
309 }
310
311 func fetchPasswdLimits(a args) {
312         t := a.t
313         mustWritePasswdConfig(t, a.url)
314         mustCreate(t, passwdPath)
315
316         *a.handler = func(w http.ResponseWriter, r *http.Request) {
317                 if r.URL.Path != "/passwd" {
318                         return
319                 }
320
321                 fmt.Fprint(w, "root:x:0:0:root:/root:/bin/bash")
322                 for i := 0; i < 65536; i++ {
323                         fmt.Fprint(w, "x")
324                 }
325                 fmt.Fprint(w, "\n")
326         }
327
328         err := mainFetch(configPath)
329         mustBeErrorWithSubstring(t, err,
330                 "passwd too large to serialize")
331
332         mustNotExist(t, statePath, plainPath, groupPath)
333         mustBeOld(t, passwdPath)
334 }
335
336 func fetchPasswd(a args) {
337         t := a.t
338         mustWritePasswdConfig(t, a.url)
339         mustCreate(t, passwdPath)
340         mustHaveHash(t, passwdPath, "da39a3ee5e6b4b0d3255bfef95601890afd80709")
341
342         t.Log("First fetch, write files")
343
344         *a.handler = func(w http.ResponseWriter, r *http.Request) {
345                 if r.URL.Path != "/passwd" {
346                         return
347                 }
348
349                 // No "Last-Modified" header
350                 fmt.Fprintln(w, "root:x:0:0:root:/root:/bin/bash")
351                 fmt.Fprintln(w, "daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin")
352         }
353
354         err := mainFetch(configPath)
355         if err != nil {
356                 t.Error(err)
357         }
358
359         mustNotExist(t, plainPath, groupPath)
360         mustBeNew(t, passwdPath, statePath)
361         // The actual content of passwdPath is verified by the NSS tests
362         mustHaveHash(t, passwdPath, "bbb7db67469b111200400e2470346d5515d64c23")
363
364         t.Log("Fetch again, no support for Last-Modified")
365
366         mustMakeOld(t, passwdPath, statePath)
367
368         err = mainFetch(configPath)
369         if err != nil {
370                 t.Error(err)
371         }
372
373         mustNotExist(t, plainPath, groupPath)
374         mustBeNew(t, passwdPath, statePath)
375         mustHaveHash(t, passwdPath, "bbb7db67469b111200400e2470346d5515d64c23")
376
377         t.Log("Fetch again, support for Last-Modified, but not retrieved yet")
378
379         mustMakeOld(t, passwdPath, statePath)
380
381         lastChange := time.Now()
382         *a.handler = func(w http.ResponseWriter, r *http.Request) {
383                 if r.URL.Path != "/passwd" {
384                         return
385                 }
386
387                 modified := r.Header.Get("If-Modified-Since")
388                 if modified != "" {
389                         x, err := http.ParseTime(modified)
390                         if err != nil {
391                                 t.Fatalf("invalid If-Modified-Since %v",
392                                         modified)
393                         }
394                         if !x.Before(lastChange) {
395                                 w.WriteHeader(http.StatusNotModified)
396                                 return
397                         }
398                 }
399
400                 w.Header().Add("Last-Modified",
401                         lastChange.Format(http.TimeFormat))
402                 fmt.Fprintln(w, "root:x:0:0:root:/root:/bin/bash")
403                 fmt.Fprintln(w, "daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin")
404         }
405
406         err = mainFetch(configPath)
407         if err != nil {
408                 t.Error(err)
409         }
410
411         mustNotExist(t, plainPath, groupPath)
412         mustBeNew(t, passwdPath, statePath)
413         mustHaveHash(t, passwdPath, "bbb7db67469b111200400e2470346d5515d64c23")
414
415         t.Log("Fetch again, support for Last-Modified")
416
417         mustMakeOld(t, passwdPath, statePath)
418
419         err = mainFetch(configPath)
420         if err != nil {
421                 t.Error(err)
422         }
423
424         mustNotExist(t, plainPath, groupPath)
425         mustBeOld(t, passwdPath)
426         mustBeNew(t, statePath)
427         mustHaveHash(t, passwdPath, "bbb7db67469b111200400e2470346d5515d64c23")
428
429         t.Log("Corrupt local passwd cache, fetched again")
430
431         os.Chmod(passwdPath, 0644) // make writable again
432         mustCreate(t, passwdPath)
433         mustMakeOld(t, passwdPath, statePath)
434
435         err = mainFetch(configPath)
436         if err != nil {
437                 t.Error(err)
438         }
439
440         mustNotExist(t, plainPath, groupPath)
441         mustBeNew(t, passwdPath, statePath)
442         mustHaveHash(t, passwdPath, "bbb7db67469b111200400e2470346d5515d64c23")
443 }
444
445 func fetchPlainEmpty(a args) {
446         t := a.t
447         mustWriteConfig(t, fmt.Sprintf(`
448 statepath = "%[1]s"
449
450 [[file]]
451 type = "plain"
452 url = "%[2]s/plain"
453 path = "%[3]s"
454 `, statePath, a.url, plainPath))
455         mustCreate(t, plainPath)
456
457         *a.handler = func(w http.ResponseWriter, r *http.Request) {
458                 // Empty response
459         }
460
461         err := mainFetch(configPath)
462         mustBeErrorWithSubstring(t, err,
463                 "refusing to use empty response")
464
465         mustNotExist(t, statePath, passwdPath, groupPath)
466         mustBeOld(t, plainPath)
467 }
468
469 func fetchPlain(a args) {
470         t := a.t
471         mustWriteConfig(t, fmt.Sprintf(`
472 statepath = "%[1]s"
473
474 [[file]]
475 type = "plain"
476 url = "%[2]s/plain"
477 path = "%[3]s"
478 `, statePath, a.url, plainPath))
479         mustCreate(t, plainPath)
480         mustHaveHash(t, plainPath, "da39a3ee5e6b4b0d3255bfef95601890afd80709")
481
482         *a.handler = func(w http.ResponseWriter, r *http.Request) {
483                 if r.URL.Path != "/plain" {
484                         return
485                 }
486
487                 fmt.Fprintln(w, "some file")
488         }
489
490         err := mainFetch(configPath)
491         if err != nil {
492                 t.Error(err)
493         }
494
495         mustNotExist(t, passwdPath, groupPath)
496         mustBeNew(t, plainPath, statePath)
497         mustHaveHash(t, plainPath, "0e08b5e8c10abc3e455b75286ba4a1fbd56e18a5")
498
499         // Remaining functionality already tested in fetchPasswd()
500 }
501
502 func fetchNoConfig(a args) {
503         t := a.t
504
505         err := mainFetch(configPath)
506         mustBeErrorWithSubstring(t, err,
507                 configPath+": no such file or directory")
508
509         mustNotExist(t, configPath, statePath, passwdPath, plainPath, groupPath)
510 }