summaryrefslogtreecommitdiff
path: root/spec/unit/knife/bootstrap_spec.rb
blob: 76b9d49a8c5948cb7f4ec21b6fefb4465c665187 (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
#
# Author:: Ian Meyer (<ianmmeyer@gmail.com>)
# Copyright:: Copyright 2010-2016, Ian Meyer
# License:: Apache License, Version 2.0
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#

require "spec_helper"

Chef::Knife::Bootstrap.load_deps
require "net/ssh"

describe Chef::Knife::Bootstrap do
  before do
    allow(ChefConfig).to receive(:windows?) { false }
  end
  let(:knife) do
    Chef::Log.logger = Logger.new(StringIO.new)
    Chef::Config[:knife][:bootstrap_template] = bootstrap_template unless bootstrap_template.nil?

    k = Chef::Knife::Bootstrap.new(bootstrap_cli_options)
    k.merge_configs

    allow(k.ui).to receive(:stderr).and_return(stderr)
    allow(k).to receive(:encryption_secret_provided_ignore_encrypt_flag?).and_return(false)
    k
  end

  let(:stderr) { StringIO.new }

  let(:bootstrap_template) { nil }

  let(:bootstrap_cli_options) { [ ] }

  it "should use chef-full as default template" do
    expect(knife.bootstrap_template).to be_a_kind_of(String)
    expect(File.basename(knife.bootstrap_template)).to eq("chef-full")
  end

  context "when using the chef-full default template" do
    let(:rendered_template) do
      knife.merge_configs
      knife.render_template
    end

    it "should render client.rb" do
      expect(rendered_template).to match("cat > /etc/chef/client.rb <<'EOP'")
      expect(rendered_template).to match("chef_server_url  \"https://localhost:443\"")
      expect(rendered_template).to match("validation_client_name \"chef-validator\"")
      expect(rendered_template).to match("log_location   STDOUT")
    end

    it "should render first-boot.json" do
      expect(rendered_template).to match("cat > /etc/chef/first-boot.json <<'EOP'")
      expect(rendered_template).to match('{"run_list":\[\]}')
    end

    context "and encrypted_data_bag_secret was provided" do
      it "should render encrypted_data_bag_secret file" do
        expect(knife).to receive(:encryption_secret_provided_ignore_encrypt_flag?).and_return(true)
        expect(knife).to receive(:read_secret).and_return("secrets")
        expect(rendered_template).to match("cat > /etc/chef/encrypted_data_bag_secret <<'EOP'")
        expect(rendered_template).to match('{"run_list":\[\]}')
        expect(rendered_template).to match(%r{secrets})
      end
    end
  end

  context "with --bootstrap-vault-item" do
    let(:bootstrap_cli_options) { [ "--bootstrap-vault-item", "vault1:item1", "--bootstrap-vault-item", "vault1:item2", "--bootstrap-vault-item", "vault2:item1" ] }
    it "sets the knife config cli option correctly" do
      expect(knife.config[:bootstrap_vault_item]).to eq({ "vault1" => %w{item1 item2}, "vault2" => ["item1"] })
    end
  end

  context "with --bootstrap-preinstall-command" do
    command = "while sudo fuser /var/lib/dpkg/lock >/dev/null 2>&1; do\n   echo 'waiting for dpkg lock';\n   sleep 1;\n  done;"
    let(:bootstrap_cli_options) { [ "--bootstrap-preinstall-command", command ] }
    let(:rendered_template) do
      knife.merge_configs
      knife.render_template
    end
    it "configures the preinstall command in the bootstrap template correctly" do
      expect(rendered_template).to match(%r{command})
    end
  end

  context "with --bootstrap-proxy" do
    let(:bootstrap_cli_options) { [ "--bootstrap-proxy", "1.1.1.1" ] }
    let(:rendered_template) do
      knife.merge_configs
      knife.render_template
    end
    it "configures the https_proxy environment variable in the bootstrap template correctly" do
      expect(rendered_template).to match(%r{https_proxy="1.1.1.1" export https_proxy})
    end
  end

  context "with --bootstrap-no-proxy" do
    let(:bootstrap_cli_options) { [ "--bootstrap-no-proxy", "localserver" ] }
    let(:rendered_template) do
      knife.merge_configs
      knife.render_template
    end
    it "configures the https_proxy environment variable in the bootstrap template correctly" do
      expect(rendered_template).to match(%r{no_proxy="localserver" export no_proxy})
    end
  end

  context "with :bootstrap_template and :template_file cli options" do
    let(:bootstrap_cli_options) { [ "--bootstrap-template", "my-template", "other-template" ] }

    it "should select bootstrap template" do
      expect(File.basename(knife.bootstrap_template)).to eq("my-template")
    end
  end

  context "when finding templates" do
    context "when :bootstrap_template config is set to a file" do
      context "that doesn't exist" do
        let(:bootstrap_template) { "/opt/blah/not/exists/template.erb" }

        it "raises an error" do
          expect { knife.find_template }.to raise_error(Errno::ENOENT)
        end
      end

      context "that exists" do
        let(:bootstrap_template) { File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "test.erb")) }

        it "loads the given file as the template" do
          expect(Chef::Log).to receive(:trace)
          expect(knife.find_template).to eq(File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "test.erb")))
        end
      end
    end

    context "when :bootstrap_template config is set to a template name" do
      let(:bootstrap_template) { "example" }

      let(:builtin_template_path) { File.expand_path(File.join(File.dirname(__FILE__), "../../../lib/chef/knife/bootstrap/templates", "example.erb")) }

      let(:chef_config_dir_template_path) { "/knife/chef/config/bootstrap/example.erb" }

      let(:env_home_template_path) { "/env/home/.chef/bootstrap/example.erb" }

      let(:gem_files_template_path) { "/Users/schisamo/.rvm/gems/ruby-1.9.2-p180@chef-0.10/gems/knife-windows-0.5.4/lib/chef/knife/bootstrap/fake-bootstrap-template.erb" }

      def configure_chef_config_dir
        allow(Chef::Knife).to receive(:chef_config_dir).and_return("/knife/chef/config")
      end

      def configure_env_home
        allow(Chef::Util::PathHelper).to receive(:home).with(".chef", "bootstrap", "example.erb").and_yield(env_home_template_path)
      end

      def configure_gem_files
        allow(Gem).to receive(:find_files).and_return([ gem_files_template_path ])
      end

      before(:each) do
        expect(File).to receive(:exists?).with(bootstrap_template).and_return(false)
      end

      context "when file is available everywhere" do
        before do
          configure_chef_config_dir
          configure_env_home
          configure_gem_files

          expect(File).to receive(:exists?).with(builtin_template_path).and_return(true)
        end

        it "should load the template from built-in templates" do
          expect(knife.find_template).to eq(builtin_template_path)
        end
      end

      context "when file is available in chef_config_dir" do
        before do
          configure_chef_config_dir
          configure_env_home
          configure_gem_files

          expect(File).to receive(:exists?).with(builtin_template_path).and_return(false)
          expect(File).to receive(:exists?).with(chef_config_dir_template_path).and_return(true)

          it "should load the template from chef_config_dir" do
            knife.find_template.should eq(chef_config_dir_template_path)
          end
        end
      end

      context "when file is available in home directory" do
        before do
          configure_chef_config_dir
          configure_env_home
          configure_gem_files

          expect(File).to receive(:exists?).with(builtin_template_path).and_return(false)
          expect(File).to receive(:exists?).with(chef_config_dir_template_path).and_return(false)
          expect(File).to receive(:exists?).with(env_home_template_path).and_return(true)
        end

        it "should load the template from chef_config_dir" do
          expect(knife.find_template).to eq(env_home_template_path)
        end
      end

      context "when file is available in Gem files" do
        before do
          configure_chef_config_dir
          configure_env_home
          configure_gem_files

          expect(File).to receive(:exists?).with(builtin_template_path).and_return(false)
          expect(File).to receive(:exists?).with(chef_config_dir_template_path).and_return(false)
          expect(File).to receive(:exists?).with(env_home_template_path).and_return(false)
          expect(File).to receive(:exists?).with(gem_files_template_path).and_return(true)
        end

        it "should load the template from Gem files" do
          expect(knife.find_template).to eq(gem_files_template_path)
        end
      end

      context "when file is available in Gem files and home dir doesn't exist" do
        before do
          configure_chef_config_dir
          configure_gem_files
          allow(Chef::Util::PathHelper).to receive(:home).with(".chef", "bootstrap", "example.erb").and_return(nil)

          expect(File).to receive(:exists?).with(builtin_template_path).and_return(false)
          expect(File).to receive(:exists?).with(chef_config_dir_template_path).and_return(false)
          expect(File).to receive(:exists?).with(gem_files_template_path).and_return(true)
        end

        it "should load the template from Gem files" do
          expect(knife.find_template).to eq(gem_files_template_path)
        end
      end
    end
  end

  ["-t", "--bootstrap-template"].each do |t|
    context "when #{t} option is given in the command line" do
      it "sets the knife :bootstrap_template config" do
        knife.parse_options([t, "blahblah"])
        knife.merge_configs
        expect(knife.bootstrap_template).to eq("blahblah")
      end
    end
  end

  context "with run_list template" do
    let(:bootstrap_template) { File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "test.erb")) }

    it "should return an empty run_list" do
      expect(knife.render_template).to eq('{"run_list":[]}')
    end

    it "should have role[base] in the run_list" do
      knife.parse_options(["-r", "role[base]"])
      knife.merge_configs
      expect(knife.render_template).to eq('{"run_list":["role[base]"]}')
    end

    it "should have role[base] and recipe[cupcakes] in the run_list" do
      knife.parse_options(["-r", "role[base],recipe[cupcakes]"])
      knife.merge_configs
      expect(knife.render_template).to eq('{"run_list":["role[base]","recipe[cupcakes]"]}')
    end

    context "with bootstrap_attribute options" do
      let(:jsonfile) do
        file = Tempfile.new (["node", ".json"])
        File.open(file.path, "w") { |f| f.puts '{"foo":{"bar":"baz"}}' }
        file
      end

      it "should have foo => {bar => baz} in the first_boot from cli" do
        knife.parse_options(["-j", '{"foo":{"bar":"baz"}}'])
        knife.merge_configs
        expected_hash = FFI_Yajl::Parser.new.parse('{"foo":{"bar":"baz"},"run_list":[]}')
        actual_hash = FFI_Yajl::Parser.new.parse(knife.render_template)
        expect(actual_hash).to eq(expected_hash)
      end

      it "should have foo => {bar => baz} in the first_boot from file" do
        knife.parse_options(["--json-attribute-file", jsonfile.path])
        knife.merge_configs
        expected_hash = FFI_Yajl::Parser.new.parse('{"foo":{"bar":"baz"},"run_list":[]}')
        actual_hash = FFI_Yajl::Parser.new.parse(knife.render_template)
        expect(actual_hash).to eq(expected_hash)
        jsonfile.close
      end

      context "when --json-attributes and --json-attribute-file were both passed" do
        it "raises a Chef::Exceptions::BootstrapCommandInputError with the proper error message" do
          knife.parse_options(["-j", '{"foo":{"bar":"baz"}}'])
          knife.parse_options(["--json-attribute-file", jsonfile.path])
          knife.merge_configs
          expect { knife.run }.to raise_error(Chef::Exceptions::BootstrapCommandInputError)
          jsonfile.close
        end
      end
    end
  end

  context "with hints template" do
    let(:bootstrap_template) { File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "test-hints.erb")) }

    it "should create a hint file when told to" do
      knife.parse_options(["--hint", "openstack"])
      knife.merge_configs
      expect(knife.render_template).to match(/\/etc\/chef\/ohai\/hints\/openstack.json/)
    end

    it "should populate a hint file with JSON when given a file to read" do
      allow(::File).to receive(:read).and_return('{ "foo" : "bar" }')
      knife.parse_options(["--hint", "openstack=hints/openstack.json"])
      knife.merge_configs
      expect(knife.render_template).to match(/\{\"foo\":\"bar\"\}/)
    end
  end

  describe "specifying no_proxy with various entries" do
    subject(:knife) do
      k = described_class.new
      Chef::Config[:knife][:bootstrap_template] = template_file
      k.parse_options(options)
      k.merge_configs
      k
    end

    let(:options) { ["--bootstrap-no-proxy", setting, "-s", "foo"] }
    let(:template_file) { File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "no_proxy.erb")) }
    let(:rendered_template) do
      knife.render_template
    end

    context "via --bootstrap-no-proxy" do
      let(:setting) { "api.opscode.com" }

      it "renders the client.rb with a single FQDN no_proxy entry" do
        expect(rendered_template).to match(%r{.*no_proxy\s*"api.opscode.com".*})
      end
    end

    context "via --bootstrap-no-proxy multiple" do
      let(:setting) { "api.opscode.com,172.16.10.*" }

      it "renders the client.rb with comma-separated FQDN and wildcard IP address no_proxy entries" do
        expect(rendered_template).to match(%r{.*no_proxy\s*"api.opscode.com,172.16.10.\*".*})
      end
    end

    context "via --ssl-verify-mode none" do
      let(:options) { ["--node-ssl-verify-mode", "none"] }

      it "renders the client.rb with ssl_verify_mode set to :verify_none" do
        expect(rendered_template).to match(/ssl_verify_mode :verify_none/)
      end
    end

    context "via --node-ssl-verify-mode peer" do
      let(:options) { ["--node-ssl-verify-mode", "peer"] }

      it "renders the client.rb with ssl_verify_mode set to :verify_peer" do
        expect(rendered_template).to match(/ssl_verify_mode :verify_peer/)
      end
    end

    context "via --node-ssl-verify-mode all" do
      let(:options) { ["--node-ssl-verify-mode", "all"] }

      it "raises error" do
        expect { rendered_template }.to raise_error(RuntimeError)
      end
    end

    context "via --node-verify-api-cert" do
      let(:options) { ["--node-verify-api-cert"] }

      it "renders the client.rb with verify_api_cert set to true" do
        expect(rendered_template).to match(/verify_api_cert true/)
      end
    end

    context "via --no-node-verify-api-cert" do
      let(:options) { ["--no-node-verify-api-cert"] }

      it "renders the client.rb with verify_api_cert set to false" do
        expect(rendered_template).to match(/verify_api_cert false/)
      end
    end
  end

  describe "specifying the encrypted data bag secret key" do
    let(:secret) { "supersekret" }
    let(:options) { [] }
    let(:bootstrap_template) { File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "secret.erb")) }
    let(:rendered_template) do
      knife.parse_options(options)
      knife.merge_configs
      knife.render_template
    end

    it "creates a secret file" do
      expect(knife).to receive(:encryption_secret_provided_ignore_encrypt_flag?).and_return(true)
      expect(knife).to receive(:read_secret).and_return(secret)
      expect(rendered_template).to match(%r{#{secret}})
    end

    it "renders the client.rb with an encrypted_data_bag_secret entry" do
      expect(knife).to receive(:encryption_secret_provided_ignore_encrypt_flag?).and_return(true)
      expect(knife).to receive(:read_secret).and_return(secret)
      expect(rendered_template).to match(%r{encrypted_data_bag_secret\s*"/etc/chef/encrypted_data_bag_secret"})
    end

  end

  describe "when transferring trusted certificates" do
    let(:trusted_certs_dir) { Chef::Util::PathHelper.cleanpath(File.join(File.dirname(__FILE__), "../../data/trusted_certs")) }

    let(:rendered_template) do
      knife.merge_configs
      knife.render_template
    end

    before do
      Chef::Config[:trusted_certs_dir] = trusted_certs_dir
      allow(IO).to receive(:read).and_call_original
      allow(IO).to receive(:read).with(File.expand_path(Chef::Config[:validation_key])).and_return("")
    end

    def certificates
      Dir[File.join(trusted_certs_dir, "*.{crt,pem}")]
    end

    it "creates /etc/chef/trusted_certs" do
      expect(rendered_template).to match(%r{mkdir -p /etc/chef/trusted_certs})
    end

    it "copies the certificates in the directory" do
      certificates.each do |cert|
        expect(IO).to receive(:read).with(File.expand_path(cert))
      end

      certificates.each do |cert|
        expect(rendered_template).to match(%r{cat > /etc/chef/trusted_certs/#{File.basename(cert)} <<'EOP'})
      end
    end

    it "doesn't create /etc/chef/trusted_certs if :trusted_certs_dir is empty" do
      allow(Dir).to receive(:glob).and_call_original
      expect(Dir).to receive(:glob).with(File.join(trusted_certs_dir, "*.{crt,pem}")).and_return([])
      expect(rendered_template).not_to match(%r{mkdir -p /etc/chef/trusted_certs})
    end
  end

  context "when doing fips things" do
    let(:template_file) { File.expand_path(File.join(CHEF_SPEC_DATA, "bootstrap", "no_proxy.erb")) }
    let(:trusted_certs_dir) { Chef::Util::PathHelper.cleanpath(File.join(File.dirname(__FILE__), "../../data/trusted_certs")) }

    before do
      Chef::Config[:knife][:bootstrap_template] = template_file
    end

    let(:rendered_template) do
      knife.render_template
    end

    context "when knife is in fips mode" do
      before do
        Chef::Config[:fips] = true
      end

      it "renders 'fips true'" do
        Chef::Config[:fips] = true
        expect(rendered_template).to match("fips")
      end
    end

    context "when knife is not in fips mode" do
      before do
        # This is required because the chef-fips pipeline does
        # has a default value of true for fips
        Chef::Config[:fips] = false
      end

      it "does not render anything about fips" do
        expect(rendered_template).not_to match("fips")
      end
    end
  end

  describe "when transferring client.d" do

    let(:rendered_template) do
      knife.merge_configs
      knife.render_template
    end

    before do
      Chef::Config[:client_d_dir] = client_d_dir
    end

    context "when client_d_dir is nil" do
      let(:client_d_dir) { nil }

      it "does not create /etc/chef/client.d" do
        expect(rendered_template).not_to match(%r{mkdir -p /etc/chef/client\.d})
      end
    end

    context "when client_d_dir is set" do
      let(:client_d_dir) do
        Chef::Util::PathHelper.cleanpath(
        File.join(File.dirname(__FILE__), "../../data/client.d_00")) end

      it "creates /etc/chef/client.d" do
        expect(rendered_template).to match("mkdir -p /etc/chef/client\.d")
      end

      context "a flat directory structure" do
        it "escapes single-quotes" do
          expect(rendered_template).to match("cat > /etc/chef/client.d/02-strings.rb <<'EOP'")
          expect(rendered_template).to match("something '\\\\''/foo/bar'\\\\''")
        end

        it "creates a file 00-foo.rb" do
          expect(rendered_template).to match("cat > /etc/chef/client.d/00-foo.rb <<'EOP'")
          expect(rendered_template).to match("d6f9b976-289c-4149-baf7-81e6ffecf228")
        end
        it "creates a file bar" do
          expect(rendered_template).to match("cat > /etc/chef/client.d/bar <<'EOP'")
          expect(rendered_template).to match("1 / 0")
        end
      end

      context "a nested directory structure" do
        let(:client_d_dir) do
          Chef::Util::PathHelper.cleanpath(
          File.join(File.dirname(__FILE__), "../../data/client.d_01")) end
        it "creates a file foo/bar.rb" do
          expect(rendered_template).to match("cat > /etc/chef/client.d/foo/bar.rb <<'EOP'")
          expect(rendered_template).to match("1 / 0")
        end
      end
    end
  end

  describe "handling policyfile options" do

    context "when only policy_name is given" do

      let(:bootstrap_cli_options) { %w{ --policy-name my-app-server } }

      it "returns an error stating that policy_name and policy_group must be given together" do
        expect { knife.validate_options! }.to raise_error(SystemExit)
        expect(stderr.string).to include("ERROR: --policy-name and --policy-group must be specified together")
      end

    end

    context "when only policy_group is given" do

      let(:bootstrap_cli_options) { %w{ --policy-group staging } }

      it "returns an error stating that policy_name and policy_group must be given together" do
        expect { knife.validate_options! }.to raise_error(SystemExit)
        expect(stderr.string).to include("ERROR: --policy-name and --policy-group must be specified together")
      end

    end

    context "when both policy_name and policy_group are given, but run list is also given" do

      let(:bootstrap_cli_options) { %w{ --policy-name my-app --policy-group staging --run-list cookbook } }

      it "returns an error stating that policyfile and run_list are exclusive" do
        expect { knife.validate_options! }.to raise_error(SystemExit)
        expect(stderr.string).to include("ERROR: Policyfile options and --run-list are exclusive")
      end

    end

    context "when policy_name and policy_group are given with no conflicting options" do

      let(:bootstrap_cli_options) { %w{ --policy-name my-app --policy-group staging } }

      it "passes options validation" do
        expect { knife.validate_options! }.to_not raise_error
      end

      it "passes them into the bootstrap context" do
        expect(knife.bootstrap_context.first_boot).to have_key(:policy_name)
        expect(knife.bootstrap_context.first_boot).to have_key(:policy_group)
      end

      it "ensures that run_list is not set in the bootstrap context" do
        expect(knife.bootstrap_context.first_boot).to_not have_key(:run_list)
      end

    end

    # https://github.com/chef/chef/issues/4131
    # Arguably a bug in the plugin: it shouldn't be setting this to nil, but it
    # worked before, so make it work now.
    context "when a plugin sets the run list option to nil" do

      before do
        knife.config[:run_list] = nil
      end

      it "passes options validation" do
        expect { knife.validate_options! }.to_not raise_error
      end

    end

  end

  describe "when configuring the underlying knife ssh command" do
    context "from the command line" do
      let(:knife_ssh) do
        knife.name_args = ["foo.example.com"]
        knife.config[:ssh_user]      = "rooty"
        knife.config[:ssh_port]      = "4001"
        knife.config[:ssh_password]  = "open_sesame"
        Chef::Config[:knife][:ssh_user] = nil
        Chef::Config[:knife][:ssh_port] = nil
        knife.config[:forward_agent] = true
        knife.config[:ssh_identity_file] = "~/.ssh/me.rsa"
        allow(knife).to receive(:render_template).and_return("")
        knife.knife_ssh
      end

      it "configures the hostname" do
        expect(knife_ssh.name_args.first).to eq("foo.example.com")
      end

      it "configures the ssh user" do
        expect(knife_ssh.config[:ssh_user]).to eq("rooty")
      end

      it "configures the ssh password" do
        expect(knife_ssh.config[:ssh_password]).to eq("open_sesame")
      end

      it "configures the ssh port" do
        expect(knife_ssh.config[:ssh_port]).to eq("4001")
      end

      it "configures the ssh agent forwarding" do
        expect(knife_ssh.config[:forward_agent]).to eq(true)
      end

      it "configures the ssh identity file" do
        expect(knife_ssh.config[:ssh_identity_file]).to eq("~/.ssh/me.rsa")
      end
    end

    context "validating use_sudo_password" do
      before do
        knife.config[:ssh_password] = "password"
        allow(knife).to receive(:render_template).and_return("")
      end

      it "use_sudo_password contains description and long params for help" do
        expect(knife.options).to(have_key(:use_sudo_password)) \
          && expect(knife.options[:use_sudo_password][:description].to_s).not_to(eq(""))\
          && expect(knife.options[:use_sudo_password][:long].to_s).not_to(eq(""))
      end

      it "uses the password from --ssh-password for sudo when --use-sudo-password is set" do
        knife.config[:use_sudo] = true
        knife.config[:use_sudo_password] = true
        expect(knife.ssh_command).to include("echo \'#{knife.config[:ssh_password]}\' | sudo -S")
      end

      it "should not honor --use-sudo-password when --use-sudo is not set" do
        knife.config[:use_sudo] = false
        knife.config[:use_sudo_password] = true
        expect(knife.ssh_command).not_to include("echo #{knife.config[:ssh_password]} | sudo -S")
      end
    end

    context "from the knife config file" do
      let(:knife_ssh) do
        knife.name_args = ["config.example.com"]
        Chef::Config[:knife][:ssh_user] = "curiosity"
        Chef::Config[:knife][:ssh_port] = "2430"
        Chef::Config[:knife][:forward_agent] = true
        Chef::Config[:knife][:ssh_identity_file] = "~/.ssh/you.rsa"
        Chef::Config[:knife][:ssh_gateway] = "towel.blinkenlights.nl"
        Chef::Config[:knife][:ssh_gateway_identity] = "~/.ssh/gateway.rsa"
        Chef::Config[:knife][:host_key_verify] = true
        allow(knife).to receive(:render_template).and_return("")
        knife.config = {}
        knife.merge_configs
        knife.knife_ssh
      end

      it "configures the ssh user" do
        expect(knife_ssh.config[:ssh_user]).to eq("curiosity")
      end

      it "configures the ssh port" do
        expect(knife_ssh.config[:ssh_port]).to eq("2430")
      end

      it "configures the ssh agent forwarding" do
        expect(knife_ssh.config[:forward_agent]).to eq(true)
      end

      it "configures the ssh identity file" do
        expect(knife_ssh.config[:ssh_identity_file]).to eq("~/.ssh/you.rsa")
      end

      it "configures the ssh gateway" do
        expect(knife_ssh.config[:ssh_gateway]).to eq("towel.blinkenlights.nl")
      end

      it "configures the ssh gateway identity" do
        expect(knife_ssh.config[:ssh_gateway_identity]).to eq("~/.ssh/gateway.rsa")
      end

      it "configures the host key verify mode" do
        expect(knife_ssh.config[:host_key_verify]).to eq(true)
      end
    end

    describe "when falling back to password auth when host key auth fails" do
      let(:knife_ssh_with_password_auth) do
        knife.name_args = ["foo.example.com"]
        knife.config[:ssh_user] = "rooty"
        knife.config[:ssh_identity_file] = "~/.ssh/me.rsa"
        allow(knife).to receive(:render_template).and_return("")
        k = knife.knife_ssh
        allow(k).to receive(:get_password).and_return("typed_in_password")
        allow(knife).to receive(:knife_ssh).and_return(k)
        knife.knife_ssh_with_password_auth
      end

      it "prompts the user for a password " do
        expect(knife_ssh_with_password_auth.config[:ssh_password]).to eq("typed_in_password")
      end

      it "configures knife not to use the identity file that didn't work previously" do
        expect(knife_ssh_with_password_auth.config[:ssh_identity_file]).to be_nil
      end
    end
  end

  it "verifies that a server to bootstrap was given as a command line arg" do
    knife.name_args = nil
    expect { knife.run }.to raise_error(SystemExit)
    expect(stderr.string).to match(/ERROR:.+FQDN or ip/)
  end

  describe "when running the bootstrap" do
    let(:knife_ssh) do
      knife.name_args = ["foo.example.com"]
      knife.config[:chef_node_name] = "foo.example.com"
      knife.config[:ssh_user] = "rooty"
      knife.config[:ssh_identity_file] = "~/.ssh/me.rsa"
      allow(knife).to receive(:render_template).and_return("")
      knife_ssh = knife.knife_ssh
      allow(knife).to receive(:knife_ssh).and_return(knife_ssh)
      knife_ssh
    end
    let(:client) { Chef::ApiClient.new }

    context "when running with a configured and present validation key" do
      before do
        # this tests runs the old code path where we have a validation key, so we need to pass that check
        allow(File).to receive(:exist?).with(File.expand_path(Chef::Config[:validation_key])).and_return(true)
      end

      it "configures the underlying ssh command and then runs it" do
        expect(knife_ssh).to receive(:run)
        knife.run
      end

      it "falls back to password based auth when auth fails the first time" do
        allow(knife).to receive(:puts)

        fallback_knife_ssh = knife_ssh.dup
        expect(knife_ssh).to receive(:run).and_raise(Net::SSH::AuthenticationFailed.new("no ssh for you"))
        allow(knife).to receive(:knife_ssh_with_password_auth).and_return(fallback_knife_ssh)
        expect(fallback_knife_ssh).to receive(:run)
        knife.run
      end

      it "raises the exception if config[:ssh_password] is set and an authentication exception is raised" do
        knife.config[:ssh_password] = "password"
        expect(knife_ssh).to receive(:run).and_raise(Net::SSH::AuthenticationFailed)
        expect { knife.run }.to raise_error(Net::SSH::AuthenticationFailed)
      end

      it "creates the client and adds chef-vault items if vault_list is set" do
        knife.config[:bootstrap_vault_file] = "/not/our/responsibility/to/check/if/this/exists"
        expect(knife_ssh).to receive(:run)
        expect(knife.client_builder).to receive(:run)
        expect(knife.client_builder).to receive(:client).and_return(client)
        expect(knife.chef_vault_handler).to receive(:run).with(client)
        knife.run
      end

      it "creates the client and adds chef-vault items if vault_items is set" do
        knife.config[:bootstrap_vault_json] = '{ "vault" => "item" }'
        expect(knife_ssh).to receive(:run)
        expect(knife.client_builder).to receive(:run)
        expect(knife.client_builder).to receive(:client).and_return(client)
        expect(knife.chef_vault_handler).to receive(:run).with(client)
        knife.run
      end

      it "does old-style validation without creating a client key if vault_list+vault_items is not set" do
        expect(File).to receive(:exist?).with(File.expand_path(Chef::Config[:validation_key])).and_return(true)
        expect(knife_ssh).to receive(:run)
        expect(knife.client_builder).not_to receive(:run)
        expect(knife.chef_vault_handler).not_to receive(:run)
        knife.run
      end

      it "raises an exception if the config[:chef_node_name] is not present" do
        knife.config[:chef_node_name] = nil

        expect { knife.run }.to raise_error(SystemExit)
      end
    end

    context "when the validation key is not present" do
      before do
        # this tests runs the old code path where we have a validation key, so we need to pass that check
        allow(File).to receive(:exist?).with(File.expand_path(Chef::Config[:validation_key])).and_return(false)
      end

      it "creates the client (and possibly adds chef-vault items)" do
        expect(knife_ssh).to receive(:run)
        expect(knife.client_builder).to receive(:run)
        expect(knife.client_builder).to receive(:client).and_return(client)
        expect(knife.chef_vault_handler).to receive(:run).with(client)
        knife.run
      end

      it "raises an exception if the config[:chef_node_name] is not present" do
        knife.config[:chef_node_name] = nil

        expect { knife.run }.to raise_error(SystemExit)
      end
    end

    context "when the validation_key is nil" do
      before do
        # this tests runs the old code path where we have a validation key, so we need to pass that check for some plugins
        Chef::Config[:validation_key] = nil
      end

      it "creates the client and does not run client_builder or the chef_vault_handler" do
        expect(knife_ssh).to receive(:run)
        expect(knife.client_builder).not_to receive(:run)
        expect(knife.chef_vault_handler).not_to receive(:run)
        knife.run
      end
    end
  end

  describe "specifying ssl verification" do

  end
end