├── .foodcritic ├── .github ├── ISSUE_TEMPLATE.md └── PULL_REQUEST_TEMPLATE.md ├── .gitignore ├── .inch.yml ├── .kitchen.cloud.yml ├── .kitchen.yml ├── .travis.yml ├── .yardopts ├── Berksfile ├── CHANGELOG.md ├── CONTRIBUTING.md ├── Gemfile ├── Guardfile ├── LICENSE ├── README.md ├── Rakefile ├── TESTING.md ├── TODO.md ├── attributes └── default.rb ├── libraries ├── resource_helpers.rb └── template_helpers.rb ├── metadata.rb ├── resources └── ssh_authorized_key.rb ├── spec ├── recipes │ └── default_spec.rb ├── spec_helper.rb └── support │ └── coverage.rb ├── templates └── authorized_keys.erb └── test ├── cookbooks └── ssh_authorized_keys_test │ ├── CHANGELOG.md │ ├── README.md │ ├── metadata.rb │ └── recipes │ └── default.rb ├── integration └── default │ ├── bats │ └── bob.bats │ └── serverspec │ ├── Gemfile │ ├── alice_spec.rb │ ├── bob_spec.rb │ └── spec_helper.rb └── unit ├── resource_helpers_spec.rb └── template_helpers_spec.rb /.foodcritic: -------------------------------------------------------------------------------- 1 | ~FC015 2 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Cookbook Version 2 | [Version of the cookbook where you are encountering the issue] 3 | 4 | ### Chef Client Version 5 | [Version of chef-client in your environment] 6 | 7 | ### Platform Details 8 | [Operating system distribution and release version. Cloud provider if running in the cloud] 9 | 10 | ### Scenario 11 | [What you are trying to achieve and you can't?] 12 | 13 | ### Steps to Reproduce 14 | [If you are filing an issue what are the things we need to do in order to repro your problem? How are you using this cookbook or any resources it includes?] 15 | 16 | ### Expected Result 17 | [What are you expecting to happen as the consequence of above reproduction steps?] 18 | 19 | ### Actual Result 20 | [What actually happens after the reproduction steps? Include the error output or a link to a gist if possible.] 21 | -------------------------------------------------------------------------------- /.github/PULL_REQUEST_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | ### Description 2 | 3 | [Describe what this change achieves] 4 | 5 | ### Issues Resolved 6 | 7 | [List any existing issues this PR resolves] 8 | 9 | ### Contribution Check List 10 | 11 | - [ ] All tests pass. 12 | - [ ] New functionality includes testing. 13 | - [ ] New functionality has been documented in the README and metadata if applicable. 14 | 15 | See [CONTRIBUTING.md](https://github.com/zuazo/ssh_authorized_keys-cookbook/blob/master/CONTRIBUTING.md). 16 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .#* 2 | *~ 3 | *# 4 | \#*# 5 | Berksfile.lock 6 | bin 7 | bin/* 8 | .bundle 9 | .bundle/* 10 | .cache 11 | /cookbooks 12 | coverage 13 | doc 14 | Dockerfile-kitchen* 15 | *.gem 16 | Gemfile.lock 17 | .kitchen 18 | .kitchen.local.yml 19 | metadata.json 20 | nodes/ 21 | .*.sw[a-z] 22 | test/kitchen/.kitchen/ 23 | *.un~ 24 | .vagrant 25 | vendor 26 | .yardoc 27 | -------------------------------------------------------------------------------- /.inch.yml: -------------------------------------------------------------------------------- 1 | files: 2 | included: 3 | - Berksfile 4 | - Gemfile 5 | - Guardfile 6 | - Rakefile 7 | - attributes/*.rb 8 | - definitions/*.rb 9 | - libraries/*.rb 10 | - providers/*.rb 11 | - recipes/*.rb 12 | - resources/*.rb 13 | - templates/**/*.rb 14 | - spec/**/*.rb 15 | - test/**/*.rb 16 | - metatada.rb 17 | - Gemfile 18 | - Rakefile 19 | - Capfile 20 | - Guardfile 21 | - Podfile 22 | - Thorfile 23 | - Vagrantfile 24 | - Berksfile 25 | - Cheffile 26 | - Vagabondfile 27 | -------------------------------------------------------------------------------- /.kitchen.cloud.yml: -------------------------------------------------------------------------------- 1 | --- 2 | driver: 3 | aws_ssh_key_id: <%= ENV['AWS_KEYPAIR_NAME'] %> 4 | 5 | platforms: 6 | - name: centos-7-0-x64 7 | driver_plugin: digitalocean 8 | driver_config: 9 | flavor: 512MB 10 | 11 | - name: centos-8-0-x64 12 | driver_plugin: digitalocean 13 | driver_config: 14 | flavor: 512MB 15 | 16 | - name: debian-8-0-x64 17 | driver_plugin: digitalocean 18 | driver_config: 19 | flavor: 512MB 20 | run_list: ["recipe[apt]"] 21 | 22 | - name: debian-9-0-x64 23 | driver_plugin: digitalocean 24 | driver_config: 25 | flavor: 512MB 26 | run_list: ["recipe[apt]"] 27 | 28 | - name: fedora-19-x64 29 | driver_plugin: digitalocean 30 | driver_config: 31 | flavor: 512MB 32 | 33 | - name: fedora-20-x64 34 | driver_plugin: digitalocean 35 | driver_config: 36 | flavor: 512MB 37 | 38 | - name: ubuntu-16-04-x64 39 | driver_plugin: digitalocean 40 | driver_config: 41 | flavor: 512MB 42 | run_list: ["recipe[apt]"] 43 | 44 | - name: ubuntu-18-04-x64 45 | driver_plugin: digitalocean 46 | driver_config: 47 | flavor: 512MB 48 | run_list: ["recipe[apt]"] 49 | 50 | - name: ubuntu-20-04-x64 51 | driver_plugin: digitalocean 52 | driver_config: 53 | flavor: 512MB 54 | run_list: ["recipe[apt]"] 55 | 56 | - name: amazon-2 57 | driver_plugin: ec2 58 | driver_config: 59 | image_id: ami-02354e95b39ca8dec 60 | flavor_id: t2.micro 61 | username: ec2-user 62 | <% if ENV['SSH_AGENT_PID'].nil? %> 63 | ssh_key: <%= ENV['EC2_SSH_KEY_PATH'] %> 64 | <% end %> 65 | -------------------------------------------------------------------------------- /.kitchen.yml: -------------------------------------------------------------------------------- 1 | --- 2 | driver: 3 | name: vagrant 4 | 5 | provisioner: 6 | name: chef_zero 7 | product_name: chef 8 | <% if ENV.key?('CHEF_VERSION') %> 9 | product_version: <%= ENV['CHEF_VERSION'].sub(/^.*> (.*)[.][0-9]+$/, '\1') %> 10 | <% else %> 11 | product_version: 16 12 | <% end %> 13 | deprecations_as_errors: true 14 | chef_license: accept-no-persist 15 | 16 | platforms: 17 | - name: centos-6 18 | - name: centos-7 19 | - name: centos-8 20 | - name: debian-8 21 | - name: debian-9 22 | - name: debian-10 23 | - name: fedora-32 24 | # FreeBSD platform requires to run kitchen verify twice by hand 25 | # - name: freebsd-9.2 26 | # - name: freebsd-10.0 27 | # - name: freebsd-11 28 | - name: opensuse-leap-15 29 | - name: oracle-7 30 | - name: oracle-8 31 | - name: ubuntu-16.04 32 | - name: ubuntu-18.04 33 | - name: ubuntu-20.04 34 | 35 | suites: 36 | - name: default 37 | run_list: 38 | - recipe[ssh_authorized_keys_test::default] 39 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: ruby 2 | rvm: 2.5 3 | cache: bundler 4 | services: docker 5 | os: linux 6 | dist: bionic 7 | 8 | env: 9 | jobs: 10 | - TESTS="style unit" CHEF_VERSION="~> 14.0" CHEF_LICENSE=accept 11 | - TESTS="style unit" CHEF_VERSION="~> 15.0" CHEF_LICENSE=accept 12 | - TESTS="style unit" CHEF_VERSION="~> 16.0" CHEF_LICENSE=accept 13 | 14 | before_install: 15 | - chef --version &> /dev/null || curl -L https://www.getchef.com/chef/install.sh | sudo bash -s -- -P chefdk -v 4.10.0 16 | - eval "$(/opt/chefdk/bin/chef shell-init bash)" 17 | 18 | install: 19 | - chef exec bundle install --jobs=3 --retry=3 --without='doc integration_vagrant integration_cloud guard' 20 | 21 | before_script: 22 | # https://github.com/zuazo/kitchen-in-travis-native/issues/1#issuecomment-142455888 23 | - sudo iptables -L DOCKER || ( echo "DOCKER iptables chain missing" ; sudo iptables -N DOCKER ) 24 | - chef --version 25 | - cookstyle --version 26 | - foodcritic --version 27 | 28 | script: travis_retry chef exec bundle exec rake $TESTS 29 | -------------------------------------------------------------------------------- /.yardopts: -------------------------------------------------------------------------------- 1 | --markup markdown 2 | --no-private 3 | --exclude spec 4 | '*/**/*.rb' 5 | - 6 | *.md 7 | -------------------------------------------------------------------------------- /Berksfile: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # -*- mode: ruby -*- 3 | # vi: set ft=ruby : 4 | 5 | # More info at http://berkshelf.com/#the-berksfile 6 | 7 | source 'https://supermarket.chef.io' 8 | my_cookbook = 'ssh_authorized_keys' 9 | 10 | # Berkshelf helper to include a local cookbook from disk. 11 | # 12 | # @param name [String] cookbook name. 13 | # @param version [String] cookbook version requirement. 14 | # @param options [Hash] #cookbook method options. 15 | # return void 16 | def local_cookbook(name, version = '>= 0.0.0', options = {}) 17 | cookbook(name, version, { 18 | path: "../../cookbooks/#{name}", 19 | }.merge(options)) 20 | end 21 | 22 | metadata 23 | 24 | # Minitest Chef Handler 25 | # More info at https://github.com/calavera/minitest-chef-handler 26 | if ::File.directory?(::File.join('files', 'default', 'tests', 'minitest')) || 27 | ::File.directory?( 28 | ::File.join( 29 | 'test', 'cookbooks', "#{my_cookbook}_test", 'files', 'default', 'tests', 30 | 'minitest' 31 | ) 32 | ) 33 | cookbook 'minitest-handler' 34 | end 35 | 36 | # Integration tests cookbook: 37 | if ::File.directory?("./test/cookbooks/#{my_cookbook}_test") 38 | cookbook "#{my_cookbook}_test", path: "./test/cookbooks/#{my_cookbook}_test" 39 | end 40 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # CHANGELOG for ssh_authorized_keys 2 | 3 | All notable changes to the [`ssh_authorized_keys`](https://supermarket.chef.io/cookbooks/ssh_authorized_keys) Chef cookbook will be documented in this file. 4 | 5 | The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). 6 | 7 | ## [Unreleased] 8 | - ... 9 | 10 | ## [1.0.0] - 2020-08-09 11 | [![Build Status](https://img.shields.io/travis/zuazo/ssh_authorized_keys-cookbook/1.0.0.svg?style=flat)](https://travis-ci.org/zuazo/ssh_authorized_keys-cookbook) 12 | 13 | ### Added 14 | - Chef 16 support (issues [#15](https://github.com/zuazo/ssh_authorized_keys-cookbook/pull/15) and [#16](https://github.com/zuazo/ssh_authorized_keys-cookbook/pull/16), thanks [Benjamin M. Hughes](https://github.com/bmhughes) and [Corey Hemminger](https://github.com/Stromweld)). 15 | - Included Oracle support. 16 | 17 | ### Removed 18 | - Drop Ruby `< 2.5` support. 19 | - Drop Chef `< 14` support. 20 | 21 | ### Documentation Changes 22 | - README: Fix broken badges 23 | 24 | ## [0.4.0] - 2017-06-12 25 | [![Build Status](https://img.shields.io/travis/zuazo/ssh_authorized_keys-cookbook/0.4.0.svg?style=flat)](https://travis-ci.org/zuazo/ssh_authorized_keys-cookbook) 26 | 27 | ### Added 28 | - Adding ability to disable assert ([issue #6](https://github.com/zuazo/ssh_authorized_keys-cookbook/pull/6), thanks [Anthony Caiafa](https://github.com/acaiafa)). 29 | - Allowing direct key injection ([issue #7](https://github.com/zuazo/ssh_authorized_keys-cookbook/pull/7), thanks [Anthony Caiafa](https://github.com/acaiafa)). 30 | - Add AIX as supported platform ([issue #8](https://github.com/zuazo/ssh_authorized_keys-cookbook/issues/8), thanks [Mike Veltman](https://github.com/MVNW)). 31 | - metadata: Add `chef_version`. 32 | 33 | ### Removed 34 | - Drop Ruby `< 2.3` support. 35 | - Drop Chef `< 12` support. 36 | 37 | ### Documentation Changes 38 | - README: 39 | - Add documentation badge. 40 | - Fix Parameters table. 41 | - Add GitHub templates. 42 | - CHANGELOG: Follow "Keep a CHANGELOG". 43 | 44 | ## [0.3.0] - 2015-08-14 45 | [![Build Status](https://img.shields.io/travis/zuazo/ssh_authorized_keys-cookbook/0.3.0.svg?style=flat)](https://travis-ci.org/zuazo/ssh_authorized_keys-cookbook) 46 | 47 | ### Fixed 48 | - Use *gid* from `Etc.getpwnam` (issue [#3](https://github.com/zuazo/ssh_authorized_keys-cookbook/pull/3), thanks [Ong Ming Yang](https://github.com/ongmingyang)). 49 | - Recursively create *.ssh* directory if it does not exist (issue [#4](https://github.com/zuazo/ssh_authorized_keys-cookbook/pull/4), thanks [Ong Ming Yang](https://github.com/ongmingyang)). 50 | - Update chef links to use *chef.io* domain. 51 | - Update contact information and links after migration. 52 | 53 | ## [0.2.0] - 2015-05-27 54 | [![Build Status](https://img.shields.io/travis/zuazo/ssh_authorized_keys-cookbook/0.2.0.svg?style=flat)](https://travis-ci.org/zuazo/ssh_authorized_keys-cookbook) 55 | 56 | ### Added 57 | - Add openSUSE as supported platform. 58 | 59 | ### Fixed 60 | - Sort keys always in the same order ([issue #2](https://github.com/zuazo/ssh_authorized_keys-cookbook/issues/2), thanks to [Chris Burroughs](https://github.com/cburroughs) for the idea). 61 | 62 | ## 0.1.0 - 2015-01-11 63 | [![Build Status](https://img.shields.io/travis/zuazo/ssh_authorized_keys-cookbook/0.1.0.svg?style=flat)](https://travis-ci.org/zuazo/ssh_authorized_keys-cookbook) 64 | 65 | - Initial release of `ssh_authorized_keys`. 66 | 67 | [Unreleased]: https://github.com/zuazo/ssh_authorized_keys-cookbook/compare/1.0.0...HEAD 68 | [1.0.0]: https://github.com/zuazo/ssh_authorized_keys-cookbook/compare/0.4.0...1.0.0 69 | [0.4.0]: https://github.com/zuazo/ssh_authorized_keys-cookbook/compare/0.3.0...0.4.0 70 | [0.3.0]: https://github.com/zuazo/ssh_authorized_keys-cookbook/compare/0.2.0...0.3.0 71 | [0.2.0]: https://github.com/zuazo/ssh_authorized_keys-cookbook/compare/0.1.0...0.2.0 72 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | Contributing 2 | ============ 3 | 4 | 1. [Fork the repository on GitHub](https://help.github.com/articles/fork-a-repo). 5 | 2. Create a named feature branch (`$ git checkout -b my-new-feature`). 6 | 3. Write tests for your change (if applicable). 7 | 4. Write your change. 8 | 5. Add documentation to your change. 9 | 6. [Run the tests](https://github.com/zuazo/ssh_authorized_keys-cookbook/blob/master/TESTING.md), ensuring they all pass (`$ bundle exec rake`). 10 | 7. Commit your change (`$ git commit -am 'Add some feature'`). 11 | 8. Push to the branch (`$ git push origin my-new-feature`). 12 | 9. [Submit a Pull Request using GitHub](https://help.github.com/articles/creating-a-pull-request). 13 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # -*- mode: ruby -*- 3 | # vi: set ft=ruby : 4 | 5 | # More info at http://bundler.io/gemfile.html 6 | # 7 | # Many of the gem versions installed here are based on the versions installed 8 | # by ChefDK. 9 | 10 | source 'https://rubygems.org' 11 | 12 | chef_version = ENV.key?('CHEF_VERSION') ? ENV['CHEF_VERSION'] : nil 13 | 14 | group :doc do 15 | gem 'yard', '~> 0.9.5' 16 | end 17 | 18 | group :test do 19 | gem 'rake', '~> 13.0' 20 | gem 'berkshelf', '~> 7.0' 21 | end 22 | 23 | group :style do 24 | gem 'cookstyle', '~> 6.14' 25 | gem 'foodcritic', '~> 16.3' 26 | gem 'rubocop', '~> 0.88.0' 27 | end 28 | 29 | group :unit do 30 | gem 'chef', chef_version unless chef_version.nil? 31 | gem 'chefspec', '~> 9.2' 32 | gem 'simplecov', '~> 0.9' 33 | gem 'should_not', '~> 1.1' 34 | end 35 | 36 | group :integration do 37 | gem 'test-kitchen', '~> 2.5' 38 | end 39 | 40 | group :integration_docker do 41 | gem 'kitchen-docker', '~> 2.10' 42 | end 43 | 44 | group :integration_vagrant do 45 | gem 'vagrant-wrapper', '~> 2.0' 46 | gem 'kitchen-vagrant', '~> 1.7' 47 | end 48 | 49 | group :integration_cloud do 50 | gem 'kitchen-ec2', '~> 3.7' 51 | gem 'kitchen-digitalocean', '~> 0.11' 52 | end 53 | 54 | group :guard do 55 | gem 'guard', '~> 2.16' 56 | gem 'guard-foodcritic', '~> 3.0' 57 | gem 'guard-rubocop', '~> 1.3' 58 | gem 'guard-rspec', '~> 4.7' 59 | gem 'guard-kitchen', '~> 0.1' 60 | end 61 | 62 | group :travis do 63 | gem 'coveralls', '~> 0.8', require: false 64 | end 65 | -------------------------------------------------------------------------------- /Guardfile: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # -*- mode: ruby -*- 3 | # vi: set ft=ruby : 4 | 5 | # More info at https://github.com/guard/guard#readme 6 | 7 | # Style Tests 8 | # =========== 9 | # - Foodcritic 10 | # - RuboCop 11 | 12 | group :style, 13 | halt_on_fail: true do 14 | guard :foodcritic, 15 | cli: '--exclude test/unit', 16 | cookbook_paths: '.', 17 | all_on_start: false do 18 | watch(%r{attributes/.+\.rb$}) 19 | watch(%r{definitions/.+\.rb$}) 20 | watch(%r{libraries/.+\.rb$}) 21 | watch(%r{providers/.+\.rb$}) 22 | watch(%r{recipes/.+\.rb$}) 23 | watch(%r{resources/.+\.rb$}) 24 | watch(%r{templates/.+\.erb$}) 25 | watch('metadata.rb') 26 | end 27 | 28 | guard :rubocop, 29 | all_on_start: false do 30 | watch(/.+\.rb$/) 31 | watch('Gemfile') 32 | watch('Rakefile') 33 | watch('Capfile') 34 | watch('Guardfile') 35 | watch('Podfile') 36 | watch('Thorfile') 37 | watch('Vagrantfile') 38 | watch('Berksfile') 39 | watch('Cheffile') 40 | watch('Vagabondfile') 41 | end 42 | end # group style 43 | 44 | # Unit Tests 45 | # ========== 46 | # - test/unit/libraries/${library}_spec.rb: Unit tests for libraries. 47 | # - test/unit/recipes/${recipe}_spec.rb: ChefSpec tests for recipes. 48 | # - test/unit/resources/${resource}_spec.rb: ChefSpec tests for resources. 49 | 50 | group :unit do 51 | guard :rspec, 52 | cmd: 'bundle exec rake unit', 53 | all_on_start: false do 54 | watch(%r{^libraries/(.+)\.rb$}) do |m| 55 | "test/unit/libraries/#{m[1]}_spec.rb" 56 | end 57 | watch(%r{^recipes/(.+)\.rb$}) { |m| "test/unit/recipes/#{m[1]}_spec.rb" } 58 | watch(%r{^(?:providers|resources)/(.+)\.rb$}) do |m| 59 | "test/unit/resources/#{m[1]}_spec.rb" 60 | end 61 | watch(%r{^test/unit/.+_spec\.rb$}) 62 | watch('test/unit/spec_helper.rb') { 'spec' } 63 | end 64 | end # group unit 65 | 66 | # Integration Tests 67 | # ================= 68 | # - test-kitchen 69 | # 70 | # Temporary disabled. See the Gemfile. 71 | 72 | # group :integration do 73 | # guard 'kitchen', 74 | # all_on_start: false do 75 | # watch(%r{attributes/.+\.rb$}) 76 | # watch(%r{definitions/.+\.rb$}) 77 | # watch(%r{libraries/.+\.rb$}) 78 | # watch(%r{providers/.+\.rb$}) 79 | # watch(%r{recipes/.+\.rb$}) 80 | # watch(%r{resources/.+\.rb$}) 81 | # watch(%r{files/.+}) 82 | # watch(%r{templates/.+\.erb$}) 83 | # watch('metadata.rb') 84 | # watch(%r{test/.+$}) 85 | # watch('Berksfile') 86 | # end 87 | # end # group integration 88 | 89 | scope groups: [:style, :unit] 90 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | Copyright 2015-2016 Xabier de Zuazo 179 | 180 | Licensed under the Apache License, Version 2.0 (the "License"); 181 | you may not use this file except in compliance with the License. 182 | You may obtain a copy of the License at 183 | 184 | http://www.apache.org/licenses/LICENSE-2.0 185 | 186 | Unless required by applicable law or agreed to in writing, software 187 | distributed under the License is distributed on an "AS IS" BASIS, 188 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 189 | See the License for the specific language governing permissions and 190 | limitations under the License. 191 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # SSH Authorized Keys Cookbook 2 | 3 | [![Documentation](http://img.shields.io/badge/docs-rdoc.info-blue.svg?style=flat)](http://www.rubydoc.info/github/zuazo/ssh_authorized_keys-cookbook) 4 | [![GitHub](http://img.shields.io/badge/github-zuazo/ssh__authorized__keys--cookbook-blue.svg?style=flat)](https://github.com/zuazo/ssh_authorized_keys-cookbook) 5 | [![License](https://img.shields.io/github/license/zuazo/ssh_authorized_keys-cookbook.svg?style=flat)](#license-and-author) 6 | 7 | [![Cookbook Version](https://img.shields.io/cookbook/v/ssh_authorized_keys.svg?style=flat)](https://supermarket.chef.io/cookbooks/ssh_authorized_keys) 8 | [![Dependency Status](https://img.shields.io/librariesio/github/zuazo/ssh_authorized_keys-cookbook)](https://libraries.io/github/zuazo/ssh_authorized_keys-cookbook#dependencies) 9 | [![Code Climate maintainability](https://img.shields.io/codeclimate/maintainability/zuazo/ssh_authorized_keys-cookbook)](https://codeclimate.com/github/onddo/ssh_authorized_keys-cookbook) 10 | [![Build Status](https://img.shields.io/travis/zuazo/ssh_authorized_keys-cookbook.svg?style=flat)](https://travis-ci.org/zuazo/ssh_authorized_keys-cookbook) 11 | [![Coverage Status](https://img.shields.io/coveralls/zuazo/ssh_authorized_keys-cookbook.svg?style=flat)](https://coveralls.io/r/zuazo/ssh_authorized_keys-cookbook?branch=master) 12 | [![Inline docs](https://inch-ci.org/github/zuazo/ssh_authorized_keys-cookbook.svg?branch=master&style=flat)](https://inch-ci.org/github/zuazo/ssh_authorized_keys-cookbook) 13 | 14 | [Chef](https://www.chef.io/) cookbook to create SSH authorized keys files in user home directories. 15 | 16 | Tries to avoid generating a corrupt file that could render your server inaccessible. 17 | 18 | ## Requirements 19 | 20 | ### Supported Platforms 21 | 22 | This cookbook has been tested on the following platforms: 23 | 24 | * AIX 25 | * Amazon Linux 26 | * Debian 27 | * CentOS 28 | * Fedora 29 | * FreeBSD 30 | * openSUSE 31 | * Oracle 32 | * RedHat 33 | * SUSE 34 | * Ubuntu 35 | 36 | Please, [let us know](https://github.com/zuazo/ssh_authorized_keys-cookbook/issues/new?title=I%20have%20used%20it%20successfully%20on%20...) if you use it successfully on any other platform. 37 | 38 | ### Required Applications 39 | 40 | * Chef `14` or higher. 41 | * Ruby `2.5` or higher. 42 | 43 | ## Definitions 44 | 45 | ### ssh_authorize_key 46 | 47 | Authorize a key for public key authentication using SSH. 48 | 49 | **Warning:** This definition uses the [Accumulator Pattern](http://docs.chef.io/definitions.html#many-recipes-one-definition). This implies that any SSH key added using other methods (such as **keys added by hand**) will be **deleted**. 50 | 51 | ### ssh_authorize_key Properties 52 | 53 | | Property | Default | Description | 54 | |:-------------|:------------------|:-----------------------------------------| 55 | | user | `nil` | System user **(required)**. | 56 | | group | user | System group. | 57 | | home | *calculated* | System user home path. | 58 | | key | `nil` | SSH public key in base64 **(required)**. | 59 | | keytype | `'ssh-rsa'` | SSH key type. | 60 | | comment | *definition name* | SSH key comment. | 61 | | options | `nil` | SSH key options as a hash. | 62 | | validate_key | `true` | Enable/Disable assert_key | 63 | 64 | ## Usage Examples 65 | 66 | First of all, don't forget to include the `ssh_authorized_keys` cookbook as a dependency in the cookbook metadata: 67 | 68 | ```ruby 69 | # metadata.rb 70 | # [...] 71 | 72 | depends 'ssh_authorized_keys' 73 | ``` 74 | 75 | You can use the `ssh_authorize_key` to authorize SSH public keys to use SSH public key authentication: 76 | 77 | ```ruby 78 | # Bob is the admin here. 79 | 80 | ssh_authorize_key 'bob@acme.com' do 81 | key 'AAAAB3NzaC1yc2EAAAADAQABAAABAQCctNyRouVDhzjiP[...]' 82 | user 'root' 83 | end 84 | 85 | ssh_authorize_key 'alice@acme.com' do 86 | key 'AAAAB3NzaC1yc2EAAAADAQABAAABAQCySLKbpFRGCrKU/[...]' 87 | user 'alice' 88 | end 89 | ``` 90 | 91 | ### Setting the SSH Key Options Field 92 | 93 | You can set the options field as follows: 94 | 95 | ```ruby 96 | # As the root user by default in ubuntu: 97 | ssh_authorize_key 'bob@acme.com' do 98 | key 'AAAAB3NzaC1yc2EAAAADAQABAAABAQCctNyRouVDhzjiP[...]' 99 | user 'root' 100 | options( 101 | 'no-port-forwarding' => true, 102 | 'no-agent-forwarding' => true, 103 | 'no-X11-forwarding' => true, 104 | command: 105 | 'echo \'Please login as the user "bob" rather than the user "root".\''\ 106 | ';echo;sleep 10' 107 | ) 108 | end 109 | ``` 110 | 111 | ### Reading the Keys from a Data Bag 112 | 113 | For example, from the following data bag item: 114 | 115 | ```json 116 | { 117 | "id": "users", 118 | "bob@acme.com": { 119 | "key": "AAAAB3NzaC1yc2EAAAADAQABAAABAQCctNyRouVDhzjiP[...]", 120 | "user": "root" 121 | }, 122 | "alice@acme.com": { 123 | "key": "AAAAB3NzaC1yc2EAAAADAQABAAABAQCySLKbpFRGCrKU/[...]", 124 | "user": "alice" 125 | } 126 | } 127 | ``` 128 | 129 | You can read the data bag item from a recipe as follows: 130 | 131 | ```ruby 132 | users = data_bag_item('ssh', 'users') 133 | users.delete('id') 134 | 135 | users.each do |name, ssh_key| 136 | ssh_authorize_key name do 137 | key ssh_key['key'] 138 | user ssh_key['user'] 139 | end 140 | end 141 | ``` 142 | 143 | See [the data bags DSL documentation](http://docs.chef.io/data_bags.html#load-with-dsl-recipe) for a more detailed explanation and [the data bags knife documentation](http://docs.chef.io/data_bags.html#using-knife-title) to learn how to create a data bag. 144 | 145 | ## Attributes 146 | 147 | 148 | These attributes are primarily intended to support the different platforms. Do not touch them unless you know what you are doing. 149 | 150 | | Attribute | Default | Description | 151 | |:------------------------------------------|:-------------|:-----------------------| 152 | | `node['ssh_authorized_keys']['keytypes']` | *calculated* | Allowed SSH key types. | 153 | 154 | ## Testing 155 | 156 | 157 | See [TESTING.md](https://github.com/zuazo/ssh_authorized_keys-cookbook/blob/master/TESTING.md). 158 | 159 | ## ChefSpec Tests 160 | 161 | To create ChefSpec tests for the `ssh_authorize_key` definition, you can use the [`render_file`](http://www.rubydoc.info/github/sethvargo/chefspec#render_file) matcher to check the *authorized_keys* file content: 162 | 163 | ```ruby 164 | it 'allows bob to login as root' do 165 | expect(chef_run).to render_file('/root/.ssh/authorized_keys') 166 | .with_content(/^ssh-rsa [A-Za-z0-9+\/=]+ bob@acme\.com$/) 167 | end 168 | ``` 169 | 170 | You can also test against the internal template: 171 | 172 | ```ruby 173 | it 'creates ~bob/.ssh/authorized_keys file' do 174 | expect(chef_run).to create_template('/home/bob/.ssh/authorized_keys') 175 | end 176 | ``` 177 | 178 | ## Contributing 179 | 180 | 181 | Please do not hesitate to [open an issue](https://github.com/zuazo/ssh_authorized_keys-cookbook/issues/new) with any questions or problems. 182 | 183 | See [CONTRIBUTING.md](https://github.com/zuazo/ssh_authorized_keys-cookbook/blob/master/CONTRIBUTING.md). 184 | 185 | ## TODO 186 | 187 | 188 | See [TODO.md](https://github.com/zuazo/ssh_authorized_keys-cookbook/blob/master/TODO.md). 189 | 190 | 191 | ## License and Author 192 | 193 | | | | 194 | |:---------------------|:-----------------------------------------| 195 | | **Author:** | [Raul Rodriguez](https://github.com/raulr) () 196 | | **Author:** | [Xabier de Zuazo](https://github.com/zuazo) () 197 | | **Contributor:** | [Ong Ming Yang](https://github.com/ongmingyang) 198 | | **Contributor:** | [MVNW](https://github.com/MVNW) 199 | | **Contributor:** | [Anthony Caiafa](https://github.com/acaiafa) 200 | | **Contributor:** | [Benjamin M. Hughes](https://github.com/bmhughes) 201 | | **Contributor:** | [Corey Hemminger](https://github.com/Stromweld) 202 | | **Copyright:** | Copyright (c) 2015-2016, Xabier de Zuazo 203 | | **Copyright:** | Copyright (c) 2015, Onddo Labs, SL. 204 | | **License:** | Apache License, Version 2.0 205 | 206 | Licensed under the Apache License, Version 2.0 (the "License"); 207 | you may not use this file except in compliance with the License. 208 | You may obtain a copy of the License at 209 | 210 | http://www.apache.org/licenses/LICENSE-2.0 211 | 212 | Unless required by applicable law or agreed to in writing, software 213 | distributed under the License is distributed on an "AS IS" BASIS, 214 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 215 | See the License for the specific language governing permissions and 216 | limitations under the License. 217 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # -*- mode: ruby -*- 3 | # vi: set ft=ruby : 4 | 5 | # 6 | # Available Rake tasks: 7 | # 8 | # $ rake -T 9 | # rake clean # Clean some generated files 10 | # rake default # Run doc, style, unit and integration tests 11 | # rake doc # Generate Ruby documentation 12 | # rake integration[regexp,action] # Run Test Kitchen integration tests 13 | # rake integration:cloud[regexp,action] # Run Kitchen tests in the cloud 14 | # rake integration:docker[regexp,action] # Run Kitchen tests using docker 15 | # rake integration:vagrant[regexp,action] # Run Kitchen tests using vagrant 16 | # rake style # Run all style checks 17 | # rake style:chef # Run Chef style checks using foodcritic 18 | # rake style:ruby # Run Ruby style checks using rubocop 19 | # rake style:ruby:auto_correct # Auto-correct RuboCop offenses 20 | # rake unit # Run ChefSpec unit tests 21 | # rake yard # Generate Ruby documentation using yard 22 | # 23 | # More info at https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc 24 | # 25 | 26 | require 'bundler/setup' 27 | 28 | # Checks if we are inside a Continuous Integration machine. 29 | # 30 | # @return [Boolean] whether we are inside a CI. 31 | # @example 32 | # ci? #=> false 33 | def ci? 34 | ENV['CI'] == 'true' 35 | end 36 | 37 | desc 'Clean some generated files' 38 | task :clean do 39 | %w( 40 | Berksfile.lock 41 | .bundle 42 | .cache 43 | coverage 44 | Gemfile.lock 45 | .kitchen 46 | metadata.json 47 | vendor 48 | ).each { |f| FileUtils.rm_rf(Dir.glob(f)) } 49 | end 50 | 51 | desc 'Generate Ruby documentation using yard' 52 | task :yard do 53 | require 'yard' 54 | YARD::Rake::YardocTask.new do |t| 55 | t.stats_options = %w(--list-undoc) 56 | end 57 | end 58 | 59 | desc 'Generate Ruby documentation' 60 | task doc: %w(yard) 61 | 62 | namespace :style do 63 | require 'cookstyle' 64 | require 'rubocop/rake_task' 65 | desc 'Run Ruby style checks using rubocop' 66 | RuboCop::RakeTask.new(:cookstyle) 67 | 68 | require 'foodcritic' 69 | desc 'Run Chef style checks using foodcritic' 70 | FoodCritic::Rake::LintTask.new(:chef) do |t| 71 | t.options = { 72 | fail_tags: ['any'], 73 | progress: true, 74 | } 75 | end 76 | end 77 | 78 | desc 'Run all style checks' 79 | task style: %w(style:chef style:cookstyle) 80 | 81 | desc 'Run ChefSpec unit tests' 82 | task :unit do 83 | require 'rspec/core/rake_task' 84 | RSpec::Core::RakeTask.new(:unit) do |t| 85 | t.rspec_opts = '--color --format progress' 86 | t.pattern = 'test/unit/**{,/*/**}/*_spec.rb' 87 | end 88 | end 89 | 90 | desc 'Run Test Kitchen integration tests' 91 | namespace :integration do 92 | # Generates the `Kitchen::Config` class configuration values. 93 | # 94 | # @param loader_config [Hash] loader configuration options. 95 | # @return [Hash] configuration values for the `Kitchen::Config` class. 96 | def kitchen_config(loader_config = {}) 97 | {}.tap do |config| 98 | unless loader_config.empty? 99 | @loader = Kitchen::Loader::YAML.new(loader_config) 100 | config[:loader] = @loader 101 | end 102 | end 103 | end 104 | 105 | # Gets a collection of instances. 106 | # 107 | # @param regexp [String] regular expression to match against instance names. 108 | # @param config [Hash] configuration values for the `Kitchen::Config` class. 109 | # @return [Collection] all instances. 110 | def kitchen_instances(regexp, config) 111 | instances = Kitchen::Config.new(config).instances 112 | return instances if regexp.nil? || regexp == 'all' 113 | instances.get_all(Regexp.new(regexp)) 114 | end 115 | 116 | # Runs a test kitchen action against some instances. 117 | # 118 | # @param action [String] kitchen action to run (defaults to `'test'`). 119 | # @param regexp [String] regular expression to match against instance names. 120 | # @param loader_config [Hash] loader configuration options. 121 | # @return void 122 | def run_kitchen(action, regexp, loader_config = {}) 123 | action = 'test' if action.nil? 124 | require 'kitchen' 125 | Kitchen.logger = Kitchen.default_file_logger 126 | config = kitchen_config(loader_config) 127 | kitchen_instances(regexp, config).each { |i| i.send(action) } 128 | end 129 | 130 | desc 'Run Test Kitchen integration tests using vagrant' 131 | task :vagrant, [:regexp, :action] do |_t, args| 132 | run_kitchen(args.action, args.regexp) 133 | end 134 | 135 | desc 'Run Test Kitchen integration tests using docker' 136 | task :docker, [:regexp, :action] do |_t, args| 137 | run_kitchen(args.action, args.regexp, local_config: '.kitchen.docker.yml') 138 | end 139 | 140 | desc 'Run Test Kitchen integration tests in the cloud' 141 | task :cloud, [:regexp, :action] do |_t, args| 142 | run_kitchen(args.action, args.regexp, local_config: '.kitchen.cloud.yml') 143 | end 144 | end 145 | 146 | desc 'Run Test Kitchen integration tests' 147 | task :integration, [:regexp, :action] => 148 | ci? ? %w(integration:docker) : %w(integration:vagrant) 149 | 150 | desc 'Run doc, style, unit and integration tests' 151 | task default: %w(doc style unit integration) 152 | -------------------------------------------------------------------------------- /TESTING.md: -------------------------------------------------------------------------------- 1 | Testing 2 | ======= 3 | 4 | ## Installing the Requirements 5 | 6 | You must have [VirtualBox](https://www.virtualbox.org/) and [Vagrant](http://www.vagrantup.com/) installed. 7 | 8 | You can install gem dependencies with bundler: 9 | 10 | $ gem install bundler 11 | $ bundle config set without 'travis' 12 | $ bundle install 13 | 14 | ## Generating the Documentation 15 | 16 | This will generate the documentation for the source files inside the [*libraries/*](https://github.com/zuazo/ssh_authorized_keys-cookbook/tree/master/libraries) directory. 17 | 18 | $ bundle exec rake doc 19 | 20 | The documentation is included in the source code itself. 21 | 22 | ## Syntax Style Tests 23 | 24 | We use the following tools to test the code style: 25 | 26 | * [RuboCop](https://github.com/bbatsov/rubocop#readme) 27 | * [foodcritic](http://www.foodcritic.io/) 28 | 29 | To run the tests: 30 | 31 | $ bundle exec rake style 32 | 33 | ## Unit Tests 34 | 35 | We use [ChefSpec](https://github.com/sethvargo/chefspec#readme) and [RSpec](http://rspec.info/) for the unit tests. RSpec is generally used to test the libraries or some Ruby specific code. 36 | 37 | The unit test files are placed in the [*test/unit/*](https://github.com/zuazo/ssh_authorized_keys-cookbook/tree/master/test/unit) directory. 38 | 39 | To run the tests: 40 | 41 | $ bundle exec rake unit 42 | 43 | ## Integration Tests 44 | 45 | We use [Test Kitchen](http://kitchen.ci/) to run the tests and the tests are written using [Serverspec](http://serverspec.org/). 46 | 47 | The integration test files are placed in the [*test/integration/*](https://github.com/zuazo/ssh_authorized_keys-cookbook/tree/master/test/integration) directory. Some cookbooks required by this tests are in the [*test/cookbooks/*](https://github.com/zuazo/ssh_authorized_keys-cookbook/tree/master/test/cookbooks) directory. 48 | 49 | To run the tests: 50 | 51 | $ bundle exec rake integration:vagrant 52 | 53 | Or: 54 | 55 | $ bundle exec kitchen list 56 | $ bundle exec kitchen test 57 | [...] 58 | 59 | ### Integration Tests in Docker 60 | 61 | You can run the integration tests using [Docker](https://www.docker.com/) instead of Vagrant if you prefer. 62 | 63 | Of course, you need to have [Docker installed](https://docs.docker.com/engine/installation/). 64 | 65 | $ wget -qO- https://get.docker.com/ | sh 66 | 67 | Then use the `integration:docker` rake task to run the tests: 68 | 69 | $ bundle exec rake integration:docker 70 | 71 | ### Integration Tests in the Cloud 72 | 73 | You can run the tests in the cloud instead of using Vagrant. First, you must set the following environment variables: 74 | 75 | * `AWS_ACCESS_KEY_ID` 76 | * `AWS_SECRET_ACCESS_KEY` 77 | * `AWS_KEYPAIR_NAME`: EC2 SSH public key name. This is the name used in Amazon EC2 Console's Key Pars section. 78 | * `EC2_SSH_KEY_PATH`: EC2 SSH private key local full path. Only when you are not using an SSH Agent. 79 | * `DIGITALOCEAN_ACCESS_TOKEN` 80 | * `DIGITALOCEAN_SSH_KEY_IDS`: DigitalOcean SSH numeric key IDs. 81 | * `DIGITALOCEAN_SSH_KEY_PATH`: DigitalOcean SSH private key local full path. Only when you are not using an SSH Agent. 82 | 83 | Then use the `integration:cloud` rake task to run the tests: 84 | 85 | $ bundle exec rake integration:cloud 86 | 87 | ## Guard 88 | 89 | Guard is a tool that runs the tests automatically while you are making changes to the source files. 90 | 91 | To run Guard: 92 | 93 | $ guard 94 | 95 | More info at [Guard Readme](https://github.com/guard/guard#readme). 96 | 97 | ## Available Rake Tasks 98 | 99 | There are multiple Rake tasks that you can use to run the tests: 100 | 101 | $ rake -T 102 | 103 | See [Rakefile documentation](https://github.com/ruby/rake/blob/master/doc/rakefile.rdoc) for more information. 104 | -------------------------------------------------------------------------------- /TODO.md: -------------------------------------------------------------------------------- 1 | TODO 2 | ==== 3 | 4 | -------------------------------------------------------------------------------- /attributes/default.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Cookbook:: ssh_authorized_keys 4 | # Attributes:: default 5 | # Author:: Xabier de Zuazo () 6 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 7 | # License:: Apache License, Version 2.0 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); 10 | # you may not use this file except in compliance with the License. 11 | # You may obtain a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | # See the License for the specific language governing permissions and 19 | # limitations under the License. 20 | # 21 | 22 | default['ssh_authorized_keys']['keytypes'] = %w( 23 | ecdsa-sha2-nistp256 24 | ecdsa-sha2-nistp384 25 | ecdsa-sha2-nistp521 26 | ssh-ed25519 27 | ssh-dss 28 | ssh-rsa 29 | ) 30 | -------------------------------------------------------------------------------- /libraries/resource_helpers.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Cookbook:: ssh_authorized_keys 4 | # Library:: resource_helpers 5 | # Author:: Xabier de Zuazo () 6 | # Copyright:: Copyright (c) 2015-2016 Xabier de Zuazo 7 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 8 | # License:: Apache License, Version 2.0 9 | # 10 | # Licensed under the Apache License, Version 2.0 (the "License"); 11 | # you may not use this file except in compliance with the License. 12 | # You may obtain a copy of the License at 13 | # 14 | # http://www.apache.org/licenses/LICENSE-2.0 15 | # 16 | # Unless required by applicable law or agreed to in writing, software 17 | # distributed under the License is distributed on an "AS IS" BASIS, 18 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 19 | # See the License for the specific language governing permissions and 20 | # limitations under the License. 21 | # 22 | 23 | require 'etc' 24 | 25 | # `ssh_authorized_keys` internal classes. 26 | module SshAuthorizedKeysCookbook 27 | # Some helpers to use from `ssh_authorized_keys` cookbook resources and 28 | # definitions. 29 | # 30 | # @example 31 | # self.class.send(:include, ::SshAuthorizedKeysCookbook::ResourceHelpers) 32 | # user_home('vagrant') #=> "/home/vagrant" 33 | module ResourceHelpers 34 | unless defined?(::SshAuthorizedKeysCookbook::ResourceHelpers::SSH_KEY_REGEX) 35 | # Regular expression for SSH public keys in base64. 36 | SSH_KEY_REGEX = %r{ 37 | ^(?:[A-Za-z0-9+\/]{4})*(?: 38 | [A-Za-z0-9+\/]{2}== 39 | |[A-Za-z0-9+\/]{3}= 40 | |[A-Za-z0-9+\/]{4} 41 | )$ 42 | }x.freeze 43 | end 44 | 45 | # Asserts that the user name is correct. 46 | # 47 | # @param user [String] user name. 48 | # @raise [Chef::Exceptions::ValidationFailed] if the user name is wrong. 49 | # @return void 50 | def assert_user(user) 51 | return if user.is_a?(String) && !user.empty? 52 | raise Chef::Exceptions::ValidationFailed, 53 | 'ssh_authorize_key: user parameter must be a valid system user! '\ 54 | "You passed #{user.inspect}." 55 | end 56 | 57 | # Asserts that the SSH public key is correct. 58 | # 59 | # @param key [String] public key in base64. 60 | # @raise [Chef::Exceptions::ValidationFailed] if the key is wrong. 61 | # @return void 62 | def assert_key(key) 63 | return if key.is_a?(String) && !SSH_KEY_REGEX.match(key).nil? 64 | raise Chef::Exceptions::ValidationFailed, 65 | 'ssh_authorize_key: key parameter must be a valid SSH public key! '\ 66 | "You passed #{key.inspect}." 67 | end 68 | 69 | # Returns allowed SSH key types list. 70 | # 71 | # @return [Array] key types list. 72 | # @example 73 | # allowed_keytypes 74 | # #=> ["ecdsa-sha2-nistp256", "ecdsa-sha2-nistp384", 75 | # # "ecdsa-sha2-nistp521", "ssh-ed25519", "ssh-dss", "ssh-rsa"] 76 | def allowed_keytypes 77 | node['ssh_authorized_keys']['keytypes'] 78 | end 79 | 80 | # Asserts that the SSH key type is correct. 81 | # 82 | # @param keytype [String] key type. Supported types are `'ssh-rsa'`, 83 | # `'ssh-dss'`, `'ssh-ed25519'`, `'ecdsa-sha2-nistp521'`, 84 | # `'ecdsa-sha2-nistp384'` and `'ecdsa-sha2-nistp256'`. 85 | # @raise [Chef::Exceptions::ValidationFailed] if the keytype is wrong. 86 | # @return void 87 | def assert_keytype(keytype) 88 | return if allowed_keytypes.include?(keytype) 89 | raise Chef::Exceptions::ValidationFailed, 90 | 'ssh_authorize_key: keytype parameter must be equal to one of: '\ 91 | "#{allowed_keytypes.join(', ')}! You passed #{keytype.inspect}." 92 | end 93 | 94 | # Asserts that the key comment is correct. 95 | # 96 | # @param comment [String] key comment or description. 97 | # @raise [Chef::Exceptions::ValidationFailed] if the comment is wrong. 98 | # @return void 99 | def assert_comment(comment) 100 | if comment.is_a?(String) && !comment.empty? && !comment.include?("\n") 101 | return 102 | end 103 | raise Chef::Exceptions::ValidationFailed, 104 | 'ssh_authorize_key: comment parameter must be valid! You passed '\ 105 | "#{comment.inspect}." 106 | end 107 | 108 | # Returns the home directory of a system user. 109 | # 110 | # If the user does not exist, it returns `"/home/#{user}"` as the home 111 | # directory and emits a Chef warning. 112 | # 113 | # @param user [String] user name. 114 | # @return [String] home directory. 115 | # @example 116 | # user_home('root') #=> "/root" 117 | # user_home('mail') #=> "/var/mail" 118 | # user_home('bob') 119 | # #WARN: ssh_authorize_key: User bob not found at compile time, perhaps 120 | # #you should specify a home path. I will use "/home/bob" for now. 121 | # #=> "/home/bob" 122 | def user_home(user) 123 | Etc.getpwnam(user).dir 124 | rescue ArgumentError 125 | home = ::File.join('', 'home', user) 126 | Chef::Log.warn( 127 | "ssh_authorize_key: User #{user} not found at compile time, perhaps "\ 128 | "you should specify a home path. I will use #{home.inspect} for now." 129 | ) 130 | home 131 | end 132 | 133 | # Returns the group of a system user. 134 | # 135 | # @param user [String] user name. 136 | # @return [Integer] gid. 137 | # @example 138 | # user_group('root') #=> 0 139 | def user_group(user) 140 | Etc.getpwnam(user).gid 141 | rescue ArgumentError 142 | Chef::Log.warn( 143 | "ssh_authorize_key: User #{user} not found at compile time, perhaps "\ 144 | "you should specify a default group. I will use #{user} for now." 145 | ) 146 | user 147 | end 148 | end 149 | end 150 | -------------------------------------------------------------------------------- /libraries/template_helpers.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Cookbook:: ssh_authorized_keys 4 | # Library:: template_helpers 5 | # Author:: Xabier de Zuazo () 6 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 7 | # License:: Apache License, Version 2.0 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); 10 | # you may not use this file except in compliance with the License. 11 | # You may obtain a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | # See the License for the specific language governing permissions and 19 | # limitations under the License. 20 | # 21 | 22 | # `ssh_authorized_keys` internal classes. 23 | module SshAuthorizedKeysCookbook 24 | # Some helpers to use from `ssh_authorized_keys` cookbook templates. 25 | # 26 | # @example 27 | # self.class.send(:include, ::SshAuthorizedKeysCookbook::TemplateHelpers) 28 | # render_key('ssh-rsa', 'AAA...', 'sysadmin') 29 | # #=> "ssh-rsa AAA... sysadmin" 30 | module TemplateHelpers 31 | # Returns the SSH key option properly escaped. 32 | # 33 | # @param name [String] option name. 34 | # @param value [String, true] option value. Use `true` for option flags. 35 | # @return [String] string representation of the SSH key option. 36 | # @example 37 | # render_option_value('environment', 'NAME=value') 38 | # #=> "environment=\"NAME=value\"" 39 | def render_option_value(name, value) 40 | return name.to_s if value == true 41 | value_escaped = value.to_s.gsub('\\', '\\\\\\\\').gsub('"', '\\"') 42 | %(#{name}="#{value_escaped}") 43 | end 44 | 45 | # Returns the SSH key option list properly formated. 46 | # 47 | # @param options [Hash] the option list as key value hash. 48 | # @return [String] string representation of the option list properly 49 | # escaped. 50 | # @example 51 | # options = { 52 | # 'no-agent-forwarding' => true, 53 | # 'environment' => 'DISPLAY=:0' 54 | # } 55 | # render_options(options) 56 | # #=> "no-agent-forwarding,environment=\"DISPLAY=:0\"" 57 | def render_options(options) 58 | options.map { |name, value| render_option_value(name, value) }.join(',') 59 | end 60 | 61 | # Returns a rendered key line for the *authorized_keys* file. 62 | # 63 | # @param keytype [String] SSH key type. 64 | # @param key [String] SSH public key in base64. 65 | # @param comment [String] key comment or description. 66 | # @return [String] the *authorized_keys* file line. 67 | # @example 68 | # render_key('ssh-rsa', 'AAA...', 'sysadmin') 69 | # #=> "ssh-rsa AAA... sysadmin" 70 | def render_key(keytype, key, comment) 71 | "#{keytype} #{key} #{comment}" 72 | end 73 | end 74 | end 75 | -------------------------------------------------------------------------------- /metadata.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Cookbook:: ssh_authorized_keys 4 | # Author:: Xabier de Zuazo () 5 | # Copyright:: Copyright (c) 2015-2016 Xabier de Zuazo 6 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 7 | # License:: Apache License, Version 2.0 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); 10 | # you may not use this file except in compliance with the License. 11 | # You may obtain a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | # See the License for the specific language governing permissions and 19 | # limitations under the License. 20 | # 21 | 22 | name 'ssh_authorized_keys' 23 | maintainer 'Xabier de Zuazo' 24 | maintainer_email 'xabier@zuazo.org' 25 | license 'Apache-2.0' 26 | description 'Creates SSH authorized keys files in user home directories.' 27 | # long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) 28 | version '1.1.0' # WiP 29 | 30 | source_url "https://github.com/zuazo/#{name}-cookbook" 31 | issues_url "https://github.com/zuazo/#{name}-cookbook/issues" 32 | 33 | chef_version '>= 14' 34 | 35 | supports 'aix' 36 | supports 'amazon' 37 | supports 'debian' 38 | supports 'centos' 39 | supports 'fedora' 40 | supports 'freebsd' 41 | supports 'opensuse' 42 | supports 'oracle' 43 | supports 'redhat' 44 | supports 'suse' 45 | supports 'ubuntu' 46 | -------------------------------------------------------------------------------- /resources/ssh_authorized_key.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Cookbook:: ssh_authorized_keys 4 | # Resource:: ssh_authorize_key 5 | # Author:: Ben Hughes 6 | # Author:: Corey Hemminger 7 | # Author:: Xabier de Zuazo () 8 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 9 | # License:: Apache License, Version 2.0 10 | # 11 | # Licensed under the Apache License, Version 2.0 (the "License"); 12 | # you may not use this file except in compliance with the License. 13 | # You may obtain a copy of the License at 14 | # 15 | # http://www.apache.org/licenses/LICENSE-2.0 16 | # 17 | # Unless required by applicable law or agreed to in writing, software 18 | # distributed under the License is distributed on an "AS IS" BASIS, 19 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 20 | # See the License for the specific language governing permissions and 21 | # limitations under the License. 22 | # 23 | 24 | provides :ssh_authorize_key 25 | resource_name :ssh_authorize_key 26 | default_action :create 27 | 28 | description 'Manages ssh keys in users authorized_keys file' 29 | 30 | property :instance_name, String, 31 | name_property: true, 32 | description: 'Resource name' 33 | 34 | property :user, [Integer, String], 35 | required: true, 36 | description: 'System user **(required)**' 37 | 38 | property :group, [Integer, String], 39 | description: 'System group' 40 | 41 | property :home, String, 42 | description: 'System user home path' 43 | 44 | property :key, String, 45 | required: true, 46 | description: 'SSH public key in base64 **(required)**' 47 | 48 | property :keytype, String, 49 | default: 'ssh-rsa', 50 | description: 'SSH key type' 51 | 52 | property :comment, String, 53 | name_property: true, 54 | description: 'SSH key comment' 55 | 56 | property :options, Hash, 57 | description: 'SSH key options as a hash' 58 | 59 | property :validate_key, [true, false], 60 | default: true, 61 | description: 'Enable/Disable assert_key' 62 | 63 | action :create do 64 | assert_user(new_resource.user) 65 | new_resource.comment ||= new_resource.instance_name 66 | new_resource.group ||= user_group(new_resource.user) 67 | new_resource.home ||= user_home(new_resource.user) 68 | 69 | ssh_key = { 70 | options: new_resource.options, 71 | key: new_resource.key, 72 | validate_key: new_resource.validate_key, 73 | keytype: new_resource.keytype, 74 | comment: new_resource.comment, 75 | } 76 | 77 | assert_key(ssh_key[:key]) if new_resource.validate_key 78 | assert_keytype(ssh_key[:keytype]) 79 | assert_comment(ssh_key[:comment]) 80 | 81 | path = ::File.join(new_resource.home, '.ssh', 'authorized_keys') 82 | 83 | # Avoid CHEF-3694 warning for .ssh directory. 84 | dir = ::File.dirname(path) 85 | 86 | directory dir do 87 | recursive true 88 | owner new_resource.user 89 | group new_resource.group 90 | mode '00700' 91 | end 92 | 93 | # Accumulator Pattern: 94 | # https://blog.dnsimple.com/2017/10/chef-accumulators/ 95 | with_run_context :root do 96 | edit_resource(:template, path) do 97 | cookbook 'ssh_authorized_keys' 98 | source 'authorized_keys.erb' 99 | owner new_resource.user 100 | group new_resource.group 101 | mode '00600' 102 | variables['keys'] ||= {} 103 | variables['keys'][ssh_key[:comment]] = ssh_key 104 | variables['keys'] = variables['keys'].sort.to_h 105 | action :nothing 106 | delayed_action :create 107 | end 108 | end 109 | end 110 | 111 | action :remove do 112 | description 'Remove ssh keys from users authorized_keys file' 113 | # TODO: Create remove logic 114 | end 115 | 116 | action_class do 117 | include SshAuthorizedKeysCookbook::TemplateHelpers 118 | include SshAuthorizedKeysCookbook::ResourceHelpers 119 | end 120 | -------------------------------------------------------------------------------- /spec/recipes/default_spec.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Author:: Xabier de Zuazo () 4 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 5 | # License:: Apache License, Version 2.0 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | 20 | require 'spec_helper' 21 | 22 | describe 'ssh_authorized_keys_test::default', order: :random do 23 | let(:chef_runner) { ChefSpec::SoloRunner.new } 24 | let(:chef_run) { chef_runner.converge(described_recipe) } 25 | 26 | it 'creates bob user' do 27 | expect(chef_run).to create_user('bob') 28 | .with_supports(manage_home: true) 29 | .with_home('/home/bob') 30 | end 31 | 32 | it 'creates bob group' do 33 | expect(chef_run).to create_group('bob') 34 | .with_members(%w(bob)) 35 | end 36 | 37 | it 'creates bob2 user' do 38 | expect(chef_run).to create_user('bob2') 39 | .with_supports(manage_home: true) 40 | .with_home('/home/bob2') 41 | end 42 | 43 | it 'creates bob2 group' do 44 | expect(chef_run).to create_group('bob2') 45 | .with_members(%w(bob2)) 46 | end 47 | 48 | it 'creates alice user' do 49 | expect(chef_run).to create_user('alice') 50 | .with_supports(manage_home: true) 51 | .with_home('/home/alice') 52 | end 53 | 54 | it 'creates alice group' do 55 | expect(chef_run).to create_group('alice') 56 | .with_members(%w(alice)) 57 | end 58 | 59 | it 'creates ~bob/.ssh directory recursively' do 60 | expect(chef_run).to create_directory('/home/bob/.ssh') 61 | .with_recursive(true) 62 | .with_owner('bob') 63 | .with_group('bob') 64 | .with_mode('00700') 65 | end 66 | 67 | it 'creates ~bob/.ssh/authorized_keys file' do 68 | expect(chef_run).to create_template('/home/bob/.ssh/authorized_keys') 69 | .with_cookbook('ssh_authorized_keys') 70 | .with_source('authorized_keys.erb') 71 | .with_owner('bob') 72 | .with_group('bob') 73 | .with_mode('00600') 74 | end 75 | 76 | it 'authorizes bob@acme.com to login as bob' do 77 | expect(chef_run).to render_file('/home/bob/.ssh/authorized_keys') 78 | .with_content(%r{^ssh-rsa [A-Za-z0-9+/=]+ bob@acme\.com$}) 79 | end 80 | 81 | it 'authorizes bob@home.com to login as bob' do 82 | expect(chef_run).to render_file('/home/bob/.ssh/authorized_keys') 83 | .with_content(%r{^ssh-rsa [A-Za-z0-9+/=]+ bob@home\.com comment$}) 84 | end 85 | 86 | it 'creates ~bob2/.ssh directory recursively' do 87 | expect(chef_run).to create_directory('/home/bob2/.ssh') 88 | .with_recursive(true) 89 | .with_owner('bob2') 90 | .with_group('bob2') 91 | .with_mode('00700') 92 | end 93 | 94 | it 'creates ~bob2/.ssh/authorized_keys file' do 95 | expect(chef_run).to create_template('/home/bob2/.ssh/authorized_keys') 96 | .with_cookbook('ssh_authorized_keys') 97 | .with_source('authorized_keys.erb') 98 | .with_owner('bob2') 99 | .with_group('bob2') 100 | .with_mode('00600') 101 | end 102 | 103 | it 'authorizes bob@acme.com to login as bob2' do 104 | expect(chef_run).to render_file('/home/bob2/.ssh/authorized_keys') 105 | .with_content(%r{^ssh-rsa [A-Za-z0-9+/=]+ bob@acme\.com$}) 106 | end 107 | 108 | it 'authorizes bob@home.com to login as bob2' do 109 | expect(chef_run).to render_file('/home/bob2/.ssh/authorized_keys') 110 | .with_content(%r{^ssh-rsa [A-Za-z0-9+/=]+ bob@home\.com comment$}) 111 | end 112 | 113 | it 'writes bob2 keys in the same order as bob keys' do 114 | file1 = chef_run.template('/home/bob/.ssh/authorized_keys') 115 | content1 = ChefSpec::Renderer.new(chef_run, file1).content 116 | expect(chef_run).to render_file('/home/bob2/.ssh/authorized_keys') 117 | .with_content(content1) 118 | end 119 | 120 | it 'creates ~alice/.ssh directory recursively' do 121 | expect(chef_run).to create_directory('/home/alice/.ssh') 122 | .with_recursive(true) 123 | .with_owner('alice') 124 | .with_group('alice') 125 | .with_mode('00700') 126 | end 127 | 128 | it 'creates ~alice/.ssh/authorized_keys file' do 129 | expect(chef_run).to create_template('/home/alice/.ssh/authorized_keys') 130 | .with_cookbook('ssh_authorized_keys') 131 | .with_source('authorized_keys.erb') 132 | .with_owner('alice') 133 | .with_group('alice') 134 | .with_mode('00600') 135 | end 136 | 137 | it 'authorizes alice@acme.com to login as alice including options' do 138 | options = 139 | 'no-port-forwarding,no-agent-forwarding,no-X11-forwarding,'\ 140 | 'command="echo \'Please login as the user \"bob\" rather than the user '\ 141 | '\"alice\".\';echo;sleep 10"' 142 | expect(chef_run).to render_file('/home/alice/.ssh/authorized_keys') 143 | .with_content( 144 | %r{^#{Regexp.escape(options)} ssh-rsa [A-Za-z0-9+/=]+ alice@acme\.com$} 145 | ) 146 | end 147 | 148 | it 'creates ~root/.ssh directory' do 149 | expect(chef_run).to create_directory('/root/.ssh') 150 | .with_mode('00700') 151 | end 152 | 153 | it 'creates ~root/.ssh/key2 file' do 154 | expect(chef_run).to create_file('/root/.ssh/key2') 155 | .with_mode('00600') 156 | end 157 | end 158 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Author:: Xabier de Zuazo () 4 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 5 | # License:: Apache License, Version 2.0 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | 20 | $LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', 'libraries')) 21 | 22 | require 'chefspec' 23 | require 'chefspec/berkshelf' 24 | # require 'should_not/rspec' 25 | 26 | require 'support/coverage' 27 | 28 | RSpec.configure do |config| 29 | # Prohibit using the should syntax 30 | config.expect_with :rspec do |spec| 31 | spec.syntax = :expect 32 | end 33 | 34 | # Run specs in random order to surface order dependencies. If you find an 35 | # order dependency and want to debug it, you can fix the order by providing 36 | # the seed, which is printed after each run. 37 | # --seed 1234 38 | # config.order = 'random' 39 | # Library tests first (they are capitalized) to not interfere with coverage 40 | config.register_ordering(:global) do |list| 41 | list.sort_by(&:description) 42 | end 43 | 44 | # ChefSpec configuration 45 | config.log_level = :fatal 46 | config.color = true 47 | config.formatter = :documentation 48 | config.tty = true 49 | config.platform = 'ubuntu' 50 | config.version = '18.04' 51 | end 52 | -------------------------------------------------------------------------------- /spec/support/coverage.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Author:: Xabier de Zuazo () 4 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 5 | # License:: Apache License, Version 2.0 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | 20 | if ENV['TRAVIS'] 21 | require 'coveralls' 22 | Coveralls.wear! 23 | else 24 | require 'simplecov' 25 | SimpleCov.start do 26 | add_group 'Libraries', '/libraries' 27 | add_group 'ChefSpec' do |src| 28 | %r{/spec/(recipes|resources|providers)}.match(src.filename) 29 | end 30 | add_group 'RSpec' do |src| 31 | %r{/spec/(unit|functional|integration|libraries)}.match(src.filename) 32 | end 33 | add_group 'RSpec Support', '/spec/support' 34 | end 35 | end 36 | -------------------------------------------------------------------------------- /templates/authorized_keys.erb: -------------------------------------------------------------------------------- 1 | <% 2 | self.class.send(:include, ::SshAuthorizedKeysCookbook::TemplateHelpers) 3 | -%># Generated by Chef 4 | <% @keys.each do |_name, ssh_key| -%> 5 | <% if ssh_key[:validate_key] == false %> 6 | <%= ssh_key[:key] %> 7 | <% else %> 8 | <%= "#{render_options(ssh_key[:options])} " if ssh_key[:options].is_a?(Hash) 9 | %><%= render_key(ssh_key[:keytype], ssh_key[:key], ssh_key[:comment]) %> 10 | <% end -%> 11 | <% end %> 12 | -------------------------------------------------------------------------------- /test/cookbooks/ssh_authorized_keys_test/CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ssh_authorized_keys_test CHANGELOG 2 | ================================== 3 | 4 | This file is used to list changes made in each version of the ssh_authorized_keys_test cookbook. 5 | 6 | 0.1.0 7 | ----- 8 | - [your_name] - Initial release of ssh_authorized_keys_test 9 | 10 | - - - 11 | Check the [Markdown Syntax Guide](http://daringfireball.net/projects/markdown/syntax) for help with Markdown. 12 | 13 | The [Github Flavored Markdown page](http://github.github.com/github-flavored-markdown/) describes the differences between markdown on github and standard markdown. 14 | -------------------------------------------------------------------------------- /test/cookbooks/ssh_authorized_keys_test/README.md: -------------------------------------------------------------------------------- 1 | This cookbook is used with [test-kitchen](http://kitchen.ci/) to test the parent, [ssh_authorized_keys](https://supermarket.chef.io/cookbooks/ssh_authorized_keys) cookbook. 2 | -------------------------------------------------------------------------------- /test/cookbooks/ssh_authorized_keys_test/metadata.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Cookbook:: ssh_authorized_keys_test 4 | # Author:: Xabier de Zuazo () 5 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 6 | # License:: Apache License, Version 2.0 7 | # 8 | # Licensed under the Apache License, Version 2.0 (the "License"); 9 | # you may not use this file except in compliance with the License. 10 | # You may obtain a copy of the License at 11 | # 12 | # http://www.apache.org/licenses/LICENSE-2.0 13 | # 14 | # Unless required by applicable law or agreed to in writing, software 15 | # distributed under the License is distributed on an "AS IS" BASIS, 16 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | # See the License for the specific language governing permissions and 18 | # limitations under the License. 19 | # 20 | 21 | name 'ssh_authorized_keys_test' 22 | maintainer 'Xabier de Zuazo' 23 | maintainer_email 'xabier@zuazo.org' 24 | license 'Apache-2.0' 25 | description <<-EOS 26 | This cookbook is used with test-kitchen to test the parent, ssh_authorized_keys 27 | cookbook. 28 | EOS 29 | # long_description IO.read(File.join(File.dirname(__FILE__), 'README.md')) 30 | version '0.1.0' # WiP 31 | 32 | depends 'ssh_authorized_keys' 33 | -------------------------------------------------------------------------------- /test/cookbooks/ssh_authorized_keys_test/recipes/default.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Cookbook:: ssh_authorized_keys_test 4 | # Recipe:: default 5 | # Author:: Xabier de Zuazo () 6 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 7 | # License:: Apache License, Version 2.0 8 | # 9 | # Licensed under the Apache License, Version 2.0 (the "License"); 10 | # you may not use this file except in compliance with the License. 11 | # You may obtain a copy of the License at 12 | # 13 | # http://www.apache.org/licenses/LICENSE-2.0 14 | # 15 | # Unless required by applicable law or agreed to in writing, software 16 | # distributed under the License is distributed on an "AS IS" BASIS, 17 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | # See the License for the specific language governing permissions and 19 | # limitations under the License. 20 | # 21 | 22 | key1 = 23 | 'AAAAB3NzaC1yc2EAAAADAQABAAABAQCctNyRouVDhzjiP+u3R2+C0nD4VgsRgN9rOizD2ePBrf8'\ 24 | '508VR5envsmEY5oF+TM3k/wb2xBY45KXOu9yQjQi9RcCYvrCAu3wPTrx07vRetkDIvs/O383zQQ'\ 25 | 'anrHMGckNzh83uwDU4JcJqBP2EwkTMUqlk6xyrGuQyjmWFKWjjUUkmHFII5azAh+9bp4OjULE9h'\ 26 | '9fy4Y3ZOxHMrHuC5AjkWhvy88ItmGBf0sj0iW0893UVrzdfB20dz+G9pM2lE5NK/b/zfF7UlIjg'\ 27 | 'I9oR9w2+YaNZE/fmuHpH94Gx/Ptlwxb2tmdEReA8DPsnHMIML3ltcpJrwgVdTJEAAz1JnARx' 28 | 29 | key2 = 30 | 'AAAAB3NzaC1yc2EAAAADAQABAAABAQCySLKbpFRGCrKU/N6jNVB8vZLzexKbkq2bXPRKUakmf8q'\ 31 | 'rSQI9Bl1C8+6//uKpe909DrZzEkJzPC9BgpNnWtJ25SxHogKb1SybAk0OFc61X7wl1knoo+OcuW'\ 32 | '6Moi0vpNiUGy2VnM0nyecLoQxggvnj1392uoMdS4VY71PGdcBac7p9IwAwYxlsuFEKRcfKisJAH'\ 33 | 'DEblgSFyC9lLMMjTSxxKn8s5AaR1h+Lb3Kwibd7ikvIgYRybTbD12FtQRxuWZBVm39CM3539gT6'\ 34 | '514IaYyYVDyIEFDyGjK2UV27ah56jMaRFGX4IIh2gH5P2XaV7As5p8RPYoWwf+pCz19mrPd/' 35 | 36 | key3 = 37 | 'AAAAB3NzaC1yc2EAAAABJQAAAQEAmHEBrhklpHTYHVWKthuP6eUtV+60EZ+z2tLiavANwaDFbo8'\ 38 | '7y+aAm+pp8eDeaY/HNfKdZv75D98Ogcx4R4or2foYfpA2xuCH9oCYJi2G0VKCQgJRF98OeENtOJ'\ 39 | 'M2ricQuWftG8LIpeosP1j/WJjh7HIIRZDz5Mvqef8tDLuAW/wYp+a+fvVDMhCcYG/DXXK8J6fpj'\ 40 | 'aeZdQpZihCgc/r7ZpWUM58zbAqT8HzBnd9d974RvOuIzViiZ7gmCFDghURsMIbUVGK6ChoPWvAr'\ 41 | 'A93NrkbVBBgz0JCty8z4T03K9RJSL6aLyKaW0FWG1yahy2q+zZkXLBdeyEilo8TbaT6dVw==' 42 | 43 | key2_priv = [ 44 | '-----BEGIN RSA PRIVATE KEY-----', 45 | 'MIIEpAIBAAKCAQEAskiym6RURgqylPzeozVQfL2S83sSm5Ktm1z0SlGpJn/Kq0kC', 46 | 'PQZdQvPuv/7iqXvdPQ62cxJCczwvQYKTZ1rSduUsR6ICm9UsmwJNDhXOtV+8JdZJ', 47 | '6KPjnLlujKItL6TYlBstlZzNJ8nnC6EMYIL549d/drqDHUuFWO9TxnXAWnO6fSMA', 48 | 'MGMZbLhRCkXHyorCQBwxG5YEhcgvZSzDI00scSp/LOQGkdYfi29ysIm3e4pLyIGE', 49 | 'cm02w9dhbUEcblmQVZt/QjN+d/YE+udeCGmMmFQ8iBBQ8hoytlFdu2oeeozGkRRl', 50 | '+CCIdoB+T9l2lewLOafET2KFsH/qQs9fZqz3fwIDAQABAoIBAE/QAb1xrJSKl3Xh', 51 | 'Wl4gMP8W8yFzGFpzKKsjyu02b44fqYBSt+DP55Jgl6J2HcyX+ewqmP0c0Ii8Cb+/', 52 | 'D/Q2EYBOiisrWRWgMk7Wkd5bXuWNjTI3I3E1ZWE1Fkt5EteAacCsBhUzVBia54cq', 53 | 'Ots951bbk2F4j9fehjzRL2TqNAmJhEjIuPcTsUsLoireGVWuynG/sUOMqp59kf5x', 54 | 'JyOBr/00h5jFvAdjaptLVDFWrn9lwtyoSrLvbU+gK8Gjk2843vL4G04C++fdEfjs', 55 | 'WXj3pEPv/EluXOVJ8oMGPSKAY/H6dKfqeVtjK9Ncxwww/MTxseU4N0OudOMn7OLI', 56 | 'j9IOvjkCgYEA2C7xxHxE8TP0tfB2EEod518CiM0P8Pg3z/Wnz07MncjfjmwN9T0S', 57 | 'dIrolJUNe7By4t8SmF+aKgIeIsm7eVmpnlixkhPtgypgO7Z/rub32W8wNDHtEbuj', 58 | 'jTV3Z8yLoXD801M/hFkJ0tG2U0qYQ8ROBQa+Ihae8j3okY+I1Lq4XcMCgYEA0x7L', 59 | 'fIBlP/4VzI2WwSC9RNaO+0jy3ZM74y7jPHBMjqHUznNJ/SXTVJhYCHtRyzKZz7sD', 60 | 'BvSAfHYTyWmC7Dhu8Cpqz0tqEAuM0VajgNaw5+2RqKyaQtY/bsbVMfMvBY3+6qk5', 61 | 'lvUyaVM3uRLHbuvXpAK2JgOOyji1EMKnpLrIt5UCgYEAqCo8X3/bkVW9MhpPfPRq', 62 | 'tqStsAT0NZqgr+CEHTtK6CJt5LghU3eid43mxk38Iw9rDxg/utADeFIVZzJN52Pc', 63 | 'EhUkbGGcDMBWA50/TarVegqIENIVfAnee+XvcIsowvjFcw37BtTMU3ZWwgvwziZS', 64 | 'Go7YMGQwWHfYBgMFiZWF/UkCgYB5CLqYEfP6D+znbHT1G5Pmlys5nMS/it1WjVbx', 65 | 'G2CIlPavtSDB5KGXag9uLWTjHYtYsFo37oyKzhbh7X+FdYUEYw0A8rdHo5eDnCv4', 66 | 'fRzGmkhbbzixAKs1EwC+tjBK+vEeDw5ZIRFZmL/ldoKncMYb3QIYIQoHnSMRDMeX', 67 | 'hQ31UQKBgQCgfC3GjleXWYBVzQihvVdCToM6CGOljzXNcWhqroBhkKACwFXMTvGB', 68 | 'Dx7Mn9rpvnJysHHaAzZVgGan3Bd1qDyDWchZXD5vERgzy84xV6oAPriuvMzOTCDD', 69 | 'miAKI9hX5GxD4lWMFvxEsNv0KEL7O2TA7xFRPY4u5HD+pyF/oYLXgA==', 70 | '-----END RSA PRIVATE KEY-----', 71 | ].join("\n") 72 | 73 | group 'bob' 74 | 75 | user 'bob' do 76 | manage_home true 77 | home '/home/bob' 78 | gid 'bob' 79 | end 80 | 81 | group 'bob2' 82 | 83 | user 'bob2' do 84 | manage_home true 85 | home '/home/bob2' 86 | gid 'bob2' 87 | end 88 | 89 | group 'alice' 90 | 91 | user 'alice' do 92 | manage_home true 93 | home '/home/alice' 94 | gid 'alice' 95 | end 96 | 97 | ssh_authorize_key 'bob@acme.com' do 98 | keytype 'ssh-rsa' 99 | key key1 100 | user 'bob' 101 | only_if true.to_s 102 | end 103 | 104 | ssh_authorize_key 'bob@home.com' do 105 | key key2 106 | comment 'bob@home.com comment' 107 | user 'bob' 108 | end 109 | 110 | ssh_authorize_key 'bob@home3.com' do 111 | key key3 112 | user 'bob' 113 | not_if true.to_s 114 | end 115 | 116 | # bob2: Same as bob but keys in reverse order 117 | 118 | ssh_authorize_key 'bob@home.com' do 119 | key key2 120 | comment 'bob@home.com comment' 121 | user 'bob2' 122 | end 123 | 124 | ssh_authorize_key 'bob@acme.com' do 125 | keytype 'ssh-rsa' 126 | key key1 127 | user 'bob2' 128 | end 129 | 130 | ssh_authorize_key 'alice@acme.com' do 131 | key key2 132 | user 'alice' 133 | options( 134 | 'no-port-forwarding' => true, 135 | 'no-agent-forwarding' => true, 136 | 'no-X11-forwarding' => true, 137 | command: 138 | 'echo \'Please login as the user "bob" rather than the user "alice".\''\ 139 | ';echo;sleep 10' 140 | ) 141 | end 142 | 143 | directory '/root/.ssh' do 144 | mode '00700' 145 | end 146 | 147 | file '/root/.ssh/key2' do 148 | mode '00600' 149 | content key2_priv 150 | sensitive true 151 | end 152 | 153 | file 'bob-subscribe-test' do 154 | path '/home/bob/bob-subscribe-test.txt' 155 | mode '00600' 156 | owner 'bob' 157 | group 'bob' 158 | content "Test file for subscribe to ssh_authorize_key 'bob@acme.com'." 159 | action :nothing 160 | subscribes :create, 'template[/home/bob/.ssh/authorized_keys]', :immediately 161 | end 162 | -------------------------------------------------------------------------------- /test/integration/default/bats/bob.bats: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bats 2 | 3 | @test "authenticates bob user with key2" { 4 | ssh \ 5 | -o UserKnownHostsFile=/dev/null \ 6 | -o StrictHostKeyChecking=no \ 7 | -o BatchMode=yes \ 8 | -i /root/.ssh/key2 \ 9 | bob@127.0.0.1 true 10 | } 11 | 12 | @test "authenticates bob2 user with key2" { 13 | ssh \ 14 | -o UserKnownHostsFile=/dev/null \ 15 | -o StrictHostKeyChecking=no \ 16 | -o BatchMode=yes \ 17 | -i /root/.ssh/key2 \ 18 | bob2@127.0.0.1 true 19 | } 20 | -------------------------------------------------------------------------------- /test/integration/default/serverspec/Gemfile: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # -*- mode: ruby -*- 3 | # vi: set ft=ruby : 4 | 5 | source 'https://rubygems.org' 6 | 7 | gem 'serverspec', '~> 2.0' 8 | -------------------------------------------------------------------------------- /test/integration/default/serverspec/alice_spec.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Author:: Xabier de Zuazo () 4 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 5 | # License:: Apache License, Version 2.0 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | 20 | require 'spec_helper' 21 | 22 | describe file('/home/alice/.ssh') do 23 | it { should be_directory } 24 | it { should be_owned_by 'alice' } 25 | it { should be_grouped_into 'alice' } 26 | it { should be_mode 700 } 27 | end 28 | 29 | content = [ 30 | '# Generated by Chef', 31 | 'no-port-forwarding,no-agent-forwarding,no-X11-forwarding,'\ 32 | 'command="echo \'Please login as the user \"bob\" rather than the user '\ 33 | '\"alice\".\';echo;sleep 10" '\ 34 | 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCySLKbpFRGCrKU/N6jNVB8vZLzexKbkq2bXPR'\ 35 | 'KUakmf8qrSQI9Bl1C8+6//uKpe909DrZzEkJzPC9BgpNnWtJ25SxHogKb1SybAk0OFc61X7wl1k'\ 36 | 'noo+OcuW6Moi0vpNiUGy2VnM0nyecLoQxggvnj1392uoMdS4VY71PGdcBac7p9IwAwYxlsuFEKR'\ 37 | 'cfKisJAHDEblgSFyC9lLMMjTSxxKn8s5AaR1h+Lb3Kwibd7ikvIgYRybTbD12FtQRxuWZBVm39C'\ 38 | 'M3539gT6514IaYyYVDyIEFDyGjK2UV27ah56jMaRFGX4IIh2gH5P2XaV7As5p8RPYoWwf+pCz19'\ 39 | 'mrPd/ alice@acme.com', 40 | ].join("\n") << "\n" 41 | 42 | describe file('/home/alice/.ssh/authorized_keys') do 43 | it { should be_file } 44 | it { should be_owned_by 'alice' } 45 | it { should be_grouped_into 'alice' } 46 | it { should be_mode 600 } 47 | its(:content) { should eq content } 48 | end 49 | -------------------------------------------------------------------------------- /test/integration/default/serverspec/bob_spec.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Author:: Xabier de Zuazo () 4 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 5 | # License:: Apache License, Version 2.0 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | 20 | require 'spec_helper' 21 | 22 | describe file('/home/bob/.ssh') do 23 | it { should be_directory } 24 | it { should be_owned_by 'bob' } 25 | it { should be_grouped_into 'bob' } 26 | it { should be_mode 700 } 27 | end 28 | 29 | content = [ 30 | '# Generated by Chef', 31 | 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCctNyRouVDhzjiP+u3R2+C0nD4VgsRgN9rOiz'\ 32 | 'D2ePBrf8508VR5envsmEY5oF+TM3k/wb2xBY45KXOu9yQjQi9RcCYvrCAu3wPTrx07vRetkDIvs'\ 33 | '/O383zQQanrHMGckNzh83uwDU4JcJqBP2EwkTMUqlk6xyrGuQyjmWFKWjjUUkmHFII5azAh+9bp'\ 34 | '4OjULE9h9fy4Y3ZOxHMrHuC5AjkWhvy88ItmGBf0sj0iW0893UVrzdfB20dz+G9pM2lE5NK/b/z'\ 35 | 'fF7UlIjgI9oR9w2+YaNZE/fmuHpH94Gx/Ptlwxb2tmdEReA8DPsnHMIML3ltcpJrwgVdTJEAAz1'\ 36 | 'JnARx bob@acme.com', 37 | 'ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCySLKbpFRGCrKU/N6jNVB8vZLzexKbkq2bXPR'\ 38 | 'KUakmf8qrSQI9Bl1C8+6//uKpe909DrZzEkJzPC9BgpNnWtJ25SxHogKb1SybAk0OFc61X7wl1k'\ 39 | 'noo+OcuW6Moi0vpNiUGy2VnM0nyecLoQxggvnj1392uoMdS4VY71PGdcBac7p9IwAwYxlsuFEKR'\ 40 | 'cfKisJAHDEblgSFyC9lLMMjTSxxKn8s5AaR1h+Lb3Kwibd7ikvIgYRybTbD12FtQRxuWZBVm39C'\ 41 | 'M3539gT6514IaYyYVDyIEFDyGjK2UV27ah56jMaRFGX4IIh2gH5P2XaV7As5p8RPYoWwf+pCz19'\ 42 | 'mrPd/ bob@home.com comment', 43 | ].join("\n") << "\n" 44 | 45 | describe file('/home/bob/.ssh/authorized_keys') do 46 | it { should be_file } 47 | it { should be_owned_by 'bob' } 48 | it { should be_grouped_into 'bob' } 49 | it { should be_mode 600 } 50 | its(:content) { should eq content } 51 | end 52 | 53 | describe file('/home/bob2/.ssh') do 54 | it { should be_directory } 55 | it { should be_owned_by 'bob2' } 56 | it { should be_grouped_into 'bob2' } 57 | it { should be_mode 700 } 58 | end 59 | 60 | describe file('/home/bob2/.ssh/authorized_keys') do 61 | it { should be_file } 62 | it { should be_owned_by 'bob2' } 63 | it { should be_grouped_into 'bob2' } 64 | it { should be_mode 600 } 65 | its(:content) { should eq content } 66 | end 67 | 68 | subscribe_file_content = 69 | "Test file for subscribe to ssh_authorize_key 'bob@acme.com'." 70 | 71 | describe file('/home/bob/bob-subscribe-test.txt') do 72 | it { should be_file } 73 | it { should be_owned_by 'bob' } 74 | it { should be_grouped_into 'bob' } 75 | it { should be_mode 600 } 76 | its(:content) { should eq subscribe_file_content } 77 | end 78 | -------------------------------------------------------------------------------- /test/integration/default/serverspec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Author:: Xabier de Zuazo () 4 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 5 | # License:: Apache License, Version 2.0 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | 20 | require 'serverspec' 21 | 22 | # Set backend type 23 | set :backend, :exec 24 | -------------------------------------------------------------------------------- /test/unit/resource_helpers_spec.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Author:: Xabier de Zuazo () 4 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 5 | # License:: Apache License, Version 2.0 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | 20 | require 'spec_helper' 21 | require 'resource_helpers.rb' 22 | 23 | describe SshAuthorizedKeysCookbook::ResourceHelpers, order: :random do 24 | let(:helpers_class) do 25 | klass = Class.new 26 | klass.send(:include, described_class) 27 | klass 28 | end 29 | let(:helpers) { helpers_class.new } 30 | let(:node) do 31 | node = Chef::Node.new 32 | Dir.glob("#{::File.dirname(__FILE__)}/../../attributes/*.rb") do |f| 33 | node.from_file(f) 34 | end 35 | node 36 | end 37 | before { allow(helpers).to receive(:node).and_return(node) } 38 | 39 | context '#assert_user' do 40 | it 'does not raise an exception for valid strings' do 41 | expect { helpers.assert_user('bob') }.to_not raise_error 42 | end 43 | 44 | it 'raises an exception for empty string' do 45 | expect { helpers.assert_user('') } 46 | .to raise_error(/ssh_authorize_key: user parameter must be a valid/) 47 | end 48 | 49 | it 'raises an exception for wrong types' do 50 | expect { helpers.assert_user(Object.new) } 51 | .to raise_error(/ssh_authorize_key: user parameter must be a valid/) 52 | end 53 | end # context #assert_user 54 | 55 | context '#assert_key' do 56 | let(:key) do 57 | 'AAAAB3NzaC1yc2EAAAADAQABAAABAQCsH9DvJxgTglpJtCzKzo+WcqLf5H+IR2Iv0ntBgxc'\ 58 | 'huMPpFJKSuzBjgLFzq16xqXkBuGh9hL18LjIbMNH1GXLCfgnuU7S6HF9w4FFDAYY+EUH/M8'\ 59 | 'n99jWiNyk/0K1ruvLzJJM0DBFzZ64fHtEx0YcOVl0pw0ZBz75nJuEh2o1VaABqmQA+FpjrR'\ 60 | '+sId/OqXusVjqxdeV1fOf46RCL9Y4tO41k7F358UCywp2Zhnas51QaER+mh6imb/H7YwcfC'\ 61 | 'ZmJ/BB13G7iwvlmi5ANRCD/NNX1DBqWsG2UYVO06ZEg3LoRTF1pmLp2cuvObdz36AQgk8IJ'\ 62 | 'Uop9RlH/5vrofLF3p' 63 | end 64 | 65 | it 'does not raise an exception for valid keys' do 66 | expect { helpers.assert_key(key) }.to_not raise_error 67 | end 68 | 69 | it 'raises an exception for incomplete keys' do 70 | expect { helpers.assert_key(key[0..-2]) } 71 | .to raise_error(/ssh_authorize_key: key parameter must be a valid/) 72 | end 73 | 74 | it 'raises an exception for wrong types' do 75 | expect { helpers.assert_key(Object.new) } 76 | .to raise_error(/ssh_authorize_key: key parameter must be a valid/) 77 | end 78 | end # context #assert_key 79 | 80 | context '#assert_keytype' do 81 | %w( 82 | ecdsa-sha2-nistp256 83 | ecdsa-sha2-nistp384 84 | ecdsa-sha2-nistp521 85 | ssh-ed25519 86 | ssh-dss 87 | ssh-rsa 88 | ).each do |keytype| 89 | it "does not raise an exception for #{keytype.inspect}" do 90 | expect { helpers.assert_keytype(keytype) }.to_not raise_error 91 | end 92 | end # each keytype 93 | 94 | [ 95 | nil, 96 | 1, 97 | Object.new, 98 | 'ssh-bad', 99 | ].each do |keytype| 100 | it "raises an exception for #{keytype.inspect}" do 101 | expect { helpers.assert_keytype(keytype) } 102 | .to raise_error(/^ssh_authorize_key: keytype parameter must be/) 103 | end 104 | end # each keytype 105 | end # context #assert_keytype 106 | 107 | context '#assert_comment' do 108 | it 'does not raise an exception for valid comments' do 109 | expect { helpers.assert_comment('bob@acme.com') }.to_not raise_error 110 | end 111 | 112 | it 'raises an exception for wrong comments with new lines' do 113 | expect { helpers.assert_comment("comment\n with new line") } 114 | .to raise_error(/^ssh_authorize_key: comment parameter must be/) 115 | end 116 | 117 | it 'raises an exception for wrong types' do 118 | expect { helpers.assert_comment(Object.new) } 119 | .to raise_error(/^ssh_authorize_key: comment parameter must be/) 120 | end 121 | end # context #assert_comment 122 | 123 | context '#user_home' do 124 | let(:home) { '/specialhome/bob' } 125 | let(:user) do 126 | require 'etc' 127 | Etc::Passwd.new('bob', 'x', 1000, 1000, 'bob,,,', home) 128 | end 129 | 130 | it 'returns system user home' do 131 | expect(Etc).to receive(:getpwnam).with('bob').and_return(user) 132 | expect(helpers.user_home('bob')).to eq(home) 133 | end 134 | 135 | context 'when user does not exist' do 136 | before do 137 | expect(Etc).to receive(:getpwnam).with('bob').and_raise(ArgumentError.new) 138 | allow(Chef::Log).to receive(:warn) 139 | end 140 | 141 | it 'prints a Chef warning' do 142 | expect(Chef::Log).to receive(:warn) 143 | .with(/^ssh_authorize_key: User .* not found at compile time/).once 144 | helpers.user_home('bob') 145 | end 146 | 147 | it 'returns /home/${user} path' do 148 | expect(helpers.user_home('bob')).to eq('/home/bob') 149 | end 150 | end 151 | end 152 | 153 | context '#user_group' do 154 | let(:user) do 155 | require 'etc' 156 | Etc::Passwd.new('bob', 'x', 1000, 1000, 'bob,,,') 157 | end 158 | 159 | it 'returns system user group' do 160 | expect(Etc).to receive(:getpwnam).with('bob').and_return(user) 161 | expect(helpers.user_group('bob')).to eq(1000) 162 | end 163 | 164 | context 'when user does not exist' do 165 | before do 166 | expect(Etc).to receive(:getpwnam).with('bob').and_raise(ArgumentError.new) 167 | allow(Chef::Log).to receive(:warn) 168 | end 169 | 170 | it 'prints a Chef warning' do 171 | expect(Chef::Log).to receive(:warn) 172 | .with(/^ssh_authorize_key: User .* not found at compile time/).once 173 | helpers.user_group('bob') 174 | end 175 | 176 | it 'returns ${user}' do 177 | expect(helpers.user_group('bob')).to eq('bob') 178 | end 179 | end 180 | end 181 | end 182 | -------------------------------------------------------------------------------- /test/unit/template_helpers_spec.rb: -------------------------------------------------------------------------------- 1 | # encoding: UTF-8 2 | # 3 | # Author:: Xabier de Zuazo () 4 | # Copyright:: Copyright (c) 2015 Onddo Labs, SL. 5 | # License:: Apache License, Version 2.0 6 | # 7 | # Licensed under the Apache License, Version 2.0 (the "License"); 8 | # you may not use this file except in compliance with the License. 9 | # You may obtain a copy of the License at 10 | # 11 | # http://www.apache.org/licenses/LICENSE-2.0 12 | # 13 | # Unless required by applicable law or agreed to in writing, software 14 | # distributed under the License is distributed on an "AS IS" BASIS, 15 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | # See the License for the specific language governing permissions and 17 | # limitations under the License. 18 | # 19 | 20 | require 'spec_helper' 21 | require 'template_helpers.rb' 22 | 23 | describe SshAuthorizedKeysCookbook::TemplateHelpers, order: :random do 24 | let(:helpers_class) do 25 | klass = Class.new 26 | klass.send(:include, described_class) 27 | klass 28 | end 29 | let(:helpers) { helpers_class.new } 30 | 31 | context '#render_option_value' do 32 | option = 'option_name' 33 | { 34 | true => option, 35 | 1 => %(#{option}="1"), 36 | 'NAME=value 1' => %(#{option}="NAME=value 1"), 37 | 'NAME="value"' => %(#{option}="NAME=\\"value\\""), 38 | 'NAME="va\nlue"' => %(#{option}="NAME=\\"va\\\\nlue\\""), 39 | }.each do |value, result| 40 | it "returns #{result.inspect} for #{value.inspect}" do 41 | expect(helpers.render_option_value(option, value)).to eq(result) 42 | end 43 | end # each value, string 44 | end # context #render_keys 45 | 46 | context '#render_options' do 47 | let(:options) do 48 | { 49 | 'no-agent-forwarding' => true, 50 | 'environment' => 'DISPLAY=:0', 51 | } 52 | end 53 | it 'renders options correctly' do 54 | result = 'no-agent-forwarding,environment="DISPLAY=:0"' 55 | expect(helpers.render_options(options)).to eq(result) 56 | end 57 | end 58 | 59 | context '#render_keys' do 60 | it 'merges keytype, key and comment as a string' do 61 | expect(helpers.render_key('A', 'B', 'C')).to eq('A B C') 62 | end 63 | end # context #render_keys 64 | end 65 | --------------------------------------------------------------------------------