]> ruderich.org/simon Gitweb - nsscash/nsscash.git/blob - main_test.go
d28c822ac3bbb8ef65e44c221ed8fb054b691d85
[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                 // Special tests
195                 fetchNoConfig,
196         }
197
198         cleanup := []string{
199                 configPath,
200                 statePath,
201                 passwdPath,
202                 plainPath,
203                 groupPath,
204         }
205
206         for _, f := range tests {
207                 // NOTE: This is not guaranteed to work according to reflect's
208                 // documentation but seems to work reliable for normal
209                 // functions.
210                 fn := runtime.FuncForPC(reflect.ValueOf(f).Pointer())
211                 name := fn.Name()
212                 name = name[strings.LastIndex(name, ".")+1:]
213
214                 t.Run(name, func(t *testing.T) {
215                         // Preparation & cleanup
216                         for _, p := range cleanup {
217                                 err := os.Remove(p)
218                                 if err != nil && !os.IsNotExist(err) {
219                                         t.Fatal(err)
220                                 }
221                                 // Remove the file at the end of this test
222                                 // run, if it was created
223                                 defer os.Remove(p)
224                         }
225
226                         var handler func(http.ResponseWriter, *http.Request)
227                         ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
228                                 handler(w, r)
229                         }))
230                         defer ts.Close()
231
232                         f(args{
233                                 t:       t,
234                                 url:     ts.URL,
235                                 handler: &handler,
236                         })
237                 })
238         }
239 }
240
241 func fetchPasswdCacheFileDoesNotExist(a args) {
242         t := a.t
243         mustWritePasswdConfig(t, a.url)
244
245         err := mainFetch(configPath)
246         mustBeErrorWithSubstring(t, err,
247                 "file.path \""+passwdPath+"\" must exist")
248
249         mustNotExist(t, statePath, passwdPath, plainPath, groupPath)
250 }
251
252 func fetchPasswd404(a args) {
253         t := a.t
254         mustWritePasswdConfig(t, a.url)
255         mustCreate(t, passwdPath)
256
257         *a.handler = func(w http.ResponseWriter, r *http.Request) {
258                 // 404
259                 w.WriteHeader(http.StatusNotFound)
260         }
261
262         err := mainFetch(configPath)
263         mustBeErrorWithSubstring(t, err,
264                 "status code 404")
265
266         mustNotExist(t, statePath, plainPath, groupPath)
267         mustBeOld(a.t, passwdPath)
268 }
269
270 func fetchPasswdEmpty(a args) {
271         t := a.t
272         mustWritePasswdConfig(t, a.url)
273         mustCreate(t, passwdPath)
274
275         *a.handler = func(w http.ResponseWriter, r *http.Request) {
276                 // Empty response
277         }
278
279         err := mainFetch(configPath)
280         mustBeErrorWithSubstring(t, err,
281                 "refusing to use empty passwd file")
282
283         mustNotExist(t, statePath, plainPath, groupPath)
284         mustBeOld(t, passwdPath)
285 }
286
287 func fetchPasswdInvalid(a args) {
288         t := a.t
289         mustWritePasswdConfig(t, a.url)
290         mustCreate(t, passwdPath)
291
292         *a.handler = func(w http.ResponseWriter, r *http.Request) {
293                 if r.URL.Path != "/passwd" {
294                         return
295                 }
296
297                 fmt.Fprintln(w, "root:x:invalid:0:root:/root:/bin/bash")
298         }
299
300         err := mainFetch(configPath)
301         mustBeErrorWithSubstring(t, err,
302                 "invalid uid in line")
303
304         mustNotExist(t, statePath, plainPath, groupPath)
305         mustBeOld(t, passwdPath)
306 }
307
308 func fetchPasswdLimits(a args) {
309         t := a.t
310         mustWritePasswdConfig(t, a.url)
311         mustCreate(t, passwdPath)
312
313         *a.handler = func(w http.ResponseWriter, r *http.Request) {
314                 if r.URL.Path != "/passwd" {
315                         return
316                 }
317
318                 fmt.Fprint(w, "root:x:0:0:root:/root:/bin/bash")
319                 for i := 0; i < 65536; i++ {
320                         fmt.Fprint(w, "x")
321                 }
322                 fmt.Fprint(w, "\n")
323         }
324
325         err := mainFetch(configPath)
326         mustBeErrorWithSubstring(t, err,
327                 "passwd too large to serialize")
328
329         mustNotExist(t, statePath, plainPath, groupPath)
330         mustBeOld(t, passwdPath)
331 }
332
333 func fetchPasswd(a args) {
334         t := a.t
335         mustWritePasswdConfig(t, a.url)
336         mustCreate(t, passwdPath)
337         mustHaveHash(t, passwdPath, "da39a3ee5e6b4b0d3255bfef95601890afd80709")
338
339         t.Log("First fetch, write files")
340
341         *a.handler = func(w http.ResponseWriter, r *http.Request) {
342                 if r.URL.Path != "/passwd" {
343                         return
344                 }
345
346                 // No "Last-Modified" header
347                 fmt.Fprintln(w, "root:x:0:0:root:/root:/bin/bash")
348                 fmt.Fprintln(w, "daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin")
349         }
350
351         err := mainFetch(configPath)
352         if err != nil {
353                 t.Error(err)
354         }
355
356         mustNotExist(t, plainPath, groupPath)
357         mustBeNew(t, passwdPath, statePath)
358         // The actual content of passwdPath is verified by the NSS tests
359         mustHaveHash(t, passwdPath, "bbb7db67469b111200400e2470346d5515d64c23")
360
361         t.Log("Fetch again, no support for Last-Modified")
362
363         mustMakeOld(t, passwdPath, statePath)
364
365         err = mainFetch(configPath)
366         if err != nil {
367                 t.Error(err)
368         }
369
370         mustNotExist(t, plainPath, groupPath)
371         mustBeNew(t, passwdPath, statePath)
372         mustHaveHash(t, passwdPath, "bbb7db67469b111200400e2470346d5515d64c23")
373
374         t.Log("Fetch again, support for Last-Modified, but not retrieved yet")
375
376         mustMakeOld(t, passwdPath, statePath)
377
378         lastChange := time.Now()
379         *a.handler = func(w http.ResponseWriter, r *http.Request) {
380                 if r.URL.Path != "/passwd" {
381                         return
382                 }
383
384                 modified := r.Header.Get("If-Modified-Since")
385                 if modified != "" {
386                         x, err := http.ParseTime(modified)
387                         if err != nil {
388                                 t.Fatalf("invalid If-Modified-Since %v",
389                                         modified)
390                         }
391                         if !x.Before(lastChange) {
392                                 w.WriteHeader(http.StatusNotModified)
393                                 return
394                         }
395                 }
396
397                 w.Header().Add("Last-Modified",
398                         lastChange.Format(http.TimeFormat))
399                 fmt.Fprintln(w, "root:x:0:0:root:/root:/bin/bash")
400                 fmt.Fprintln(w, "daemon:x:1:1:daemon:/usr/sbin:/usr/sbin/nologin")
401         }
402
403         err = mainFetch(configPath)
404         if err != nil {
405                 t.Error(err)
406         }
407
408         mustNotExist(t, plainPath, groupPath)
409         mustBeNew(t, passwdPath, statePath)
410         mustHaveHash(t, passwdPath, "bbb7db67469b111200400e2470346d5515d64c23")
411
412         t.Log("Fetch again, support for Last-Modified")
413
414         mustMakeOld(t, passwdPath, statePath)
415
416         err = mainFetch(configPath)
417         if err != nil {
418                 t.Error(err)
419         }
420
421         mustNotExist(t, plainPath, groupPath)
422         mustBeOld(t, passwdPath)
423         mustBeNew(t, statePath)
424         mustHaveHash(t, passwdPath, "bbb7db67469b111200400e2470346d5515d64c23")
425
426         t.Log("Corrupt local passwd cache, fetched again")
427
428         os.Chmod(passwdPath, 0644) // make writable again
429         mustCreate(t, passwdPath)
430         mustMakeOld(t, passwdPath, statePath)
431
432         err = mainFetch(configPath)
433         if err != nil {
434                 t.Error(err)
435         }
436
437         mustNotExist(t, plainPath, groupPath)
438         mustBeNew(t, passwdPath, statePath)
439         mustHaveHash(t, passwdPath, "bbb7db67469b111200400e2470346d5515d64c23")
440 }
441
442 func fetchNoConfig(a args) {
443         t := a.t
444
445         err := mainFetch(configPath)
446         mustBeErrorWithSubstring(t, err,
447                 configPath+": no such file or directory")
448
449         mustNotExist(t, configPath, statePath, passwdPath, plainPath, groupPath)
450 }