summaryrefslogtreecommitdiffstats
path: root/test/network/handler/fileserver.rb
blob: 1046617ec607d8f356f1f2af805154d99b68a16d (plain)
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
#!/usr/bin/env ruby

require File.dirname(__FILE__) + '/../../lib/puppettest'

require 'puppettest'
require 'puppet/network/handler/fileserver'

class TestFileServer < Test::Unit::TestCase
	include PuppetTest

    def mkmount(path = nil)
        mount = nil
        name = "yaytest"
        base = path || tempfile()
        unless FileTest.exists?(base)
            Dir.mkdir(base)
        end
        # Create a test file
        File.open(File.join(base, "file"), "w") { |f| f.puts "bazoo" }
        assert_nothing_raised {
            mount = Puppet::Network::Handler.fileserver::Mount.new(name, base)
        }

        return mount
    end
    # make a simple file source
    def mktestdir
        testdir = File.join(tmpdir(), "remotefilecopytesting")
        @@tmpfiles << testdir

        # create a tmpfile
        pattern = "tmpfile"
        tmpfile = File.join(testdir, pattern)
        assert_nothing_raised {
            Dir.mkdir(testdir)
            File.open(tmpfile, "w") { |f|
                3.times { f.puts rand(100) }
            }
        }

        return [testdir, %r{#{pattern}}, tmpfile]
    end

    # make a bunch of random test files
    def mktestfiles(testdir)
        @@tmpfiles << testdir
        assert_nothing_raised {
            files = %w{a b c d e}.collect { |l|
                name = File.join(testdir, "file%s" % l)
                File.open(name, "w") { |f|
                    f.puts rand(100)
                }
                
                name
            }

            return files
        }
    end

    def assert_describe(base, file, server)
        file = File.basename(file)
        assert_nothing_raised {
            desc = server.describe(base + file)
            assert(desc, "Got no description for %s" % file)
            assert(desc != "", "Got no description for %s" % file)
            assert_match(/^\d+/, desc, "Got invalid description %s" % desc)
        }
    end

    # test for invalid names
    def test_namefailures
        server = nil
        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => false
            )
        }

        [" ", "=" "+", "&", "#", "*"].each do |char|
            assert_raise(Puppet::Network::Handler::FileServerError, "'%s' did not throw a failure in fileserver module names" % char) {
                server.mount("/tmp", "invalid%sname" % char)
            }
        end
    end

    # verify that listing the root behaves as expected
    def test_listroot
        server = nil
        testdir, pattern, tmpfile = mktestdir()

        file = nil
        checks = Puppet::Network::Handler.fileserver::CHECKPARAMS

        # and make our fileserver
        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => false
            )
        }

        # mount the testdir
        assert_nothing_raised {
            server.mount(testdir, "test")
        }

        # and verify different iterations of 'root' return the same value
        list = nil
        assert_nothing_raised {
            list = server.list("/test/", :manage, true, false)
        }

        assert(list =~ pattern)

        assert_nothing_raised {
            list = server.list("/test", :manage, true, false)
        }
        assert(list =~ pattern)

    end

    # test listing individual files
    def test_getfilelist
        server = nil
        testdir, pattern, tmpfile = mktestdir()

        file = nil

        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => false
            )
        }

        assert_nothing_raised {
            server.mount(testdir, "test")
        }

        # get our listing
        list = nil
        sfile = "/test/tmpfile"
        assert_nothing_raised {
            list = server.list(sfile, :manage, true, false)
        }

        output = "/\tfile"

        # verify it got listed as a file
        assert_equal(output, list)

        # verify we got all fields
        assert(list !~ /\t\t/)

        # verify that we didn't get the directory itself
        list.split("\n").each { |line|
            assert(line !~ %r{remotefile})
        }

        # and then verify that the contents match
        contents = File.read(tmpfile)

        ret = nil
        assert_nothing_raised {
            ret = server.retrieve(sfile)
        }

        assert_equal(contents, ret)
    end

    # check that the fileserver is seeing newly created files
    def test_seenewfiles
        server = nil
        testdir, pattern, tmpfile = mktestdir()


        newfile = File.join(testdir, "newfile")

        # go through the whole schtick again...
        file = nil
        checks = Puppet::Network::Handler.fileserver::CHECKPARAMS

        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => false
            )
        }

        assert_nothing_raised {
            server.mount(testdir, "test")
        }

        list = nil
        sfile = "/test/"
        assert_nothing_raised {
            list = server.list(sfile, :manage, true, false)
        }

        # create the new file
        File.open(newfile, "w") { |f|
            3.times { f.puts rand(100) }
        }

        newlist = nil
        assert_nothing_raised {
            newlist = server.list(sfile, :manage, true, false)
        }

        # verify the list has changed
        assert(list != newlist)

        # and verify that we are specifically seeing the new file
        assert(newlist =~ /newfile/)
    end

    # verify we can mount /, which is what local file servers will
    # normally do
    def test_mountroot
        server = nil
        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => false
            )
        }

        assert_nothing_raised {
            server.mount("/", "root")
        }

        testdir, pattern, tmpfile = mktestdir()

        list = nil
        assert_nothing_raised {
            list = server.list("/root/" + testdir, :manage, true, false)
        }

        assert(list =~ pattern)
        assert_nothing_raised {
            list = server.list("/root" + testdir, :manage, true, false)
        }

        assert(list =~ pattern)
    end

    # verify that we're correctly recursing the right number of levels
    def test_recursionlevels
        server = nil
        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => false
            )
        }

        # make our deep recursion
        basedir = File.join(tmpdir(), "recurseremotetesting")
        testdir = "%s/with/some/sub/directories/for/the/purposes/of/testing" % basedir
        oldfile = File.join(testdir, "oldfile")
        assert_nothing_raised {
            system("mkdir -p %s" % testdir)
            File.open(oldfile, "w") { |f|
                3.times { f.puts rand(100) }
            }
            @@tmpfiles << basedir
        }

        assert_nothing_raised {
            server.mount(basedir, "test")
        }

        # get our list
        list = nil
        assert_nothing_raised {
            list = server.list("/test/with", :manage, false, false)
        }

        # make sure we only got one line, since we're not recursing
        assert(list !~ /\n/)

        # for each level of recursion, make sure we get the right list
        [0, 1, 2].each { |num|
            assert_nothing_raised {
                list = server.list("/test/with", :manage, num, false)
            }

            count = 0
            while list =~ /\n/
                list.sub!(/\n/, '')
                count += 1
            end
            assert_equal(num, count)
        }
    end

    # verify that we're not seeing the dir we ask for; i.e., that our
    # list is relative to that dir, not it's parent dir
    def test_listedpath
        server = nil
        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => false
            )
        }


        # create a deep dir
        basedir = tempfile()
        testdir = "%s/with/some/sub/directories/for/testing" % basedir
        oldfile = File.join(testdir, "oldfile")
        assert_nothing_raised {
            system("mkdir -p %s" % testdir)
            File.open(oldfile, "w") { |f|
                3.times { f.puts rand(100) }
            }
            @@tmpfiles << basedir
        }

        # mounty mounty
        assert_nothing_raised {
            server.mount(basedir, "localhost")
        }

        list = nil
        # and then check a few dirs
        assert_nothing_raised {
            list = server.list("/localhost/with", :manage, false, false)
        }

        assert(list !~ /with/)

        assert_nothing_raised {
            list = server.list("/localhost/with/some/sub", :manage, true, false)
        }

        assert(list !~ /sub/)
    end

    # test many dirs, not necessarily very deep
    def test_widelists
        server = nil
        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => false
            )
        }

        basedir = tempfile()
        dirs = %w{a set of directories}
        assert_nothing_raised {
            Dir.mkdir(basedir)
            dirs.each { |dir|
                Dir.mkdir(File.join(basedir, dir))
            }
            @@tmpfiles << basedir
        }

        assert_nothing_raised {
            server.mount(basedir, "localhost")
        }

        list = nil
        assert_nothing_raised {
            list = server.list("/localhost/", :manage, 1, false)
        }
        assert_instance_of(String, list, "Server returned %s instead of string")
        list = list.split("\n")

        assert_equal(dirs.length + 1, list.length)
    end

    # verify that 'describe' works as advertised
    def test_describe
        server = nil
        testdir = tstdir()
        files = mktestfiles(testdir)

        file = nil
        checks = Puppet::Network::Handler.fileserver::CHECKPARAMS

        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => false
            )
        }

        assert_nothing_raised {
            server.mount(testdir, "test")
        }

        # get our list
        list = nil
        sfile = "/test/"
        assert_nothing_raised {
            list = server.list(sfile, :manage, true, false)
        }

        # and describe each file in the list
        assert_nothing_raised {
            list.split("\n").each { |line|
                file, type = line.split("\t")

                desc = server.describe(sfile + file)
            }
        }

        # and then make sure we can describe everything that we know is there
        files.each { |file|
            assert_describe(sfile, file, server)
        }

        # And then describe some files that we know aren't there
        retval = nil
        assert_nothing_raised("Describing non-existent files raised an error") {
            retval = server.describe(sfile + "noexisties")
        }

        assert_equal("", retval, "Description of non-existent files returned a value")

        # Now try to describe some sources that don't even exist
        retval = nil
        assert_raise(Puppet::Network::Handler::FileServerError,
            "Describing non-existent mount did not raise an error") {
            retval = server.describe("/notmounted/" + "noexisties")
        }

        assert_nil(retval, "Description of non-existent mounts returned a value")
    end

    def test_describe_does_not_fail_when_mount_does_not_find_file
        server = Puppet::Network::Handler.fileserver.new(:Local => true, :Config => false)

        assert_nothing_raised("Failed when describing missing plugins") do
            server.describe "/plugins"
        end
    end

    # test that our config file is parsing and working as planned
    def test_configfile
        server = nil
        basedir = File.join(tmpdir, "fileserverconfigfiletesting")
        @@tmpfiles << basedir

        # make some dirs for mounting
        Dir.mkdir(basedir)
        mounts = {}
        %w{thing thus the-se those}.each { |dir|
            path = File.join(basedir, dir)
            Dir.mkdir(path)
            mounts[dir] = mktestfiles(path)

        }

        # create an example file with each of them
        conffile = tempfile
        @@tmpfiles << conffile

        File.open(conffile, "w") { |f|
            f.print "# a test config file
 
[thing]
    path #{basedir}/thing
    allow 192.168.0.*

[thus]
    path #{basedir}/thus
    allow *.madstop.com, *.kanies.com
    deny *.sub.madstop.com

[the-se]
    path #{basedir}/the-se

[those]
    path #{basedir}/those

"
        }
        

        # create a server with the file
        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => false,
                :Config => conffile
            )
        }

        list = nil
        # run through once with no host/ip info, to verify everything is working
        mounts.each { |mount, files|
            mount = "/#{mount}/"
            assert_nothing_raised {
                list = server.list(mount, :manage, true, false)
            }

            assert_nothing_raised {
                list.split("\n").each { |line|
                    file, type = line.split("\t")

                    desc = server.describe(mount + file)
                }
            }

            files.each { |f|
                assert_describe(mount, f, server)
            }
        }

        # now let's check that things are being correctly forbidden
        # this is just a map of names and expected results
        {
            "thing" => {
                :deny => [
                    ["hostname.com", "192.168.1.0"],
                    ["hostname.com", "192.158.0.0"]
                ],
                :allow => [
                    ["hostname.com", "192.168.0.0"],
                    ["hostname.com", "192.168.0.245"],
                ]
            },
            "thus" => {
                :deny => [
                    ["hostname.com", "192.168.1.0"],
                    ["name.sub.madstop.com", "192.158.0.0"]
                ],
                :allow => [
                    ["luke.kanies.com", "192.168.0.0"],
                    ["luke.madstop.com", "192.168.0.245"],
                ]
            }
        }.each { |mount, hash|
            mount = "/#{mount}/"

            # run through the map
            hash.each { |type, ary|
                ary.each { |sub|
                    host, ip = sub

                    case type
                    when :deny:
                        assert_raise(Puppet::AuthorizationError,
                            "Host %s, ip %s, allowed %s" %
                            [host, ip, mount]) {
                                list = server.list(mount, :manage, true, false, host, ip)
                        }
                    when :allow:
                        assert_nothing_raised("Host %s, ip %s, denied %s" %
                            [host, ip, mount]) {
                                list = server.list(mount, :manage, true, false, host, ip)
                        }
                    end
                }
            }
        }

    end

    # Test that we smoothly handle invalid config files
    def test_configfailures
        # create an example file with each of them
        conffile = tempfile()

        invalidmounts = {
            "noexist" => "[noexist]
    path /this/path/does/not/exist
    allow 192.168.0.*
"
}

        invalidconfigs = [
"[not valid]
    path /this/path/does/not/exist
    allow 192.168.0.*
",
"[valid]
    invalidstatement
    path /etc
    allow 192.168.0.*
",
"[valid]
    allow 192.168.0.*
"
]

        invalidmounts.each { |mount, text|
            File.open(conffile, "w") { |f|
                f.print text
            }
            

            # create a server with the file
            server = nil
            assert_nothing_raised {
                server = Puppet::Network::Handler.fileserver.new(
                    :Local => true,
                    :Config => conffile
                )
            }

            assert_raise(Puppet::Network::Handler::FileServerError,
                "Invalid mount was mounted") {
                    server.list(mount, :manage)
            }
        }

        invalidconfigs.each_with_index { |text, i|
            File.open(conffile, "w") { |f|
                f.print text
            }
            

            # create a server with the file
            server = nil
            assert_raise(Puppet::Network::Handler::FileServerError,
                "Invalid config %s did not raise error" % i) {
                server = Puppet::Network::Handler.fileserver.new(
                    :Local => true,
                    :Config => conffile
                )
            }
        }
    end

    # verify we reread the config file when it changes
    def test_filereread
        server = nil

        conffile = tempfile()
        dir = tstdir()

        files = mktestfiles(dir)
        File.open(conffile, "w") { |f|
            f.print "# a test config file
 
[thing]
    path #{dir}
    allow test1.domain.com
"
        }
        
        # Reset the timeout, so we reload faster
        Puppet[:filetimeout] = 0.5

        # start our server with a fast timeout
        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => false,
                :Config => conffile
            )
        }

        list = nil
        assert_nothing_raised {
            list = server.list("/thing/", :manage, false, false,
                "test1.domain.com", "127.0.0.1")
        }
        assert(list != "", "List returned nothing in rereard test")

        assert_raise(Puppet::AuthorizationError, "List allowed invalid host") {
            list = server.list("/thing/", :manage, false, false,
                "test2.domain.com", "127.0.0.1")
        }

        sleep 1
        File.open(conffile, "w") { |f|
            f.print "# a test config file
 
[thing]
    path #{dir}
    allow test2.domain.com
"
        }
        
        assert_raise(Puppet::AuthorizationError, "List allowed invalid host") {
            list = server.list("/thing/", :manage, false, false,
                "test1.domain.com", "127.0.0.1")
        }

        assert_nothing_raised {
            list = server.list("/thing/", :manage, false, false,
                "test2.domain.com", "127.0.0.1")
        }

        assert(list != "", "List returned nothing in rereard test")

        list = nil
    end

    # Verify that we get converted to the right kind of string
    def test_mountstring
        mount = nil
        name = "yaytest"
        path = tmpdir()
        assert_nothing_raised {
            mount = Puppet::Network::Handler.fileserver::Mount.new(name, path)
        }

        assert_equal("mount[#{name}]", mount.to_s)
    end

    def test_servinglinks
        # Disable the checking, so changes propagate immediately.
        Puppet[:filetimeout] = -5
        server = nil
        source = tempfile()
        file = File.join(source, "file")
        link = File.join(source, "link")
        Dir.mkdir(source)
        File.open(file, "w") { |f| f.puts "yay" }
        File.symlink(file, link)
        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => false
            )
        }

        assert_nothing_raised {
            server.mount(source, "mount")
        }

        # First describe the link when following
        results = {}
        assert_nothing_raised {
            server.describe("/mount/link", :follow).split("\t").zip(
                Puppet::Network::Handler.fileserver::CHECKPARAMS
            ).each { |v,p| results[p] = v }
        }

        assert_equal("file", results[:type])

        # Then not
        results = {}
        assert_nothing_raised {
            server.describe("/mount/link", :manage).split("\t").zip(
                Puppet::Network::Handler.fileserver::CHECKPARAMS
            ).each { |v,p| results[p] = v }
        }

        assert_equal("link", results[:type])

        results.each { |p,v|
            assert(v, "%s has no value" % p)
            assert(v != "", "%s has no value" % p)
        }
    end

    # Test that substitution patterns in the path are exapanded
    # properly.  Disabled, because it was testing too much of the process
    # and in a non-portable way.  This is a thorough enough test that it should
    # be kept, but it should be done in a way that is clearly portable (e.g.,
    # no md5 sums of file paths).
    def test_host_specific
        client1 = "client1.example.com"
        client2 = "client2.example.com"
        ip = "127.0.0.1"

        # Setup a directory hierarchy for the tests
        fsdir = File.join(tmpdir(), "host-specific")
        @@tmpfiles << fsdir
        hostdir = File.join(fsdir, "host")
        fqdndir = File.join(fsdir, "fqdn")
        client1_hostdir = File.join(hostdir, "client1")
        client2_fqdndir = File.join(fqdndir, client2)
        contents = {
            client1_hostdir => "client1\n",
            client2_fqdndir => client2 + "\n"
        }
        [fsdir, hostdir, fqdndir, 
         client1_hostdir, client2_fqdndir].each { |d|  Dir.mkdir(d) }
        
        [client1_hostdir, client2_fqdndir].each do |d|
            File.open(File.join(d, "file.txt"), "w") do |f| 
                f.print contents[d] 
            end
        end
        conffile = tempfile()
        File.open(conffile, "w") do |f|
            f.print("
[host]
path #{hostdir}/%h
allow *
[fqdn]
path #{fqdndir}/%H
allow *
")
        end

        server = nil
        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => conffile
            )
        }

        # check that list returns the correct thing for the two clients
        list = nil
        sfile = "/host/file.txt"
        assert_nothing_raised {
            list = server.list(sfile, :manage, true, false, client1, ip)
        }
        assert_equal("/\tfile", list)
        assert_nothing_raised {
            list = server.list(sfile, :manage, true, false, client2, ip)
        }
        assert_equal("", list)

        sfile = "/fqdn/file.txt"
        assert_nothing_raised {
            list = server.list(sfile, :manage, true, false, client1, ip)
        }
        assert_equal("", list)
        assert_nothing_raised {
            list = server.list(sfile, :manage, true, false, client2, ip)
        }
        assert_equal("/\tfile", list)

        # check describe
        sfile = "/host/file.txt"
        assert_nothing_raised {
            list = server.describe(sfile, :manage, client1, ip).split("\t")
        }
        assert_equal(5, list.size)
        assert_equal("file", list[1])
        md5 = Digest::MD5.hexdigest(contents[client1_hostdir])
        assert_equal("{md5}#{md5}", list[4])

        assert_nothing_raised {
            list = server.describe(sfile, :manage, client2, ip).split("\t")
        }
        assert_equal([], list)

        sfile = "/fqdn/file.txt"
        assert_nothing_raised {
            list = server.describe(sfile, :manage, client1, ip).split("\t")
        }
        assert_equal([], list)

        assert_nothing_raised {
            list = server.describe(sfile, :manage, client2, ip).split("\t")
        }
        assert_equal(5, list.size)
        assert_equal("file", list[1])
        md5 = Digest::MD5.hexdigest(contents[client2_fqdndir])
        assert_equal("{md5}#{md5}", list[4])

        # Check retrieve
        sfile = "/host/file.txt"
        assert_nothing_raised {
            list = server.retrieve(sfile, :manage, client1, ip).chomp
        }
        assert_equal(contents[client1_hostdir].chomp, list)

        assert_nothing_raised {
            list = server.retrieve(sfile, :manage, client2, ip).chomp
        }
        assert_equal("", list)

        sfile = "/fqdn/file.txt"
        assert_nothing_raised {
            list = server.retrieve(sfile, :manage, client1, ip).chomp
        }
        assert_equal("", list)

        assert_nothing_raised {
            list = server.retrieve(sfile, :manage, client2, ip).chomp
        }
        assert_equal(contents[client2_fqdndir].chomp, list)
    end

    # Make sure the 'subdir' method in Mount works.
    def test_mount_subdir
        mount = nil
        base = tempfile()
        Dir.mkdir(base)
        subdir = File.join(base, "subdir")
        Dir.mkdir(subdir)
        [base, subdir].each do |d|
            File.open(File.join(d, "file"), "w") { |f| f.puts "bazoo" }
        end
        mount = mkmount(base)

        assert_equal(base, mount.subdir(), "Did not default to base path")
        assert_equal(subdir, mount.subdir("subdir"), "Did not default to base path")
    end

    # Make sure mounts get correctly marked expandable or not, depending on
    # the path.
    def test_expandable
        name = "yaytest"
        dir = tempfile()
        Dir.mkdir(dir)

        mount = mkmount()
        assert_nothing_raised {
            mount.path = dir
        }

        assert(! mount.expandable?, "Mount incorrectly called expandable")

        assert_nothing_raised {
            mount.path = "/dir/a%a"
        }
        assert(mount.expandable?, "Mount not called expandable")

        # This isn't a valid replacement pattern, so it should throw an error
        # because the dir doesn't exist
        assert_raise(Puppet::Network::Handler::FileServerError) {
            mount.path = "/dir/a%"
        }

        # Now send it back to a normal path
        assert_nothing_raised {
            mount.path = dir
        }
        # Make sure it got reverted
        assert(! mount.expandable?, "Mount incorrectly called expandable")


    end

    def test_mount_expand
        mount = mkmount()

        check = proc do |client, pattern, repl|
            path = "/my/#{pattern}/file"
            assert_equal("/my/#{repl}/file", mount.expand(path, client))
        end

        # Do a round of checks with a fake client
        client = "host.domain.com"
        {"%h" => "host", # Short name
         "%H" => client, # Full name
         "%d" => "domain.com", # domain
         "%%" => "%", # escape
         "%o" => "%o" # other
         }.each do |pat, repl|
             result = check.call(client, pat, repl)
         end

        # Now, check that they use Facter info 
        Puppet.notice "The following messages are normal"
        client = nil
        Facter.stubs(:value).with(:ipaddress).returns("127.0.0.1")
        Facter.stubs(:value).with { |v| v.to_s == "hostname" }.returns("myhost")
        Facter.stubs(:value).with { |v| v.to_s == "domain" }.returns("mydomain.com")
        Facter.stubs(:value).with(:domain).returns("mydomain.com")

        {"%h" => "myhost", # Short name
         "%H" => "myhost.mydomain.com", # Full name
         "%d" => "mydomain.com", # domain
         "%%" => "%", # escape
         "%o" => "%o" # other
         }.each do |pat, repl|
             check.call(client, pat, repl)
         end

    end

    # Test that the fileserver expands the %h and %d things.
    def test_fileserver_expansion
        server = nil
        assert_nothing_raised {
            server = Puppet::Network::Handler.fileserver.new(
                :Local => true,
                :Config => false
            )
        }

        dir = tempfile()
        Facter.stubs(:value).with(:ipaddress).returns("127.0.0.1")
        Facter.stubs(:value).with { |v| v.to_s == "hostname" }.returns("myhost")
        Facter.stubs(:value).with { |v| v.to_s == "domain" }.returns("mydomain.com")
        Facter.stubs(:value).with(:domain).returns("mydomain.com")
        ip = Facter.value(:ipaddress)

        Dir.mkdir(dir)
        host = "myhost.mydomain.com"
        {
            "%H" => "myhost.mydomain.com", "%h" => "myhost", "%d" => "mydomain.com"
        }.each do |pattern, string|
            file = File.join(dir, string)
            mount = File.join(dir, pattern)
            File.open(file, "w") do |f| f.puts "yayness: %s" % string end
            name = "name"
            obj = nil
            assert_nothing_raised {
                obj = server.mount(mount, name)
            }
            obj.allow "*"

            ret = nil
            assert_nothing_raised do
                ret = server.list("/name", :manage, false, false, host, ip)
            end

            assert_equal("/\tfile", ret)

            assert_nothing_raised do
                ret = server.describe("/name", :manage, host, ip)
            end
            assert(ret =~ /\tfile\t/, "Did not get valid a description (#{ret.inspect})")

            assert_nothing_raised do
                ret = server.retrieve("/name", :manage, host, ip)
            end

            assert_equal(ret, File.read(file))

            server.umount(name)

            File.unlink(file)
        end
    end

    # Test the default modules fileserving
    def test_modules_default
        moddir = tempfile
        Dir.mkdir(moddir)
        mounts = {}
        Puppet[:modulepath] = moddir

        mods = %w{green red}.collect do |name|
            path = File::join(moddir, name, Puppet::Module::FILES)
            FileUtils::mkdir_p(path)
            if name == "green"
                file = File::join(path, "test.txt")
                File::open(file, "w") { |f| f.print name }
            end

           Puppet::Module::find(name)
        end

        conffile = tempfile

        File.open(conffile, "w") { |f| f.puts "# a test config file" }

        # create a server with the file
        server = nil
        assert_nothing_raised {
            server = Puppet::Network::Handler::FileServer.new(
                :Local => false ,
                :Config => conffile
            )
        }

        mods.each do |mod|
            mount = "/#{mod.name}/"
            list = nil
            assert_nothing_raised {
                list = server.list(mount, :manage, true, false)
            }
            list = list.split("\n")
            if mod.name == "green"
                assert_equal(2, list.size)
                assert_equal("/\tdirectory", list[0])
                assert_equal("/test.txt\tfile", list[1])
            else
                assert_equal(1, list.size)
                assert_equal("/\tdirectory", list[0])
            end

            assert_nothing_raised("Host 'allow' denied #{mount}") {
                server.list(mount, :manage, true, false,
                            'allow.example.com', "192.168.0.1")
            }
        end
    end

    # Test that configuring deny/allow for modules works
    def test_modules_config
        moddir = tempfile
        Dir.mkdir(moddir)
        mounts = {}
        Puppet[:modulepath] = moddir

        path = File::join(moddir, "amod", Puppet::Module::FILES)
        file = File::join(path, "test.txt")
        FileUtils::mkdir_p(path)
        File::open(file, "w") { |f| f.print "Howdy" }

        mod = Puppet::Module::find("amod")

        conffile = tempfile
        @@tmpfiles << conffile

        File.open(conffile, "w") { |f|
            f.print "# a test config file
[modules]
    path #{basedir}/thing
    allow 192.168.0.*
"
        }

        # create a server with the file
        server = nil
        assert_nothing_raised {
            server = Puppet::Network::Handler::FileServer.new(
                :Local => false,
                :Config => conffile
            )
        }

        list = nil
        mount = "/#{mod.name}/"
        assert_nothing_raised {
            list = server.list(mount, :manage, true, false)
        }

        assert_nothing_raised {
            list.split("\n").each { |line|
                file, type = line.split("\t")
                server.describe(mount + file)
            }
        }

        assert_describe(mount, file, server)

        # now let's check that things are being correctly forbidden
        assert_raise(Puppet::AuthorizationError,
                     "Host 'deny' allowed #{mount}") {
            server.list(mount, :manage, true, false,
                        'deny.example.com', "192.168.1.1")
        }
        assert_nothing_raised("Host 'allow' denied #{mount}") {
            server.list(mount, :manage, true, false,
                        'allow.example.com', "192.168.0.1")
        }
    end

    # Make sure we successfully throw errors -- someone ran into this with
    # 0.22.4.
    def test_failures
        # create a server with the file
        server = nil

        config = tempfile
        [
        "[this is invalid]\nallow one.two.com", # invalid name
        "[valid]\nallow *.testing something.com", # invalid allow
        "[valid]\nallow one.two.com\ndeny *.testing something.com", # invalid deny
        ].each do |failer|
            File.open(config, "w") { |f| f.puts failer }
            assert_raise(Puppet::Network::Handler::FileServerError, "Did not fail on %s" % failer.inspect) {
                server = Puppet::Network::Handler::FileServer.new(
                    :Local => false,
                    :Config => config
                )
            }
        end
    end

    def test_can_start_without_configuration
        Puppet[:fileserverconfig] = tempfile
        assert_nothing_raised("Could not create fileserver when configuration is absent") do
                server = Puppet::Network::Handler::FileServer.new(
                    :Local => false
                )
        end
    end

    def test_creates_default_mounts_when_no_configuration_is_available
        Puppet[:fileserverconfig] = tempfile
        server = Puppet::Network::Handler::FileServer.new(:Local => false)

        assert(server.mounted?("plugins"), "Did not create default plugins mount when missing configuration file")
        assert(server.mounted?("modules"), "Did not create default modules mount when missing configuration file")
    end
end