aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitignore1
-rw-r--r--.pdkignore1
-rw-r--r--.rubocop.yml11
-rw-r--r--.sync.yml21
-rw-r--r--.travis.yml3
-rw-r--r--README.md102
-rw-r--r--REFERENCE.md174
-rw-r--r--Rakefile69
-rw-r--r--lib/puppet/provider/ssh_authorized_key/parsed.rb103
-rw-r--r--lib/puppet/provider/sshkey/parsed.rb47
-rw-r--r--lib/puppet/type/ssh_authorized_key.rb26
-rw-r--r--lib/puppet/type/sshkey.rb26
-rw-r--r--metadata.json2
-rw-r--r--spec/acceptance/nodesets/default.yml19
-rw-r--r--spec/acceptance/tests/resource/ssh_authorized_key/create.rb39
-rw-r--r--spec/acceptance/tests/resource/ssh_authorized_key/create_spec.rb36
-rw-r--r--spec/acceptance/tests/resource/ssh_authorized_key/destroy.rb42
-rw-r--r--spec/acceptance/tests/resource/ssh_authorized_key/destroy_spec.rb38
-rw-r--r--spec/acceptance/tests/resource/ssh_authorized_key/modify.rb43
-rw-r--r--spec/acceptance/tests/resource/ssh_authorized_key/modify_spec.rb36
-rw-r--r--spec/acceptance/tests/resource/ssh_authorized_key/query.rb35
-rw-r--r--spec/acceptance/tests/resource/sshkey/create.rb77
-rw-r--r--spec/acceptance/tests/resource/sshkey/create_spec.rb81
-rw-r--r--spec/integration/provider/ssh_authorized_key_spec.rb151
-rw-r--r--spec/integration/provider/sshkey_spec.rb177
-rw-r--r--spec/lib/puppet_spec/compiler.rb12
-rw-r--r--spec/spec_helper_acceptance.rb26
-rw-r--r--spec/spec_helper_local.rb4
-rw-r--r--spec/unit/provider/sshkey/parsed_spec.rb57
-rw-r--r--spec/unit/type/ssh_authorized_key_spec.rb228
-rw-r--r--spec/unit/type/sshkey_spec.rb43
31 files changed, 965 insertions, 765 deletions
diff --git a/.gitignore b/.gitignore
index 49bc2a4..650022e 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,3 +1,4 @@
+.git/
.*.sw[op]
.metadata
.yardoc
diff --git a/.pdkignore b/.pdkignore
index 49bc2a4..650022e 100644
--- a/.pdkignore
+++ b/.pdkignore
@@ -1,3 +1,4 @@
+.git/
.*.sw[op]
.metadata
.yardoc
diff --git a/.rubocop.yml b/.rubocop.yml
index 7ed6225..e4664cb 100644
--- a/.rubocop.yml
+++ b/.rubocop.yml
@@ -66,11 +66,16 @@ Style/TrailingCommaInLiteral:
Style/SymbolArray:
Description: Using percent style obscures symbolic intent of array's contents.
EnforcedStyle: brackets
-RSpec/MessageSpies:
- EnforcedStyle: receive
+RSpec/NamedSubject:
+ Enabled: false
Style/Documentation:
Exclude:
- lib/puppet/parser/functions/**/*
+ - spec/**/*
+ - lib/puppet/type/**
+ - lib/puppet/provider/**
+RSpec/MessageSpies:
+ EnforcedStyle: receive
Style/WordArray:
EnforcedStyle: brackets
Style/CollectionMethods:
@@ -81,6 +86,8 @@ Style/StringMethods:
Enabled: true
Layout/EndOfLine:
Enabled: false
+Layout/IndentHeredoc:
+ Enabled: false
Metrics/AbcSize:
Enabled: false
Metrics/BlockLength:
diff --git a/.sync.yml b/.sync.yml
index d608181..e4407f1 100644
--- a/.sync.yml
+++ b/.sync.yml
@@ -27,12 +27,21 @@ Rakefile:
requires:
- puppet-lint/tasks/puppet-lint
-#.rubocop.yml:
-# default_configs:
-# Layout/IndentHeredoc:
-# Enabled: false
-# RSpec/NamedSubject:
-# Enabled: false
+.rubocop.yml:
+ default_configs:
+ RSpec/NamedSubject:
+ Enabled: false
+ Style/Documentation:
+ Exclude:
+ - lib/puppet/parser/functions/**/*
+ - spec/**/*
+ - lib/puppet/type/**
+ - lib/puppet/provider/**
.gitlab-ci.yml:
delete: true
+
+.travis.yml:
+ remove_includes:
+ - env: PUPPET_GEM_VERSION="~> 4.0" CHECK=parallel_spec
+ rvm: 2.1.9
diff --git a/.travis.yml b/.travis.yml
index 81f77dd..2c6edb7 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -24,9 +24,6 @@ matrix:
env: CHECK="syntax lint metadata_lint check:symlinks check:git_ignore check:dot_underscore check:test_file rubocop"
-
env: CHECK=parallel_spec
- -
- env: PUPPET_GEM_VERSION="~> 4.0" CHECK=parallel_spec
- rvm: 2.1.9
branches:
only:
- master
diff --git a/README.md b/README.md
index 09b25ad..9c6bef0 100644
--- a/README.md
+++ b/README.md
@@ -1,95 +1,61 @@
# sshkeys_core
-Welcome to your new module. A short overview of the generated parts can be found in the PDK documentation at https://puppet.com/pdk/latest/pdk_generating_modules.html .
-
-The README template below provides a starting point with details about what information to include in your README.
-
-
-
-
-
-
-
-#### Table of Contents
+## Table of Contents
1. [Description](#description)
-2. [Setup - The basics of getting started with sshkeys_core](#setup)
- * [What sshkeys_core affects](#what-sshkeys_core-affects)
- * [Setup requirements](#setup-requirements)
- * [Beginning with sshkeys_core](#beginning-with-sshkeys_core)
-3. [Usage - Configuration options and additional functionality](#usage)
-4. [Limitations - OS compatibility, etc.](#limitations)
-5. [Development - Guide for contributing to the module](#development)
+2. [Usage - Configuration options and additional functionality](#usage)
+3. [Reference - User documentation](#reference)
+4. [Development - Guide for contributing to the module](#development)
## Description
-Briefly tell users why they might want to use your module. Explain what your module does and what kind of problems users can solve with it.
-
-This should be a fairly short description helps the user decide if your module is what they want.
-
-
-## Setup
-
-### What sshkeys_core affects **OPTIONAL**
-
-If it's obvious what your module touches, you can skip this section. For example, folks can probably figure out that your mysql_instance module affects their MySQL instances.
-
-If there's more that they should know about, though, this is the place to mention:
-
-* Files, packages, services, or operations that the module will alter, impact, or execute.
-* Dependencies that your module automatically installs.
-* Warnings or other important notices.
+Manage SSH `authorized_keys`, and `ssh_known_hosts` files.
-### Setup Requirements **OPTIONAL**
-
-If your module requires anything extra before setting up (pluginsync enabled, another module, etc.), mention it here.
+## Usage
-If your most recent release breaks compatibility or requires particular steps for upgrading, you might want to include an additional "Upgrading" section here.
+To manage an authorized key for a user:
-### Beginning with sshkeys_core
+```
+ssh_authorized_key { 'nick@magpie.example.com':
+ ensure => present,
+ user => 'nick',
+ type => 'ssh-rsa',
+ key => 'AAAAB3Nza[...]qXfdaQ==',
+}
+```
-The very basic steps needed for a user to get the module up and running. This can include setup steps, if necessary, or it can be an example of the most basic use of the module.
+To manage a known hosts file entry:
-## Usage
+```
+sshkey { 'github.com':
+ ensure => present,
+ type => 'ssh-rsa',
+ key => 'AAAAB3Nza[...]UFFAaQ==',
+}
+```
-Include usage examples for common use cases in the **Usage** section. Show your users how to use your module to solve problems, and be sure to include code examples. Include three to five examples of the most important or common tasks a user can accomplish with your module. Show users how to accomplish more complex tasks that involve different types, classes, and functions working in tandem.
+More details cana be found in the `REFERENCE.md` file.
## Reference
-This section is deprecated. Instead, add reference information to your code as Puppet Strings comments, and then use Strings to generate a REFERENCE.md in your module. For details on how to add code comments and generate documentation with Strings, see the Puppet Strings [documentation](https://puppet.com/docs/puppet/latest/puppet_strings.html) and [style guide](https://puppet.com/docs/puppet/latest/puppet_strings_style.html)
-
-If you aren't ready to use Strings yet, manually create a REFERENCE.md in the root of your module directory and list out each of your module's classes, defined types, facts, functions, Puppet tasks, task plans, and resource types and providers, along with the parameters for each.
+Please see `REFERENCE.md` for the reference documentation.
-For each element (class, defined type, function, and so on), list:
+This module is documented using Puppet Strings.
- * The data type, if applicable.
- * A description of what the element does.
- * Valid values, if the data type doesn't make it obvious.
- * Default value, if any.
-
-For example:
+For a quick primer on how Strings works, please see [this blog post](https://puppet.com/blog/using-puppet-strings-generate-great-documentation-puppet-modules) or the [README.md](https://github.com/puppetlabs/puppet-strings/blob/master/README.md) for Puppet Strings.
+To generate documentation locally, run
```
-### `pet::cat`
-
-#### Parameters
-
-##### `meow`
-
-Enables vocalization in your cat. Valid options: 'string'.
-
-Default: 'medium-loud'.
+bundle install
+bundle exec puppet strings generate ./lib/**/*.rb
```
-
-## Limitations
-
-In the Limitations section, list any incompatibilities, known issues, or other warnings.
+This command will create a browsable `\_index.html` file in the `doc` directory. The references available here are all generated from YARD-style comments embedded in the code base. When any development happens on this module, the impacted documentation should also be updated.
## Development
-In the Development section, tell other users the ground rules for contributing to your project and how they should submit their work.
+Puppet Labs modules on the Puppet Forge are open projects, and community contributions are essential for keeping them great. We can't access the huge number of platforms and myriad of hardware, software, and deployment configurations that Puppet is intended to serve.
-## Release Notes/Contributors/Etc. **Optional**
+We want to keep it as easy as possible to contribute changes so that our modules work in your environment. There are a few guidelines that we need contributors to follow so that we can have a chance of keeping on top of things.
-If you aren't using changelog, put your release notes here (though you should consider using changelog). You can also add any additional sections you feel are necessary or important to include here. Please use the `## ` header.
+For more information, see our [module contribution guide.](https://docs.puppetlabs.com/forge/contributing.html)
diff --git a/REFERENCE.md b/REFERENCE.md
new file mode 100644
index 0000000..b72e9ee
--- /dev/null
+++ b/REFERENCE.md
@@ -0,0 +1,174 @@
+# Reference
+
+## Resource types
+* [`ssh_authorized_key`](#ssh_authorized_key): Manages SSH authorized keys. Currently only type 2 keys are supported. In their native habitat, SSH keys usually appear as a single long lin
+* [`sshkey`](#sshkey): Installs and manages ssh host keys. By default, this type will install keys into `/etc/ssh/ssh_known_hosts`. To manage ssh keys in a differe
+## Resource types
+
+### ssh_authorized_key
+
+Manages SSH authorized keys. Currently only type 2 keys are supported.
+
+In their native habitat, SSH keys usually appear as a single long line, in
+the format `<TYPE> <KEY> <NAME/COMMENT>`. This resource type requires you
+to split that line into several attributes. Thus, a key that appears in
+your `~/.ssh/id_rsa.pub` file like this...
+
+ ssh-rsa AAAAB3Nza[...]qXfdaQ== nick@magpie.example.com
+
+...would translate to the following resource:
+
+ ssh_authorized_key { 'nick@magpie.example.com':
+ ensure => present,
+ user => 'nick',
+ type => 'ssh-rsa',
+ key => 'AAAAB3Nza[...]qXfdaQ==',
+ }
+
+To ensure that only the currently approved keys are present, you can purge
+unmanaged SSH keys on a per-user basis. Do this with the `user` resource
+type's `purge_ssh_keys` attribute:
+
+ user { 'nick':
+ ensure => present,
+ purge_ssh_keys => true,
+ }
+
+This will remove any keys in `~/.ssh/authorized_keys` that aren't being
+managed with `ssh_authorized_key` resources. See the documentation of the
+`user` type for more details.
+
+**Autorequires:** If Puppet is managing the user account in which this
+SSH key should be installed, the `ssh_authorized_key` resource will autorequire
+that user.
+
+
+#### Properties
+
+The following properties are available in the `ssh_authorized_key` type.
+
+##### `ensure`
+
+Valid values: present, absent
+
+The basic property that the resource should be in.
+
+Default value: present
+
+##### `type`
+
+Valid values: ssh-dss, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384, ecdsa-sha2-nistp521, ssh-ed25519, dsa, ed25519, rsa
+
+Aliases: "dsa"=>"ssh-dss", "ed25519"=>"ssh-ed25519", "rsa"=>"ssh-rsa"
+
+The encryption type used.
+
+##### `key`
+
+The public key itself; generally a long string of hex characters. The `key`
+attribute may not contain whitespace.
+
+Make sure to omit the following in this attribute (and specify them in
+other attributes):
+
+* Key headers, such as 'ssh-rsa' --- put these in the `type` attribute.
+* Key identifiers / comments, such as 'joe@joescomputer.local' --- put these in
+ the `name` attribute/resource title.
+
+##### `user`
+
+The user account in which the SSH key should be installed. The resource
+will autorequire this user if it is being managed as a `user` resource.
+
+##### `target`
+
+The absolute filename in which to store the SSH key. This
+property is optional and should be used only in cases where keys
+are stored in a non-standard location, for instance when not in
+`~user/.ssh/authorized_keys`.
+
+Default value: absent
+
+##### `options`
+
+Key options; see sshd(8) for possible values. Multiple values
+should be specified as an array.
+
+#### Parameters
+
+The following parameters are available in the `ssh_authorized_key` type.
+
+##### `name`
+
+namevar
+
+The SSH key comment. This can be anything, and doesn't need to match
+the original comment from the `.pub` file.
+
+Due to internal limitations, this must be unique across all user accounts;
+if you want to specify one key for multiple users, you must use a different
+comment for each instance.
+
+
+### sshkey
+
+Installs and manages ssh host keys. By default, this type will
+install keys into `/etc/ssh/ssh_known_hosts`. To manage ssh keys in a
+different `known_hosts` file, such as a user's personal `known_hosts`,
+pass its path to the `target` parameter. See the `ssh_authorized_key`
+type to manage authorized keys.
+
+
+#### Properties
+
+The following properties are available in the `sshkey` type.
+
+##### `ensure`
+
+Valid values: present, absent
+
+The basic property that the resource should be in.
+
+Default value: present
+
+##### `type`
+
+Valid values: ssh-dss, ssh-ed25519, ssh-rsa, ecdsa-sha2-nistp256, ecdsa-sha2-nistp384, ecdsa-sha2-nistp521, dsa, ed25519, rsa
+
+Aliases: "dsa"=>"ssh-dss", "ed25519"=>"ssh-ed25519", "rsa"=>"ssh-rsa"
+
+The encryption type used. Probably ssh-dss or ssh-rsa.
+
+##### `key`
+
+The key itself; generally a long string of uuencoded characters. The `key`
+attribute may not contain whitespace.
+
+Make sure to omit the following in this attribute (and specify them in
+other attributes):
+
+* Key headers, such as 'ssh-rsa' --- put these in the `type` attribute.
+* Key identifiers / comments, such as 'joescomputer.local' --- put these in
+ the `name` attribute/resource title.
+
+##### `host_aliases`
+
+Any aliases the host might have. Multiple values must be
+specified as an array.
+
+##### `target`
+
+The file in which to store the ssh key. Only used by
+the `parsed` provider.
+
+#### Parameters
+
+The following parameters are available in the `sshkey` type.
+
+##### `name`
+
+namevar
+
+The host name that the key is associated with.
+
+
diff --git a/Rakefile b/Rakefile
index ef5f698..a7c4d68 100644
--- a/Rakefile
+++ b/Rakefile
@@ -1,7 +1,76 @@
require 'puppetlabs_spec_helper/rake_tasks'
require 'puppet-syntax/tasks/puppet-syntax'
require 'puppet_blacksmith/rake_tasks' if Bundler.rubygems.find_name('puppet-blacksmith').any?
+require 'github_changelog_generator/task' if Bundler.rubygems.find_name('github_changelog_generator').any?
require 'puppet-lint/tasks/puppet-lint'
+def changelog_user
+ return unless Rake.application.top_level_tasks.include? "changelog"
+ returnVal = nil || JSON.load(File.read('metadata.json'))['author']
+ raise "unable to find the changelog_user in .sync.yml, or the author in metadata.json" if returnVal.nil?
+ puts "GitHubChangelogGenerator user:#{returnVal}"
+ returnVal
+end
+
+def changelog_project
+ return unless Rake.application.top_level_tasks.include? "changelog"
+ returnVal = nil || JSON.load(File.read('metadata.json'))['name']
+ raise "unable to find the changelog_project in .sync.yml or the name in metadata.json" if returnVal.nil?
+ puts "GitHubChangelogGenerator project:#{returnVal}"
+ returnVal
+end
+
+def changelog_future_release
+ return unless Rake.application.top_level_tasks.include? "changelog"
+ returnVal = JSON.load(File.read('metadata.json'))['version']
+ raise "unable to find the future_release (version) in metadata.json" if returnVal.nil?
+ puts "GitHubChangelogGenerator future_release:#{returnVal}"
+ returnVal
+end
+
PuppetLint.configuration.send('disable_relative')
+if Bundler.rubygems.find_name('github_changelog_generator').any?
+ GitHubChangelogGenerator::RakeTask.new :changelog do |config|
+ raise "Set CHANGELOG_GITHUB_TOKEN environment variable eg 'export CHANGELOG_GITHUB_TOKEN=valid_token_here'" if Rake.application.top_level_tasks.include? "changelog" and ENV['CHANGELOG_GITHUB_TOKEN'].nil?
+ config.user = "#{changelog_user}"
+ config.project = "#{changelog_project}"
+ config.future_release = "#{changelog_future_release}"
+ config.exclude_labels = ['maintenance']
+ config.header = "# Change log\n\nAll notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/) and this project adheres to [Semantic Versioning](http://semver.org)."
+ config.add_pr_wo_labels = true
+ config.issues = false
+ config.merge_prefix = "### UNCATEGORIZED PRS; GO LABEL THEM"
+ config.configure_sections = {
+ "Changed" => {
+ "prefix" => "### Changed",
+ "labels" => ["backwards-incompatible"],
+ },
+ "Added" => {
+ "prefix" => "### Added",
+ "labels" => ["feature", "enhancement"],
+ },
+ "Fixed" => {
+ "prefix" => "### Fixed",
+ "labels" => ["bugfix"],
+ },
+ }
+ end
+else
+ desc 'Generate a Changelog from GitHub'
+ task :changelog do
+ raise <<EOM
+The changelog tasks depends on unreleased features of the github_changelog_generator gem.
+Please manually add it to your .sync.yml for now, and run `pdk update`:
+---
+Gemfile:
+ optional:
+ ':development':
+ - gem: 'github_changelog_generator'
+ git: 'https://github.com/skywinder/github-changelog-generator'
+ ref: '20ee04ba1234e9e83eb2ffb5056e23d641c7a018'
+ condition: "Gem::Version.new(RUBY_VERSION.dup) >= Gem::Version.new('2.2.2')"
+EOM
+ end
+end
+
diff --git a/lib/puppet/provider/ssh_authorized_key/parsed.rb b/lib/puppet/provider/ssh_authorized_key/parsed.rb
index f7ac9f7..02a19eb 100644
--- a/lib/puppet/provider/ssh_authorized_key/parsed.rb
+++ b/lib/puppet/provider/ssh_authorized_key/parsed.rb
@@ -2,44 +2,44 @@ require 'puppet/provider/parsedfile'
Puppet::Type.type(:ssh_authorized_key).provide(
:parsed,
- :parent => Puppet::Provider::ParsedFile,
- :filetype => :flat,
- :default_target => ''
+ parent: Puppet::Provider::ParsedFile,
+ filetype: :flat,
+ default_target: '',
) do
- desc "Parse and generate authorized_keys files for SSH."
+ desc 'Parse and generate authorized_keys files for SSH.'
- text_line :comment, :match => /^\s*#/
- text_line :blank, :match => /^\s*$/
+ text_line :comment, match: %r{^\s*#}
+ text_line :blank, match: %r{^\s*$}
record_line :parsed,
- :fields => %w{options type key name},
- :optional => %w{options},
- :rts => /^\s+/,
- :match => Puppet::Type.type(:ssh_authorized_key).keyline_regex,
- :post_parse => proc { |h|
- h[:name] = "" if h[:name] == :absent
- h[:options] ||= [:absent]
- h[:options] = Puppet::Type::Ssh_authorized_key::ProviderParsed.parse_options(h[:options]) if h[:options].is_a? String
- },
- :pre_gen => proc { |h|
- # if this name was generated, don't write it back to disk
- h[:name] = "" if h[:unnamed]
- h[:options] = [] if h[:options].include?(:absent)
- h[:options] = h[:options].join(',')
- }
+ fields: ['options', 'type', 'key', 'name'],
+ optional: ['options'],
+ rts: %r{^\s+},
+ match: Puppet::Type.type(:ssh_authorized_key).keyline_regex,
+ post_parse: proc { |h|
+ h[:name] = '' if h[:name] == :absent
+ h[:options] ||= [:absent]
+ h[:options] = Puppet::Type::Ssh_authorized_key::ProviderParsed.parse_options(h[:options]) if h[:options].is_a? String
+ },
+ pre_gen: proc { |h|
+ # if this name was generated, don't write it back to disk
+ h[:name] = '' if h[:unnamed]
+ h[:options] = [] if h[:options].include?(:absent)
+ h[:options] = h[:options].join(',')
+ }
record_line :key_v1,
- :fields => %w{options bits exponent modulus name},
- :optional => %w{options},
- :rts => /^\s+/,
- :match => /^(?:(.+) )?(\d+) (\d+) (\d+)(?: (.+))?$/
+ fields: ['options', 'bits', 'exponent', 'modulus', 'name'],
+ optional: ['options'],
+ rts: %r{^\s+},
+ match: %r{^(?:(.+) )?(\d+) (\d+) (\d+)(?: (.+))?$}
def dir_perm
- 0700
+ 0o700
end
def file_perm
- 0600
+ 0o600
end
def user
@@ -48,7 +48,7 @@ Puppet::Type.type(:ssh_authorized_key).provide(
end
def flush
- raise Puppet::Error, "Cannot write SSH authorized keys without user" unless @resource.should(:user)
+ raise Puppet::Error, 'Cannot write SSH authorized keys without user' unless @resource.should(:user)
raise Puppet::Error, "User '#{@resource.should(:user)}' does not exist" unless Puppet::Util.uid(@resource.should(:user))
# ParsedFile usually calls backup_target much later in the flush process,
# but our SUID makes that fail to open filebucket files for writing.
@@ -57,14 +57,14 @@ Puppet::Type.type(:ssh_authorized_key).provide(
self.class.backup_target(target)
Puppet::Util::SUIDManager.asuser(@resource.should(:user)) do
- unless Puppet::FileSystem.exist?(dir = File.dirname(target))
- Puppet.debug "Creating #{dir} as #{@resource.should(:user)}"
- Dir.mkdir(dir, dir_perm)
- end
+ unless Puppet::FileSystem.exist?(dir = File.dirname(target))
+ Puppet.debug "Creating #{dir} as #{@resource.should(:user)}"
+ Dir.mkdir(dir, dir_perm)
+ end
- super
+ super
- File.chmod(file_perm, target)
+ File.chmod(file_perm, target)
end
end
@@ -73,17 +73,18 @@ Puppet::Type.type(:ssh_authorized_key).provide(
def self.parse_options(options)
result = []
scanner = StringScanner.new(options)
- while !scanner.eos?
- scanner.skip(/[ \t]*/)
+ until scanner.eos?
+ scanner.skip(%r{[ \t]*})
# scan a long option
- if out = scanner.scan(/[-a-z0-9A-Z_]+=\".*?[^\\]\"/) or out = scanner.scan(/[-a-z0-9A-Z_]+/)
- result << out
- else
- # found an unscannable token, let's abort
- break
- end
+ out = scanner.scan(%r{[-a-z0-9A-Z_]+=\".*?[^\\]\"}) || scanner.scan(%r{[-a-z0-9A-Z_]+})
+
+ # found an unscannable token, let's abort
+ break unless out
+
+ result << out
+
# eat a comma
- scanner.skip(/[ \t]*,[ \t]*/)
+ scanner.skip(%r{[ \t]*,[ \t]*})
end
result
end
@@ -91,15 +92,13 @@ Puppet::Type.type(:ssh_authorized_key).provide(
def self.prefetch_hook(records)
name_index = 0
records.each do |record|
- if record[:record_type] == :parsed && record[:name].empty?
- record[:unnamed] = true
- # Generate a unique ID for unnamed keys, in case they need purging.
- # If you change this, you have to keep
- # Puppet::Type::User#unknown_keys_in_file in sync! (PUP-3357)
- record[:name] = "#{record[:target]}:unnamed-#{ name_index += 1 }"
- Puppet.debug("generating name for on-disk ssh_authorized_key #{record[:key]}: #{record[:name]}")
- end
+ next unless record[:record_type] == :parsed && record[:name].empty?
+ record[:unnamed] = true
+ # Generate a unique ID for unnamed keys, in case they need purging.
+ # If you change this, you have to keep
+ # Puppet::Type::User#unknown_keys_in_file in sync! (PUP-3357)
+ record[:name] = "#{record[:target]}:unnamed-#{name_index += 1}"
+ Puppet.debug("generating name for on-disk ssh_authorized_key #{record[:key]}: #{record[:name]}")
end
end
end
-
diff --git a/lib/puppet/provider/sshkey/parsed.rb b/lib/puppet/provider/sshkey/parsed.rb
index 1c42aeb..3713df1 100644
--- a/lib/puppet/provider/sshkey/parsed.rb
+++ b/lib/puppet/provider/sshkey/parsed.rb
@@ -2,49 +2,48 @@ require 'puppet/provider/parsedfile'
Puppet::Type.type(:sshkey).provide(
:parsed,
- :parent => Puppet::Provider::ParsedFile,
- :filetype => :flat
+ parent: Puppet::Provider::ParsedFile,
+ filetype: :flat,
) do
- desc "Parse and generate host-wide known hosts files for SSH."
+ desc 'Parse and generate host-wide known hosts files for SSH.'
- text_line :comment, :match => /^#/
- text_line :blank, :match => /^\s*$/
+ text_line :comment, match: %r{^#}
+ text_line :blank, match: %r{^\s*$}
- record_line :parsed, :fields => %w{name type key},
- :post_parse => proc { |hash|
- names = hash[:name].split(",", -1)
- hash[:name] = names.shift
- hash[:host_aliases] = names
- },
- :pre_gen => proc { |hash|
- if hash[:host_aliases]
- hash[:name] = [hash[:name], hash[:host_aliases]].flatten.join(",")
- hash.delete(:host_aliases)
- end
- }
+ record_line :parsed, fields: ['name', 'type', 'key'],
+ post_parse: proc { |hash|
+ names = hash[:name].split(',', -1)
+ hash[:name] = names.shift
+ hash[:host_aliases] = names
+ },
+ pre_gen: proc { |hash|
+ if hash[:host_aliases]
+ hash[:name] = [hash[:name], hash[:host_aliases]].flatten.join(',')
+ hash.delete(:host_aliases)
+ end
+ }
# Make sure to use mode 644 if ssh_known_hosts is newly created
def self.default_mode
- 0644
+ 0o644
end
def self.default_target
case Facter.value(:operatingsystem)
- when "Darwin"
+ when 'Darwin'
# Versions 10.11 and up use /etc/ssh/ssh_known_hosts
version = Facter.value(:macosx_productversion_major)
if version
if Puppet::Util::Package.versioncmp(version, '10.11') >= 0
- "/etc/ssh/ssh_known_hosts"
+ '/etc/ssh/ssh_known_hosts'
else
- "/etc/ssh_known_hosts"
+ '/etc/ssh_known_hosts'
end
else
- "/etc/ssh_known_hosts"
+ '/etc/ssh_known_hosts'
end
else
- "/etc/ssh/ssh_known_hosts"
+ '/etc/ssh/ssh_known_hosts'
end
end
end
-
diff --git a/lib/puppet/type/ssh_authorized_key.rb b/lib/puppet/type/ssh_authorized_key.rb
index c6ff5b6..5c4df53 100644
--- a/lib/puppet/type/ssh_authorized_key.rb
+++ b/lib/puppet/type/ssh_authorized_key.rb
@@ -46,11 +46,10 @@ module Puppet
comment for each instance."
isnamevar
-
end
newproperty(:type) do
- desc "The encryption type used."
+ desc 'The encryption type used.'
newvalues :'ssh-dss', :'ssh-rsa', :'ecdsa-sha2-nistp256', :'ecdsa-sha2-nistp384', :'ecdsa-sha2-nistp521', :'ssh-ed25519'
@@ -71,7 +70,7 @@ module Puppet
the `name` attribute/resource title."
validate do |value|
- raise Puppet::Error, _("Key must not contain whitespace: %{value}") % { value: value } if value =~ /\s/
+ raise Puppet::Error, _('Key must not contain whitespace: %{value}') % { value: value } if value =~ %r{\s}
end
end
@@ -89,14 +88,14 @@ module Puppet
defaultto :absent
def should
- return super if defined?(@should) and @should[0] != :absent
+ return super if defined?(@should) && @should[0] != :absent
- return nil unless user = resource[:user]
+ return nil unless resource[:user]
begin
- return File.expand_path("~#{user}/.ssh/authorized_keys")
+ return File.expand_path("~#{resource[:user]}/.ssh/authorized_keys")
rescue
- Puppet.debug "The required user is not yet present on the system"
+ Puppet.debug 'The required user is not yet present on the system'
return nil
end
end
@@ -106,15 +105,18 @@ module Puppet
end
end
- newproperty(:options, :array_matching => :all) do
+ newproperty(:options, array_matching: :all) do
desc "Key options; see sshd(8) for possible values. Multiple values
should be specified as an array."
- defaultto do :absent end
+ defaultto { :absent }
validate do |value|
- unless value == :absent or value =~ /^[-a-z0-9A-Z_]+(?:=\".*?\")?$/
- raise Puppet::Error, _("Option %{value} is not valid. A single option must either be of the form 'option' or 'option=\"value\". Multiple options must be provided as an array") % { value: value }
+ unless value == :absent || value =~ %r{^[-a-z0-9A-Z_]+(?:=\".*?\")?$}
+ raise(
+ Puppet::Error,
+ _("Option %{value} is not valid. A single option must either be of the form 'option' or 'option=\"value\". Multiple options must be provided as an array") % { value: value },
+ )
end
end
end
@@ -135,7 +137,7 @@ module Puppet
end
# regular expression suitable for use by a ParsedFile based provider
- REGEX = /^(?:(.+)\s+)?(ssh-dss|ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521)\s+([^ ]+)\s*(.*)$/
+ REGEX = %r{^(?:(.+)\s+)?(ssh-dss|ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp256|ecdsa-sha2-nistp384|ecdsa-sha2-nistp521)\s+([^ ]+)\s*(.*)$}
def self.keyline_regex
REGEX
end
diff --git a/lib/puppet/type/sshkey.rb b/lib/puppet/type/sshkey.rb
index 31e590b..6e51cff 100644
--- a/lib/puppet/type/sshkey.rb
+++ b/lib/puppet/type/sshkey.rb
@@ -9,7 +9,7 @@ module Puppet
ensurable
newproperty(:type) do
- desc "The encryption type used. Probably ssh-dss or ssh-rsa."
+ desc 'The encryption type used. Probably ssh-dss or ssh-rsa.'
newvalues :'ssh-dss', :'ssh-ed25519', :'ssh-rsa', :'ecdsa-sha2-nistp256', :'ecdsa-sha2-nistp384', :'ecdsa-sha2-nistp521'
@@ -30,7 +30,7 @@ module Puppet
the `name` attribute/resource title."
end
- # FIXME This should automagically check for aliases to the hosts, just
+ # FIXME: This should automagically check for aliases to the hosts, just
# to see if we can automatically glean any aliases.
newproperty(:host_aliases) do
desc 'Any aliases the host might have. Multiple values must be
@@ -41,6 +41,7 @@ module Puppet
def insync?(is)
is == @should
end
+
# We actually want to return the whole array here, not just the first
# value.
def should
@@ -48,23 +49,23 @@ module Puppet
end
validate do |value|
- if value =~ /\s/
- raise Puppet::Error, _("Aliases cannot include whitespace")
+ if value =~ %r{\s}
+ raise Puppet::Error, _('Aliases cannot include whitespace')
end
- if value =~ /,/
- raise Puppet::Error, _("Aliases must be provided as an array, not a comma-separated list")
+ if value =~ %r{,}
+ raise Puppet::Error, _('Aliases must be provided as an array, not a comma-separated list')
end
end
end
newparam(:name) do
- desc "The host name that the key is associated with."
+ desc 'The host name that the key is associated with.'
isnamevar
validate do |value|
- raise Puppet::Error, _("Resourcename cannot include whitespaces") if value =~ /\s/
- raise Puppet::Error, _("No comma in resourcename allowed. If you want to specify aliases use the host_aliases property") if value.include?(',')
+ raise Puppet::Error, _('Resourcename cannot include whitespaces') if value =~ %r{\s}
+ raise Puppet::Error, _('No comma in resourcename allowed. If you want to specify aliases use the host_aliases property') if value.include?(',')
end
end
@@ -72,12 +73,13 @@ module Puppet
desc "The file in which to store the ssh key. Only used by
the `parsed` provider."
- defaultto { if @resource.class.defaultprovider.ancestors.include?(Puppet::Provider::ParsedFile)
- @resource.class.defaultprovider.default_target
+ defaultto do
+ if @resource.class.defaultprovider.ancestors.include?(Puppet::Provider::ParsedFile)
+ @resource.class.defaultprovider.default_target
else
nil
end
- }
+ end
end
end
end
diff --git a/metadata.json b/metadata.json
index 27f9c52..099bf96 100644
--- a/metadata.json
+++ b/metadata.json
@@ -86,5 +86,5 @@
],
"pdk-version": "1.5.0",
"template-url": "https://github.com/puppetlabs/pdk-templates.git",
- "template-ref": "heads/master-0-g6654f6d"
+ "template-ref": "heads/master-0-gc87eee3"
}
diff --git a/spec/acceptance/nodesets/default.yml b/spec/acceptance/nodesets/default.yml
new file mode 100644
index 0000000..ac89483
--- /dev/null
+++ b/spec/acceptance/nodesets/default.yml
@@ -0,0 +1,19 @@
+---
+HOSTS:
+ ubuntu1604-64-1:
+ pe_dir:
+ pe_ver:
+ pe_upgrade_dir:
+ pe_upgrade_ver:
+ hypervisor: vmpooler
+ platform: ubuntu-16.04-amd64
+ packaging_platform: ubuntu-16.04-amd64
+ template: ubuntu-1604-x86_64
+ roles:
+ - agent
+ - default
+CONFIG:
+ type: agent
+ nfs_server: none
+ consoleport: 443
+pooling_api: http://vmpooler.delivery.puppetlabs.net/ \ No newline at end of file
diff --git a/spec/acceptance/tests/resource/ssh_authorized_key/create.rb b/spec/acceptance/tests/resource/ssh_authorized_key/create.rb
deleted file mode 100644
index 6b4c879..0000000
--- a/spec/acceptance/tests/resource/ssh_authorized_key/create.rb
+++ /dev/null
@@ -1,39 +0,0 @@
-test_name "should create an entry for an SSH authorized key"
-
-tag 'audit:medium',
- 'audit:refactor', # Use block style `test_run`
- 'audit:acceptance' # Could be done at the integration (or unit) layer though
- # actual changing of resources could irreparably damage a
- # host running this, or require special permissions.
-
-confine :except, :platform => ['windows']
-
-auth_keys = '~/.ssh/authorized_keys'
-name = "pl#{rand(999999).to_i}"
-
-agents.each do |agent|
- teardown do
- #(teardown) restore the #{auth_keys} file
- on(agent, "mv /tmp/auth_keys #{auth_keys}", :acceptable_exit_codes => [0,1])
- end
-
- #------- SETUP -------#
- step "(setup) backup #{auth_keys} file"
- on(agent, "cp #{auth_keys} /tmp/auth_keys", :acceptable_exit_codes => [0,1])
- on(agent, "chown $LOGNAME #{auth_keys}")
-
- #------- TESTS -------#
- step "create an authorized key entry with puppet (present)"
- args = ['ensure=present',
- "user=$LOGNAME",
- "type='rsa'",
- "key='mykey'",
- ]
- on(agent, puppet_resource('ssh_authorized_key', "#{name}", args))
-
- step "verify entry in #{auth_keys}"
- on(agent, "cat #{auth_keys}") do |res|
- fail_test "didn't find the ssh_authorized_key for #{name}" unless stdout.include? "#{name}"
- end
-
-end
diff --git a/spec/acceptance/tests/resource/ssh_authorized_key/create_spec.rb b/spec/acceptance/tests/resource/ssh_authorized_key/create_spec.rb
new file mode 100644
index 0000000..5cf35fb
--- /dev/null
+++ b/spec/acceptance/tests/resource/ssh_authorized_key/create_spec.rb
@@ -0,0 +1,36 @@
+require 'spec_helper_acceptance'
+
+RSpec.context 'ssh_authorized_key: Create' do
+ test_name 'should create an entry for an SSH authorized key'
+
+ let(:auth_keys) { '~/.ssh/authorized_keys' }
+ let(:name) { "pl#{rand(999_999).to_i}" }
+
+ before(:each) do
+ posix_agents.each do |agent|
+ on(agent, "cp #{auth_keys} /tmp/auth_keys", acceptable_exit_codes: [0, 1])
+ on(agent, "chown $LOGNAME #{auth_keys}")
+ end
+ end
+
+ after(:each) do
+ posix_agents.each do |agent|
+ # (teardown) restore the #{auth_keys} file
+ on(agent, "mv /tmp/auth_keys #{auth_keys}", acceptable_exit_codes: [0, 1])
+ end
+ end
+
+ posix_agents.each do |agent|
+ it "#{agent} should create an entry for an SSH authorized key" do
+ args = ['ensure=present',
+ 'user=$LOGNAME',
+ "type='rsa'",
+ "key='mykey'"]
+ on(agent, puppet_resource('ssh_authorized_key', name.to_s, args))
+
+ on(agent, "cat #{auth_keys}") do |_res|
+ fail_test "didn't find the ssh_authorized_key for #{name}" unless stdout.include? name.to_s
+ end
+ end
+ end
+end
diff --git a/spec/acceptance/tests/resource/ssh_authorized_key/destroy.rb b/spec/acceptance/tests/resource/ssh_authorized_key/destroy.rb
deleted file mode 100644
index c80e967..0000000
--- a/spec/acceptance/tests/resource/ssh_authorized_key/destroy.rb
+++ /dev/null
@@ -1,42 +0,0 @@
-test_name "should delete an entry for an SSH authorized key"
-
-tag 'audit:medium',
- 'audit:refactor', # Use block style `test_run`
- 'audit:acceptance' # Could be done at the integration (or unit) layer though
- # actual changing of resources could irreparably damage a
- # host running this, or require special permissions.
-
-confine :except, :platform => ['windows']
-
-auth_keys = '~/.ssh/authorized_keys'
-name = "pl#{rand(999999).to_i}"
-
-agents.each do |agent|
- teardown do
- #(teardown) restore the #{auth_keys} file
- on(agent, "mv /tmp/auth_keys #{auth_keys}", :acceptable_exit_codes => [0,1])
- end
-
- #------- SETUP -------#
- step "(setup) backup #{auth_keys} file"
- on(agent, "cp #{auth_keys} /tmp/auth_keys", :acceptable_exit_codes => [0,1])
-
- step "(setup) create an authorized key in the #{auth_keys} file"
- on(agent, "echo '' >> #{auth_keys} && echo 'ssh-rsa mykey #{name}' >> #{auth_keys}")
- on(agent, "chown $LOGNAME #{auth_keys}")
-
- #------- TESTS -------#
- step "delete an authorized key entry with puppet (absent)"
- args = ['ensure=absent',
- "user=$LOGNAME",
- "type='rsa'",
- "key='mykey'",
- ]
- on(agent, puppet_resource('ssh_authorized_key', "#{name}", args))
-
- step "verify entry deleted from #{auth_keys}"
- on(agent, "cat #{auth_keys}") do |res|
- fail_test "found the ssh_authorized_key for #{name}" if stdout.include? "#{name}"
- end
-
-end
diff --git a/spec/acceptance/tests/resource/ssh_authorized_key/destroy_spec.rb b/spec/acceptance/tests/resource/ssh_authorized_key/destroy_spec.rb
new file mode 100644
index 0000000..af160ce
--- /dev/null
+++ b/spec/acceptance/tests/resource/ssh_authorized_key/destroy_spec.rb
@@ -0,0 +1,38 @@
+require 'spec_helper_acceptance'
+
+RSpec.context 'sshkeys: Destroy' do
+ confine :except, platform: ['windows']
+
+ let(:auth_keys) { '~/.ssh/authorized_keys' }
+ let(:name) { "pl#{rand(999_999).to_i}" }
+
+ before(:each) do
+ posix_agents.each do |agent|
+ on(agent, "cp #{auth_keys} /tmp/auth_keys", acceptable_exit_codes: [0, 1])
+
+ on(agent, "echo '' >> #{auth_keys} && echo 'ssh-rsa mykey #{name}' >> #{auth_keys}")
+ on(agent, "chown $LOGNAME #{auth_keys}")
+ end
+ end
+
+ after(:each) do
+ posix_agents.each do |agent|
+ # (teardown) restore the #{auth_keys} file
+ on(agent, "mv /tmp/auth_keys #{auth_keys}", acceptable_exit_codes: [0, 1])
+ end
+ end
+
+ posix_agents.each do |agent|
+ it "#{agent} should delete an entry for an SSH authorized key" do
+ args = ['ensure=absent',
+ 'user=$LOGNAME',
+ "type='rsa'",
+ "key='mykey'"]
+ on(agent, puppet_resource('ssh_authorized_key', name.to_s, args))
+
+ on(agent, "cat #{auth_keys}") do |_res|
+ expect(stdout).not_to include(name.to_s)
+ end
+ end
+ end
+end
diff --git a/spec/acceptance/tests/resource/ssh_authorized_key/modify.rb b/spec/acceptance/tests/resource/ssh_authorized_key/modify.rb
deleted file mode 100644
index 0a50c31..0000000
--- a/spec/acceptance/tests/resource/ssh_authorized_key/modify.rb
+++ /dev/null
@@ -1,43 +0,0 @@
-test_name "should update an entry for an SSH authorized key"
-
-tag 'audit:medium',
- 'audit:refactor', # Use block style `test_run`
- 'audit:acceptance' # Could be done at the integration (or unit) layer though
- # actual changing of resources could irreparably damage a
- # host running this, or require special permissions.
-
-confine :except, :platform => ['windows']
-
-auth_keys = '~/.ssh/authorized_keys'
-name = "pl#{rand(999999).to_i}"
-
-agents.each do |agent|
- teardown do
- #(teardown) restore the #{auth_keys} file
- on(agent, "mv /tmp/auth_keys #{auth_keys}", :acceptable_exit_codes => [0,1])
- end
-
- #------- SETUP -------#
- step "(setup) backup #{auth_keys} file"
- on(agent, "cp #{auth_keys} /tmp/auth_keys", :acceptable_exit_codes => [0,1])
-
- step "(setup) create an authorized key in the #{auth_keys} file"
- on(agent, "echo '' >> #{auth_keys} && echo 'ssh-rsa mykey #{name}' >> #{auth_keys}")
- on(agent, "chown $LOGNAME #{auth_keys}")
-
- #------- TESTS -------#
- step "update an authorized key entry with puppet (present)"
- args = ['ensure=present',
- "user=$LOGNAME",
- "type='rsa'",
- "key='mynewshinykey'",
- ]
- on(agent, puppet_resource('ssh_authorized_key', "#{name}", args))
-
- step "verify entry updated in #{auth_keys}"
- on(agent, "cat #{auth_keys}") do |res|
- fail_test "didn't find the updated key for #{name}" unless stdout.include? "mynewshinykey #{name}"
- fail_test "Found old key mykey #{name}" if stdout.include? "mykey #{name}"
- end
-
-end
diff --git a/spec/acceptance/tests/resource/ssh_authorized_key/modify_spec.rb b/spec/acceptance/tests/resource/ssh_authorized_key/modify_spec.rb
new file mode 100644
index 0000000..3a46374
--- /dev/null
+++ b/spec/acceptance/tests/resource/ssh_authorized_key/modify_spec.rb
@@ -0,0 +1,36 @@
+require 'spec_helper_acceptance'
+
+RSpec.context 'sshkeys: Modify' do
+ let(:auth_keys) { '~/.ssh/authorized_keys' }
+ let(:name) { "pl#{rand(999_999).to_i}" }
+
+ before(:each) do
+ posix_agents.each do |agent|
+ on(agent, "cp #{auth_keys} /tmp/auth_keys", acceptable_exit_codes: [0, 1])
+ on(agent, "echo '' >> #{auth_keys} && echo 'ssh-rsa mykey #{name}' >> #{auth_keys}")
+ on(agent, "chown $LOGNAME #{auth_keys}")
+ end
+ end
+
+ after(:each) do
+ posix_agents.each do |agent|
+ # (teardown) restore the #{auth_keys} file
+ on(agent, "mv /tmp/auth_keys #{auth_keys}", acceptable_exit_codes: [0, 1])
+ end
+ end
+
+ posix_agents.each do |agent|
+ it "#{agent} should update an entry for an SSH authorized key" do
+ args = ['ensure=present',
+ 'user=$LOGNAME',
+ "type='rsa'",
+ "key='mynewshinykey'"]
+ on(agent, puppet_resource('ssh_authorized_key', name.to_s, args))
+
+ on(agent, "cat #{auth_keys}") do |_res|
+ expect(stdout).to include("mynewshinykey #{name}")
+ expect(stdout).not_to include("mykey #{name}")
+ end
+ end
+ end
+end
diff --git a/spec/acceptance/tests/resource/ssh_authorized_key/query.rb b/spec/acceptance/tests/resource/ssh_authorized_key/query.rb
deleted file mode 100644
index 8caff85..0000000
--- a/spec/acceptance/tests/resource/ssh_authorized_key/query.rb
+++ /dev/null
@@ -1,35 +0,0 @@
-test_name "should be able to find an existing SSH authorized key"
-
-tag 'audit:medium',
- 'audit:refactor', # Use block style `test_run`
- 'audit:acceptance' # Could be done at the integration (or unit) layer though
- # actual changing of resources could irreparably damage a
- # host running this, or require special permissions.
-
-skip_test("This test is blocked by PUP-1605")
-
-confine :except, :platform => ['windows']
-
-auth_keys = '~/.ssh/authorized_keys'
-name = "pl#{rand(999999).to_i}"
-
-agents.each do |agent|
- teardown do
- #(teardown) restore the #{auth_keys} file
- on(agent, "mv /tmp/auth_keys #{auth_keys}", :acceptable_exit_codes => [0,1])
- end
-
- #------- SETUP -------#
- step "(setup) backup #{auth_keys} file"
- on(agent, "cp #{auth_keys} /tmp/auth_keys", :acceptable_exit_codes => [0,1])
-
- step "(setup) create an authorized key in the #{auth_keys} file"
- on(agent, "echo '' >> #{auth_keys} && echo 'ssh-rsa mykey #{name}' >> #{auth_keys}")
-
- #------- TESTS -------#
- step "verify SSH authorized key query with puppet"
- on(agent, puppet_resource('ssh_authorized_key', "/#{name}")) do |res|
- fail_test "Didn't find the ssh_authorized_key for #{name}" unless stdout.include? "#{name}"
- end
-
-end
diff --git a/spec/acceptance/tests/resource/sshkey/create.rb b/spec/acceptance/tests/resource/sshkey/create.rb
deleted file mode 100644
index 4e75379..0000000
--- a/spec/acceptance/tests/resource/sshkey/create.rb
+++ /dev/null
@@ -1,77 +0,0 @@
-test_name "(PUP-5508) Should add an SSH key to the correct ssh_known_hosts file on OS X/macOS" do
-# TestRail test case C93370
-
-tag 'audit:medium',
- 'audit:acceptance' # Could be done at the integration (or unit) layer though
- # actual changing of resources could irreparably damage a
- # host running this, or require special permissions.
-
-confine :to, :platform => /osx/
-
-keyname = "pl#{rand(999999).to_i}"
-
-# FIXME: This is bletcherous
-macos_version = fact_on(agent, "os.macosx.version.major")
-if ["10.9","10.10"].include? macos_version
- ssh_known_hosts = '/etc/ssh_known_hosts'
-else
- ssh_known_hosts = '/etc/ssh/ssh_known_hosts'
-end
-
-teardown do
- puts "Restore the #{ssh_known_hosts} file"
- agents.each do |agent|
- # Is it present?
- rc = on(agent, "[ -e /tmp/ssh_known_hosts ]",
- :accept_all_exit_codes => true)
- if rc.exit_code == 0
- # It's present, so restore the original
- on(agent, "mv -fv /tmp/ssh_known_hosts #{ssh_known_hosts}",
- :accept_all_exit_codes => true)
- else
- # It's missing, which means there wasn't one to backup; just
- # delete the one we laid down
- on(agent, "rm -fv #{ssh_known_hosts}",
- :accept_all_exit_codes => true)
- end
- end
-end
-
-#------- SETUP -------#
-step "Backup #{ssh_known_hosts} file, if present" do
- # The 'cp' might fail because the source file doesn't exist
- on(agent, "cp -fv #{ssh_known_hosts} /tmp/ssh_known_hosts",
- :acceptable_exit_codes => [0,1])
-end
-
-#------- TESTS -------#
-step 'Verify that the default file is empty or non-existent' do
- # Is it even there?
- rc = on(agent, "[ ! -e #{ssh_known_hosts} ]",
- :acceptable_exit_codes => [0, 1])
- if rc.exit_code == 1
- # If it's there, it should be empty
- on(agent, "cat #{ssh_known_hosts}") do |res|
- fail_test "Default #{ssh_known_hosts} file not empty" \
- unless stdout.empty?
- end
- end
-end
-
-step "Add an sshkey to the default file" do
- args = [
- "ensure=present",
- "key=how_about_the_key_of_c",
- "type=ssh-rsa",
- ]
- on(agent, puppet_resource("sshkey", "#{keyname}", args))
-end
-
-step 'Verify the new entry in the default file' do
- on(agent, "cat #{ssh_known_hosts}") do |rc|
- fail_test "Didn't find the ssh_known_host entry for #{keyname}" \
- unless stdout.include? "#{keyname}"
- end
-end
-
-end
diff --git a/spec/acceptance/tests/resource/sshkey/create_spec.rb b/spec/acceptance/tests/resource/sshkey/create_spec.rb
new file mode 100644
index 0000000..f6534b8
--- /dev/null
+++ b/spec/acceptance/tests/resource/sshkey/create_spec.rb
@@ -0,0 +1,81 @@
+require 'spec_helper_acceptance'
+
+RSpec.context 'sshkeys: Create' do
+ let(:keyname) { "pl#{rand(999_999).to_i}" }
+
+ # FIXME: This is bletcherous
+ let(:macos_version) { fact_on(agent, 'os.macosx.version.major') }
+ let(:ssh_known_hosts) do
+ if ['10.9', '10.10'].include? macos_version
+ '/etc/ssh_known_hosts'
+ else
+ '/etc/ssh/ssh_known_hosts'
+ end
+ end
+
+ before(:each) do
+ osx_agents.each do |agent|
+ # The 'cp' might fail because the source file doesn't exist
+ on(
+ agent,
+ "cp -fv #{ssh_known_hosts} /tmp/ssh_known_hosts",
+ acceptable_exit_codes: [0, 1],
+ )
+ end
+ end
+
+ after(:each) do
+ osx_agents.each do |agent|
+ # Is it present?
+ rc = on(
+ agent,
+ '[ -e /tmp/ssh_known_hosts ]',
+ accept_all_exit_codes: true,
+ )
+ if rc.exit_code == 0
+ # It's present, so restore the original
+ on(
+ agent,
+ "mv -fv /tmp/ssh_known_hosts #{ssh_known_hosts}",
+ accept_all_exit_codes: true,
+ )
+ else
+ # It's missing, which means there wasn't one to backup; just
+ # delete the one we laid down
+ on(
+ agent,
+ "rm -fv #{ssh_known_hosts}",
+ accept_all_exit_codes: true,
+ )
+ end
+ end
+ end
+
+ osx_agents.each do |agent|
+ it "#{agent} should add an SSH key to the correct ssh_known_hosts file on OS X/macOS (PUP-5508)" do
+ # Is it even there?
+ rc = on(
+ agent,
+ "[ ! -e #{ssh_known_hosts} ]",
+ acceptable_exit_codes: [0, 1],
+ )
+ if rc.exit_code == 1
+ # If it's there, it should be empty
+ on(agent, "cat #{ssh_known_hosts}") do |_res|
+ expect(stdout).to be_empty
+ end
+ end
+
+ args = [
+ 'ensure=present',
+ 'key=how_about_the_key_of_c',
+ 'type=ssh-rsa',
+ ]
+ on(agent, puppet_resource('sshkey', keyname.to_s, args))
+
+ on(agent, "cat #{ssh_known_hosts}") do |_rc|
+ expect(stdout).to include(keyname.to_s)
+ end
+ end
+ end
+end
diff --git a/spec/integration/provider/ssh_authorized_key_spec.rb b/spec/integration/provider/ssh_authorized_key_spec.rb
index 14af2de..784415c 100644
--- a/spec/integration/provider/ssh_authorized_key_spec.rb
+++ b/spec/integration/provider/ssh_authorized_key_spec.rb
@@ -1,9 +1,7 @@
-#! /usr/bin/env ruby
-
require 'spec_helper'
require 'puppet/file_bucket/dipper'
-describe Puppet::Type.type(:ssh_authorized_key).provider(:parsed), '(integration)', :unless => Puppet.features.microsoft_windows? do
+describe Puppet::Type.type(:ssh_authorized_key).provider(:parsed), unless: Puppet.features.microsoft_windows? do
include PuppetSpec::Files
let :fake_userfile do
@@ -14,35 +12,39 @@ describe Puppet::Type.type(:ssh_authorized_key).provider(:parsed), '(integration
tmpfile('authorized_keys.root')
end
+ # rubocop:disable Metrics/LineLength
let :sample_rsa_keys do
[
'AAAAB3NzaC1yc2EAAAADAQABAAAAgQCi18JBZOq10X3w4f67nVhO0O3s5Y1vHH4UgMSM3ZnQwbC5hjGyYSi9UULOoQQoQynI/a0I9NL423/Xk/XJVIKCHcS8q6V2Wmjd+fLNelOjxxoW6mbIytEt9rDvwgq3Mof3/m21L3t2byvegR00a+ikKbmInPmKwjeWZpexCIsHzQ==', # 1024 bit
'AAAAB3NzaC1yc2EAAAADAQABAAAAgQDLClyvi3CsJw5Id6khZs2/+s11qOH4Gdp6iDioDsrIp0m8kSiPr71VGyQYAfPzzvHemHS7Xg0NkG1Kc8u9tRqBQfTvz7ubq0AT/g01+4P2hQ/soFkuwlUG/HVnnaYb6N0Qp5SHWvD5vBE2nFFQVpP5GrSctPtHSjzJq/i+6LYhmQ==', # 1024 bit
- 'AAAAB3NzaC1yc2EAAAADAQABAAABAQDLygAO6txXkh9FNV8xSsBkATeqLbHzS7sFjGI3gt0Dx6q3LjyKwbhQ1RLf28kd5G6VWiXmClU/RtiPdUz8nrGuun++2mrxzrXrvpR9dq1lygLQ2wn2cI35dN5bjRMtXy3decs6HUhFo9MoNwX250rUWfdCyNPhGIp6OOfmjdy+UeLGNxq9wDx6i4bT5tVVSqVRtsEfw9+ICXchzl85QudjneVVpP+thriPZXfXA5eaGwAo/dmoKOIhUwF96gpdLqzNtrGQuxPbV80PTbGv9ZtAtTictxaDz8muXO7he9pXmchUpxUKtMFjHkL0FAZ9tRPmv3RA30sEr2fZ8+LKvnE50w0' #2048 Bit
+ 'AAAAB3NzaC1yc2EAAAADAQABAAABAQDLygAO6txXkh9FNV8xSsBkATeqLbHzS7sFjGI3gt0Dx6q3LjyKwbhQ1RLf28kd5G6VWiXmClU/RtiPdUz8nrGuun++2mrxzrXrvpR9dq1lygLQ2wn2cI35dN5bjRMtXy3decs6HUhFo9MoNwX250rUWfdCyNPhGIp6OOfmjdy+UeLGNxq9wDx6i4bT5tVVSqVRtsEfw9+ICXchzl85QudjneVVpP+thriPZXfXA5eaGwAo/dmoKOIhUwF96gpdLqzNtrGQuxPbV80PTbGv9ZtAtTictxaDz8muXO7he9pXmchUpxUKtMFjHkL0FAZ9tRPmv3RA30sEr2fZ8+LKvnE50w0' # 2048 Bit
]
end
+ # rubocop:enable Metrics/LineLength
+ # rubocop:disable Metrics/LineLength
let :sample_dsa_keys do
[
'AAAAB3NzaC1kc3MAAACBAOPck2O8MIDSqxPSnvENt6tzRrKJ5oOhB6Nc6oEcWm+VEH1gvuxdiRqwoMgRwyEf1yUd+UAcLw3a6Jn+EtFyEBN/5WF+4Tt4xTxZ0Pfik2Wc5uqHbQ2dkmOoXiAOYPiD3JUQ1Xwm/J0CgetjitoLfzAGdCNhMqguqAuHcVJ78ZZbAAAAFQCIBKFYZ+I18I+dtgteirXh+VVEEwAAAIEAs1yvQ/wnLLrRCM660pF4kBiw3D6dJfMdCXWQpn0hZmkBQSIzZv4Wuk3giei5luxscDxNc+y3CTXtnyG4Kt1Yi2sOdvhRI3rX8tD+ejn8GHazM05l5VIo9uu4AQPIE32iV63IqgApSBbJ6vDJW91oDH0J492WdLCar4BS/KE3cRwAAACBAN0uSDyJqYLRsfYcFn4HyVf6TJxQm1IcwEt6GcJVzgjri9VtW7FqY5iBqa9B9Zdh5XXAYJ0XLsWQCcrmMHM2XGHGpA4gL9VlCJ/0QvOcXxD2uK7IXwAVUA7g4V4bw8EVnFv2Flufozhsp+4soo1xiYc5jiFVHwVlk21sMhAtKAeF' # 1024 Bit
]
end
+ # rubocop:enable Metrics/LineLength
let :sample_lines do
[
"ssh-rsa #{sample_rsa_keys[1]} root@someotherhost",
"ssh-dss #{sample_dsa_keys[0]} root@anywhere",
"ssh-rsa #{sample_rsa_keys[2]} paul",
- "ssh-rsa #{sample_rsa_keys[2]} dummy"
+ "ssh-rsa #{sample_rsa_keys[2]} dummy",
]
end
let :dummy do
Puppet::Type.type(:ssh_authorized_key).new(
- :name => 'dummy',
- :target => fake_userfile,
- :user => 'nobody',
- :ensure => :absent
+ name: 'dummy',
+ target: fake_userfile,
+ user: 'nobody',
+ ensure: :absent,
)
end
@@ -57,7 +59,7 @@ describe Puppet::Type.type(:ssh_authorized_key).provider(:parsed), '(integration
end
def create_fake_key(username, content)
- filename = (username == :root ? fake_rootfile : fake_userfile )
+ filename = ((username == :root) ? fake_rootfile : fake_userfile)
File.open(filename, 'w') do |f|
content.each do |line|
f.puts line
@@ -66,13 +68,13 @@ describe Puppet::Type.type(:ssh_authorized_key).provider(:parsed), '(integration
end
def check_fake_key(username, expected_content)
- filename = (username == :root ? fake_rootfile : fake_userfile )
- content = File.readlines(filename).map(&:chomp).sort.reject{ |x| x =~ /^# HEADER:/ }
+ filename = ((username == :root) ? fake_rootfile : fake_userfile)
+ content = File.readlines(filename).map(&:chomp).sort.reject { |x| x =~ %r{^# HEADER:} }
expect(content.join("\n")).to eq(expected_content.sort.join("\n"))
end
def run_in_catalog(*resources)
- Puppet::FileBucket::Dipper.any_instance.stubs(:backup) # Don't backup to the filebucket
+ Puppet::FileBucket::Dipper.any_instance.stubs(:backup) # rubocop:disable RSpec/AnyInstance
catalog = Puppet::Resource::Catalog.new
catalog.host_config = false
resources.each do |resource|
@@ -82,35 +84,34 @@ describe Puppet::Type.type(:ssh_authorized_key).provider(:parsed), '(integration
catalog.apply
end
- it "should not complain about empty lines and comments" do
+ it 'does not complain about empty lines and comments' do
described_class.expects(:flush).never
- sample = ['',sample_lines[0],' ',sample_lines[1],'# just a comment','#and another']
- create_fake_key(:user,sample)
+ sample = ['', sample_lines[0], ' ', sample_lines[1], '# just a comment', '#and another']
+ create_fake_key(:user, sample)
run_in_catalog(dummy)
check_fake_key(:user, sample)
end
- it "should keep empty lines and comments when modifying a file" do
- create_fake_key(:user, ['',sample_lines[0],' ',sample_lines[3],'# just a comment','#and another'])
+ it 'keeps empty lines and comments when modifying a file' do
+ create_fake_key(:user, ['', sample_lines[0], ' ', sample_lines[3], '# just a comment', '#and another'])
run_in_catalog(dummy)
- check_fake_key(:user, ['',sample_lines[0],' ','# just a comment','#and another'])
+ check_fake_key(:user, ['', sample_lines[0], ' ', '# just a comment', '#and another'])
end
- describe "when managing one resource" do
-
- describe "with ensure set to absent" do
+ describe 'when managing one resource' do
+ describe 'with ensure set to absent' do
let :resource do
Puppet::Type.type(:ssh_authorized_key).new(
- :name => 'root@hostname',
- :type => :rsa,
- :key => sample_rsa_keys[0],
- :target => fake_rootfile,
- :user => 'root',
- :ensure => :absent
+ name: 'root@hostname',
+ type: :rsa,
+ key: sample_rsa_keys[0],
+ target: fake_rootfile,
+ user: 'root',
+ ensure: :absent,
)
end
- it "should not modify root's keyfile if resource is currently not present" do
+ it "does not modify root's keyfile if resource is currently not present" do
create_fake_key(:root, sample_lines)
run_in_catalog(resource)
check_fake_key(:root, sample_lines)
@@ -123,96 +124,96 @@ describe Puppet::Type.type(:ssh_authorized_key).provider(:parsed), '(integration
end
end
- describe "when ensure is present" do
+ describe 'when ensure is present' do
let :resource do
Puppet::Type.type(:ssh_authorized_key).new(
- :name => 'root@hostname',
- :type => :rsa,
- :key => sample_rsa_keys[0],
- :target => fake_rootfile,
- :user => 'root',
- :ensure => :present
+ name: 'root@hostname',
+ type: :rsa,
+ key: sample_rsa_keys[0],
+ target: fake_rootfile,
+ user: 'root',
+ ensure: :present,
)
end
# just a dummy so the parsedfile provider is aware
# of the user's authorized_keys file
- it "should add the key if it is not present" do
+ it 'adds the key if it is not present' do
create_fake_key(:root, sample_lines)
run_in_catalog(resource)
- check_fake_key(:root, sample_lines + ["ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
+ check_fake_key(:root, sample_lines + ["ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
end
- it "should modify the type if type is out of sync" do
- create_fake_key(:root,sample_lines + [ "ssh-dss #{sample_rsa_keys[0]} root@hostname" ])
+ it 'modifies the type if type is out of sync' do
+ create_fake_key(:root, sample_lines + ["ssh-dss #{sample_rsa_keys[0]} root@hostname"])
run_in_catalog(resource)
- check_fake_key(:root, sample_lines + [ "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
+ check_fake_key(:root, sample_lines + ["ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
end
- it "should modify the key if key is out of sync" do
- create_fake_key(:root,sample_lines + [ "ssh-rsa #{sample_rsa_keys[1]} root@hostname" ])
+ it 'modifies the key if key is out of sync' do
+ create_fake_key(:root, sample_lines + ["ssh-rsa #{sample_rsa_keys[1]} root@hostname"])
run_in_catalog(resource)
- check_fake_key(:root, sample_lines + [ "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
+ check_fake_key(:root, sample_lines + ["ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
end
- it "should remove the key from old file if target is out of sync" do
- create_fake_key(:user, [ sample_lines[0], "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
- create_fake_key(:root, [ sample_lines[1], sample_lines[2] ])
+ it 'removes the key from old file if target is out of sync' do
+ create_fake_key(:user, [sample_lines[0], "ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
+ create_fake_key(:root, [sample_lines[1], sample_lines[2]])
run_in_catalog(resource, dummy)
- check_fake_key(:user, [ sample_lines[0] ])
- #check_fake_key(:root, [ sample_lines[1], sample_lines[2], "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
+ check_fake_key(:user, [sample_lines[0]])
+ # check_fake_key(:root, [ sample_lines[1], sample_lines[2], "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
end
- it "should add the key to new file if target is out of sync" do
- create_fake_key(:user, [ sample_lines[0], "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
- create_fake_key(:root, [ sample_lines[1], sample_lines[2] ])
+ it 'adds the key to new file if target is out of sync' do
+ create_fake_key(:user, [sample_lines[0], "ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
+ create_fake_key(:root, [sample_lines[1], sample_lines[2]])
run_in_catalog(resource, dummy)
- #check_fake_key(:user, [ sample_lines[0] ])
- check_fake_key(:root, [ sample_lines[1], sample_lines[2], "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
+ # check_fake_key(:user, [ sample_lines[0] ])
+ check_fake_key(:root, [sample_lines[1], sample_lines[2], "ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
end
- it "should modify options if options are out of sync" do
- resource[:options]=[ 'from="*.domain1,host1.domain2"', 'no-port-forwarding', 'no-pty' ]
- create_fake_key(:root, sample_lines + [ "from=\"*.false,*.false2\",no-port-forwarding,no-pty ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
+ it 'modifies options if options are out of sync' do
+ resource[:options] = ['from="*.domain1,host1.domain2"', 'no-port-forwarding', 'no-pty']
+ create_fake_key(:root, sample_lines + ["from=\"*.false,*.false2\",no-port-forwarding,no-pty ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
run_in_catalog(resource)
- check_fake_key(:root, sample_lines + [ "from=\"*.domain1,host1.domain2\",no-port-forwarding,no-pty ssh-rsa #{sample_rsa_keys[0]} root@hostname"] )
+ check_fake_key(:root, sample_lines + ["from=\"*.domain1,host1.domain2\",no-port-forwarding,no-pty ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
end
end
end
- describe "when managing two resource" do
+ describe 'when managing two resource' do
let :examples do
resources = []
resources << Puppet::Type.type(:ssh_authorized_key).new(
- :name => 'root@hostname',
- :type => :rsa,
- :key => sample_rsa_keys[0],
- :target => fake_rootfile,
- :user => 'root',
- :ensure => :present
+ name: 'root@hostname',
+ type: :rsa,
+ key: sample_rsa_keys[0],
+ target: fake_rootfile,
+ user: 'root',
+ ensure: :present,
)
resources << Puppet::Type.type(:ssh_authorized_key).new(
- :name => 'user@hostname',
- :key => sample_rsa_keys[1],
- :type => :rsa,
- :target => fake_userfile,
- :user => 'nobody',
- :ensure => :present
+ name: 'user@hostname',
+ key: sample_rsa_keys[1],
+ type: :rsa,
+ target: fake_userfile,
+ user: 'nobody',
+ ensure: :present,
)
resources
end
- describe "and both keys are absent" do
+ describe 'and both keys are absent' do
before :each do
create_fake_key(:root, sample_lines)
create_fake_key(:user, sample_lines)
end
- it "should add both keys" do
+ it 'adds both keys' do
run_in_catalog(*examples)
- check_fake_key(:root, sample_lines + [ "ssh-rsa #{sample_rsa_keys[0]} root@hostname" ])
- check_fake_key(:user, sample_lines + [ "ssh-rsa #{sample_rsa_keys[1]} user@hostname" ])
+ check_fake_key(:root, sample_lines + ["ssh-rsa #{sample_rsa_keys[0]} root@hostname"])
+ check_fake_key(:user, sample_lines + ["ssh-rsa #{sample_rsa_keys[1]} user@hostname"])
end
end
end
diff --git a/spec/integration/provider/sshkey_spec.rb b/spec/integration/provider/sshkey_spec.rb
index f461460..4a3bf87 100644
--- a/spec/integration/provider/sshkey_spec.rb
+++ b/spec/integration/provider/sshkey_spec.rb
@@ -1,24 +1,23 @@
-#!/usr/bin/env ruby
-
require 'spec_helper'
require 'puppet/file_bucket/dipper'
require 'puppet_spec/files'
require 'puppet_spec/compiler'
-describe Puppet::Type.type(:sshkey).provider(:parsed), '(integration)',
- :unless => Puppet.features.microsoft_windows? do
+describe Puppet::Type.type(:sshkey).provider(:parsed), unless: Puppet.features.microsoft_windows? do
include PuppetSpec::Files
include PuppetSpec::Compiler
+ let(:sshkey_file) { tmpfile('sshkey_integration_specs') }
+ let(:type_under_test) { 'sshkey' }
+
before :each do
# Don't backup to filebucket
- Puppet::FileBucket::Dipper.any_instance.stubs(:backup)
+ Puppet::FileBucket::Dipper.any_instance.stubs(:backup) # rubocop:disable RSpec/AnyInstance
# We don't want to execute anything
- described_class.stubs(:filetype).
- returns Puppet::Util::FileType::FileTypeFlat
+ described_class.stubs(:filetype)
+ .returns Puppet::Util::FileType::FileTypeFlat
- @sshkey_file = tmpfile('sshkey_integration_specs')
- FileUtils.cp(my_fixture('sample'), @sshkey_file)
+ FileUtils.cp(my_fixture('sample'), sshkey_file)
end
after :each do
@@ -26,134 +25,132 @@ describe Puppet::Type.type(:sshkey).provider(:parsed), '(integration)',
described_class.clear
end
- let(:type_under_test) { 'sshkey' }
-
- describe "when managing a ssh known hosts file it..." do
+ describe 'when managing a ssh known hosts file it...' do
+ let(:host_alias) { 'r0ckdata.com' }
+ let(:invalid_type) { 'ssh-er0ck' }
+ let(:sshkey_name) { 'kirby.madstop.com' }
+ let(:super_unique) { 'my.super.unique.host' }
- let(:super_unique) { "my.super.unique.host" }
- it "should create a new known_hosts file with mode 0644" do
+ it 'creates a new known_hosts file with mode 0644' do
target = tmpfile('ssh_known_hosts')
manifest = "#{type_under_test} { '#{super_unique}':
- ensure => 'present',
- type => 'rsa',
- key => 'TESTKEY',
- target => '#{target}' }"
+ ensure => 'present',
+ type => 'rsa',
+ key => 'TESTKEY',
+ target => '#{target}' }"
apply_with_error_check(manifest)
- expect_file_mode(target, "644")
+ expect_file_mode(target, '644')
end
- it "should create an SSH host key entry (ensure present)" do
+ it 'creates an SSH host key entry (ensure present)' do
manifest = "#{type_under_test} { '#{super_unique}':
- ensure => 'present',
- type => 'rsa',
- key => 'mykey',
- target => '#{@sshkey_file}' }"
+ ensure => 'present',
+ type => 'rsa',
+ key => 'mykey',
+ target => '#{sshkey_file}' }"
apply_with_error_check(manifest)
- expect(File.read(@sshkey_file)).to match(/#{super_unique}.*mykey/)
+ expect(File.read(sshkey_file)).to match(%r{#{super_unique}.*mykey})
end
- let(:sshkey_name) { 'kirby.madstop.com' }
- it "should delete an entry for an SSH host key" do
+ it 'deletes an entry for an SSH host key' do
manifest = "#{type_under_test} { '#{sshkey_name}':
- ensure => 'absent',
- target => '#{@sshkey_file}' }"
+ ensure => 'absent',
+ target => '#{sshkey_file}' }"
apply_with_error_check(manifest)
- expect(File.read(@sshkey_file)).not_to match(/#{sshkey_name}.*Yqk0=/)
+ expect(File.read(sshkey_file)).not_to match(%r{#{sshkey_name}.*Yqk0=})
end
- it "should update an entry for an SSH host key" do
+ it 'updates an entry for an SSH host key' do
manifest = "#{type_under_test} { '#{sshkey_name}':
- ensure => 'present',
- type => 'rsa',
- key => 'mynewshinykey',
- target => '#{@sshkey_file}' }"
+ ensure => 'present',
+ type => 'rsa',
+ key => 'mynewshinykey',
+ target => '#{sshkey_file}' }"
apply_with_error_check(manifest)
- expect(File.read(@sshkey_file)).to match(/#{sshkey_name}.*mynewshinykey/)
- expect(File.read(@sshkey_file)).not_to match(/#{sshkey_name}.*Yqk0=/)
+ expect(File.read(sshkey_file)).to match(%r{#{sshkey_name}.*mynewshinykey})
+ expect(File.read(sshkey_file)).not_to match(%r{#{sshkey_name}.*Yqk0=})
end
# test all key types
- types = ["ssh-dss", "dsa",
- "ssh-ed25519", "ed25519",
- "ssh-rsa", "rsa",
- "ecdsa-sha2-nistp256",
- "ecdsa-sha2-nistp384",
- "ecdsa-sha2-nistp521"]
+ types = [
+ 'ssh-dss', 'dsa',
+ 'ssh-ed25519', 'ed25519',
+ 'ssh-rsa', 'rsa',
+ 'ecdsa-sha2-nistp256',
+ 'ecdsa-sha2-nistp384',
+ 'ecdsa-sha2-nistp521'
+ ]
# these types are treated as aliases for sshkey <ahem> type
# so they are populated as the *values* below
- aliases = {"dsa" => "ssh-dss",
- "ed25519" => "ssh-ed25519",
- "rsa" => "ssh-rsa"}
+ aliases = {
+ 'dsa' => 'ssh-dss',
+ 'ed25519' => 'ssh-ed25519',
+ 'rsa' => 'ssh-rsa',
+ }
types.each do |type|
it "should update an entry with #{type} type" do
manifest = "#{type_under_test} { '#{sshkey_name}':
- ensure => 'present',
- type => '#{type}',
- key => 'mynewshinykey',
- target => '#{@sshkey_file}' }"
+ ensure => 'present',
+ type => '#{type}',
+ key => 'mynewshinykey',
+ target => '#{sshkey_file}' }"
apply_with_error_check(manifest)
- if aliases.has_key?(type)
+ if aliases.key?(type)
full_type = aliases[type]
- expect(File.read(@sshkey_file)).
- to match(/#{sshkey_name}.*#{full_type}.*mynew/)
+ expect(File.read(sshkey_file)).to match(%r{#{sshkey_name}.*#{full_type}.*mynew})
else
- expect(File.read(@sshkey_file)).
- to match(/#{sshkey_name}.*#{type}.*mynew/)
+ expect(File.read(sshkey_file)).to match(%r{#{sshkey_name}.*#{type}.*mynew})
end
end
end
# test unknown key type fails
- let(:invalid_type) { 'ssh-er0ck' }
- it "should raise an error with an unknown type" do
+ it 'raises an error with an unknown type' do
manifest = "#{type_under_test} { '#{sshkey_name}':
- ensure => 'present',
- type => '#{invalid_type}',
- key => 'mynewshinykey',
- target => '#{@sshkey_file}' }"
+ ensure => 'present',
+ type => '#{invalid_type}',
+ key => 'mynewshinykey',
+ target => '#{sshkey_file}' }"
expect {
- apply_compiled_manifest(manifest)
- }.to raise_error(Puppet::ResourceError, /Invalid value "#{invalid_type}"/)
+ apply_compiled_manifest(manifest)
+ }.to raise_error(Puppet::ResourceError, %r{Invalid value "#{invalid_type}"})
end
- #single host_alias
- let(:host_alias) { 'r0ckdata.com' }
- it "should update an entry with new host_alias" do
+ # single host_alias
+ it 'updates an entry with a single new host_alias' do
manifest = "#{type_under_test} { '#{sshkey_name}':
- ensure => 'present',
- host_aliases => '#{host_alias}',
- target => '#{@sshkey_file}' }"
+ ensure => 'present',
+ host_aliases => '#{host_alias}',
+ target => '#{sshkey_file}' }"
apply_with_error_check(manifest)
- expect(File.read(@sshkey_file)).to match(/#{sshkey_name},#{host_alias}\s/)
- expect(File.read(@sshkey_file)).not_to match(/#{sshkey_name}\s/)
+ expect(File.read(sshkey_file)).to match(%r{#{sshkey_name},#{host_alias}\s})
+ expect(File.read(sshkey_file)).not_to match(%r{#{sshkey_name}\s})
end
- #array host_alias
- let(:host_aliases) { "r0ckdata.com,erict.net" }
- it "should update an entry with new host_alias" do
+ # array host_alias
+ it 'updates an entry with multiple new host_aliases' do
manifest = "#{type_under_test} { '#{sshkey_name}':
- ensure => 'present',
- host_aliases => '#{host_alias}',
- target => '#{@sshkey_file}' }"
+ ensure => 'present',
+ host_aliases => [ 'r0ckdata.com', 'erict.net' ],
+ target => '#{sshkey_file}' }"
apply_with_error_check(manifest)
- expect(File.read(@sshkey_file)).to match(/#{sshkey_name},#{host_alias}\s/)
- expect(File.read(@sshkey_file)).not_to match(/#{sshkey_name}\s/)
+ expect(File.read(sshkey_file)).to match(%r{#{sshkey_name},r0ckdata\.com,erict\.net\s})
+ expect(File.read(sshkey_file)).not_to match(%r{#{sshkey_name}\s})
end
- #puppet resource sshkey
- it "should fetch an entry from resources" do
- @resource_app = Puppet::Application[:resource]
- @resource_app.preinit
- @resource_app.command_line.stubs(:args).
- returns([type_under_test, sshkey_name, "target=#{@sshkey_file}"])
+ # puppet resource sshkey
+ it 'fetches an entry from resources' do
+ resource_app = Puppet::Application[:resource]
+ resource_app.preinit
+ resource_app.command_line
+ .stubs(:args)
+ .returns([type_under_test, sshkey_name, "target=#{sshkey_file}"])
- @resource_app.expects(:puts).with do |args|
- expect(args).to match(/#{sshkey_name}/)
+ resource_app.expects(:puts).with do |args|
+ expect(args).to match(%r{#{sshkey_name}})
end
- @resource_app.main
+ resource_app.main
end
-
end
-
end
diff --git a/spec/lib/puppet_spec/compiler.rb b/spec/lib/puppet_spec/compiler.rb
index 8964a26..49a6534 100644
--- a/spec/lib/puppet_spec/compiler.rb
+++ b/spec/lib/puppet_spec/compiler.rb
@@ -34,8 +34,8 @@ module PuppetSpec::Compiler
catalog.resources.each { |res| yield res }
end
transaction = Puppet::Transaction.new(catalog,
- Puppet::Transaction::Report.new,
- prioritizer)
+ Puppet::Transaction::Report.new,
+ prioritizer)
transaction.evaluate
transaction.report.finalize_report
@@ -70,7 +70,7 @@ module PuppetSpec::Compiler
collect_notices(code, node) do |compiler|
unless topscope_vars.empty?
scope = compiler.topscope
- topscope_vars.each {|k,v| scope.setvar(k, v) }
+ topscope_vars.each { |k, v| scope.setvar(k, v) }
end
if block_given?
compiler.compile do |catalog|
@@ -90,12 +90,12 @@ module PuppetSpec::Compiler
# (Parameters given by name)
#
def evaluate(code: 'undef', source: nil, node: Puppet::Node.new('testnode'), variables: {})
- source_location = caller[0]
+ source_location = caller(0..0).first
Puppet[:code] = code
compiler = Puppet::Parser::Compiler.new(node)
unless variables.empty?
scope = compiler.topscope
- variables.each {|k,v| scope.setvar(k, v) }
+ variables.each { |k, v| scope.setvar(k, v) }
end
if source.nil?
@@ -105,7 +105,7 @@ module PuppetSpec::Compiler
end
# evaluate given source is the context of the compiled state and return its result
- compiler.compile do |catalog |
+ compiler.compile do |_catalog|
Puppet::Pops::Parser::EvaluatingParser.singleton.evaluate_string(compiler.topscope, source, source_location)
end
end
diff --git a/spec/spec_helper_acceptance.rb b/spec/spec_helper_acceptance.rb
new file mode 100644
index 0000000..ac6b27e
--- /dev/null
+++ b/spec/spec_helper_acceptance.rb
@@ -0,0 +1,26 @@
+require 'beaker-rspec'
+require 'beaker/module_install_helper'
+require 'beaker/puppet_install_helper'
+
+def beaker_opts
+ { debug: true, trace: true, expect_failures: true, acceptable_exit_codes: (0...256) }
+ # { expect_failures: true, acceptable_exit_codes: (0...256) }
+end
+
+def posix_agents
+ agents.reject { |agent| agent['platform'].include?('windows') }
+end
+
+def osx_agents
+ agents.select { |agent| agent['platform'].include?('osx') }
+end
+
+RSpec.configure do |c|
+ c.before :suite do
+ unless ENV['BEAKER_provision'] == 'no'
+ run_puppet_install_helper
+ install_module_on(hosts_as('default'))
+ install_module_dependencies_on(hosts)
+ end
+ end
+end
diff --git a/spec/spec_helper_local.rb b/spec/spec_helper_local.rb
index fc786a6..f06b4bb 100644
--- a/spec/spec_helper_local.rb
+++ b/spec/spec_helper_local.rb
@@ -8,10 +8,10 @@ end
require 'puppet_spec/files'
RSpec.configure do |config|
- config.before :each do |test|
+ config.before :each do |_test|
base = PuppetSpec::Files.tmpdir('tmp_settings')
Puppet[:vardir] = File.join(base, 'var')
FileUtils.mkdir_p Puppet[:statedir]
end
-end \ No newline at end of file
+end
diff --git a/spec/unit/provider/sshkey/parsed_spec.rb b/spec/unit/provider/sshkey/parsed_spec.rb
index 38aa7f7..6442183 100644
--- a/spec/unit/provider/sshkey/parsed_spec.rb
+++ b/spec/unit/provider/sshkey/parsed_spec.rb
@@ -1,68 +1,69 @@
-#! /usr/bin/env ruby
require 'spec_helper'
-describe "sshkey parsed provider" do
- let :type do Puppet::Type.type(:sshkey) end
- let :provider do type.provider(:parsed) end
+describe 'sshkey parsed provider' do
subject { provider }
+ let(:type) { Puppet::Type.type(:sshkey) }
+ let(:provider) { type.provider(:parsed) }
+
after :each do
subject.clear
end
def key
- 'AAAAB3NzaC1yc2EAAAABIwAAAQEAzwHhxXvIrtfIwrudFqc8yQcIfMudrgpnuh1F3AV6d2BrLgu/yQE7W5UyJMUjfj427sQudRwKW45O0Jsnr33F4mUw+GIMlAAmp9g24/OcrTiB8ZUKIjoPy/cO4coxGi8/NECtRzpD/ZUPFh6OEpyOwJPMb7/EC2Az6Otw4StHdXUYw22zHazBcPFnv6zCgPx1hA7QlQDWTu4YcL0WmTYQCtMUb3FUqrcFtzGDD0ytosgwSd+JyN5vj5UwIABjnNOHPZ62EY1OFixnfqX/+dUwrFSs5tPgBF/KkC6R7tmbUfnBON6RrGEmu+ajOTOLy23qUZB4CQ53V7nyAWhzqSK+hw=='
+ 'AAAAB3NzaC1yc2EAAAABIwAAAQEAzwHhxXvIrtfIwrudFqc8yQcIfMudrgpnuh1F3AV6d2BrLgu/yQE7W5UyJMUjfj427sQudRwKW45O0Jsnr33F4mUw+GIMlAAmp9g24/OcrTiB8ZUKIjoPy/cO4coxGi8/NECtRzpD/ZUPFh6OEpyOwJPMb7/EC2Az6Otw4StHdXUYw22zHazBcPFnv6zCgPx1hA7QlQDWTu4YcL0WmTYQCtMUb3FUqrcFtzGDD0ytosgwSd+JyN5vj5UwIABjnNOHPZ62EY1OFixnfqX/+dUwrFSs5tPgBF/KkC6R7tmbUfnBON6RrGEmu+ajOTOLy23qUZB4CQ53V7nyAWhzqSK+hw==' # rubocop:disable Metrics/LineLength
end
- it "should parse the name from the first field" do
- expect(subject.parse_line('test ssh-rsa '+key)[:name]).to eq("test")
+ it 'parses the name from the first field' do
+ expect(subject.parse_line('test ssh-rsa ' + key)[:name]).to eq('test')
end
- it "should parse the first component of the first field as the name" do
- expect(subject.parse_line('test,alias ssh-rsa '+key)[:name]).to eq("test")
+ it 'parses the first component of the first field as the name' do
+ expect(subject.parse_line('test,alias ssh-rsa ' + key)[:name]).to eq('test')
end
- it "should parse host_aliases from the remaining components of the first field" do
- expect(subject.parse_line('test,alias ssh-rsa '+key)[:host_aliases]).to eq(["alias"])
+ it 'parses host_aliases from the remaining components of the first field' do
+ expect(subject.parse_line('test,alias ssh-rsa ' + key)[:host_aliases]).to eq(['alias'])
end
- it "should parse multiple host_aliases" do
- expect(subject.parse_line('test,alias1,alias2,alias3 ssh-rsa '+key)[:host_aliases]).to eq(["alias1","alias2","alias3"])
+ it 'parses multiple host_aliases' do
+ expect(subject.parse_line('test,alias1,alias2,alias3 ssh-rsa ' + key)[:host_aliases]).to eq(['alias1', 'alias2', 'alias3'])
end
- it "should not drop an empty host_alias" do
- expect(subject.parse_line('test,alias, ssh-rsa '+key)[:host_aliases]).to eq(["alias",""])
+ it 'does not drop an empty host_alias' do
+ expect(subject.parse_line('test,alias, ssh-rsa ' + key)[:host_aliases]).to eq(['alias', ''])
end
- it "should recognise when there are no host aliases" do
- expect(subject.parse_line('test ssh-rsa '+key)[:host_aliases]).to eq([])
+ it 'recognises when there are no host aliases' do
+ expect(subject.parse_line('test ssh-rsa ' + key)[:host_aliases]).to eq([])
end
- context "with the sample file" do
+ context 'with the sample file' do
['sample', 'sample_with_blank_lines'].each do |sample_file|
- let :fixture do my_fixture(sample_file) end
- before :each do subject.stubs(:default_target).returns(fixture) end
+ let(:fixture) { my_fixture(sample_file) }
+
+ before(:each) { subject.stubs(:default_target).returns(fixture) }
- it "should parse to records on prefetch" do
+ it 'parses to records on prefetch' do
expect(subject.target_records(fixture)).to be_empty
subject.prefetch
records = subject.target_records(fixture)
expect(records).to be_an Array
- expect(records).to be_all {|x| expect(x).to be_an Hash }
+ expect(records).to(be_all { |x| expect(x).to be_an(Hash) })
end
- it "should reconstitute the file from records" do
+ it 'reconstitutes the file from records' do
subject.prefetch
records = subject.target_records(fixture)
- text = subject.to_file(records).gsub(/^# HEADER.+\n/, '')
+ text = subject.to_file(records).gsub(%r{^# HEADER.+\n}, '')
oldlines = File.readlines(fixture).map(&:chomp)
newlines = text.chomp.split("\n")
expect(oldlines.length).to eq(newlines.length)
oldlines.zip(newlines).each do |old, new|
- expect(old.gsub(/\s+/, '')).to eq(new.gsub(/\s+/, ''))
+ expect(old.gsub(%r{\s+}, '')).to eq(new.gsub(%r{\s+}, ''))
end
end
end
@@ -70,7 +71,7 @@ describe "sshkey parsed provider" do
context 'default ssh_known_hosts target path' do
['9.10', '9.11', '10.10'].each do |version|
- it 'should be `/etc/ssh_known_hosts` when OSX version 10.10 or older`' do
+ it 'is `/etc/ssh_known_hosts` when OSX version 10.10 or older`' do
Facter.expects(:value).with(:operatingsystem).returns('Darwin')
Facter.expects(:value).with(:macosx_productversion_major).returns(version)
expect(subject.default_target).to eq('/etc/ssh_known_hosts')
@@ -78,14 +79,14 @@ describe "sshkey parsed provider" do
end
['10.11', '10.13', '11.0', '11.11'].each do |version|
- it 'should be `/etc/ssh/ssh_known_hosts` when OSX version 10.11 or newer`' do
+ it 'is `/etc/ssh/ssh_known_hosts` when OSX version 10.11 or newer`' do
Facter.expects(:value).with(:operatingsystem).returns('Darwin')
Facter.expects(:value).with(:macosx_productversion_major).returns(version)
expect(subject.default_target).to eq('/etc/ssh/ssh_known_hosts')
end
end
- it 'should be `/etc/ssh/ssh_known_hosts` on other operating systems' do
+ it 'is `/etc/ssh/ssh_known_hosts` on other operating systems' do
Facter.expects(:value).with(:operatingsystem).returns('RedHat')
expect(subject.default_target).to eq('/etc/ssh/ssh_known_hosts')
end
diff --git a/spec/unit/type/ssh_authorized_key_spec.rb b/spec/unit/type/ssh_authorized_key_spec.rb
index ae93667..e375f58 100644
--- a/spec/unit/type/ssh_authorized_key_spec.rb
+++ b/spec/unit/type/ssh_authorized_key_spec.rb
@@ -1,25 +1,22 @@
-#! /usr/bin/env ruby
require 'spec_helper'
-
-describe Puppet::Type.type(:ssh_authorized_key), :unless => Puppet.features.microsoft_windows? do
+describe Puppet::Type.type(:ssh_authorized_key), unless: Puppet.features.microsoft_windows? do
include PuppetSpec::Files
- before do
- provider_class = stub 'provider_class', :name => "fake", :suitable? => true, :supports_parameter? => true
+ before(:each) do
+ provider_class = stub 'provider_class', name: 'fake', suitable?: true, supports_parameter?: true
described_class.stubs(:defaultprovider).returns(provider_class)
described_class.stubs(:provider).returns(provider_class)
- provider = stub 'provider', :class => provider_class, :file_path => make_absolute("/tmp/whatever"), :clear => nil
+ provider = stub 'provider', class: provider_class, file_path: make_absolute('/tmp/whatever'), clear: nil
provider_class.stubs(:new).returns(provider)
end
- it "has :name as its namevar" do
+ it 'has :name as its namevar' do
expect(described_class.key_attributes).to eq [:name]
end
- describe "when validating attributes" do
-
+ describe 'when validating attributes' do
[:name, :provider].each do |param|
it "has a #{param} parameter" do
expect(described_class.attrtype(param)).to eq :param
@@ -31,228 +28,211 @@ describe Puppet::Type.type(:ssh_authorized_key), :unless => Puppet.features.micr
expect(described_class.attrtype(property)).to eq :property
end
end
-
end
- describe "when validating values" do
-
- describe "for name" do
-
- it "supports valid names" do
- described_class.new(:name => "username", :ensure => :present, :user => "nobody")
- described_class.new(:name => "username@hostname", :ensure => :present, :user => "nobody")
+ describe 'when validating values' do
+ describe 'for name' do
+ it 'supports valid names' do
+ described_class.new(name: 'username', ensure: :present, user: 'nobody')
+ described_class.new(name: 'username@hostname', ensure: :present, user: 'nobody')
end
- it "supports whitespace" do
- described_class.new(:name => "my test", :ensure => :present, :user => "nobody")
+ it 'supports whitespace' do
+ described_class.new(name: 'my test', ensure: :present, user: 'nobody')
end
-
end
- describe "for ensure" do
-
- it "supports :present" do
- described_class.new(:name => "whev", :ensure => :present, :user => "nobody")
+ describe 'for ensure' do
+ it 'supports :present' do
+ described_class.new(name: 'whev', ensure: :present, user: 'nobody')
end
- it "supports :absent" do
- described_class.new(:name => "whev", :ensure => :absent, :user => "nobody")
+ it 'supports :absent' do
+ described_class.new(name: 'whev', ensure: :absent, user: 'nobody')
end
- it "nots support other values" do
- expect { described_class.new(:name => "whev", :ensure => :foo, :user => "nobody") }.to raise_error(Puppet::Error, /Invalid value/)
+ it 'nots support other values' do
+ expect { described_class.new(name: 'whev', ensure: :foo, user: 'nobody') }.to raise_error(Puppet::Error, %r{Invalid value})
end
-
end
- describe "for type" do
-
+ describe 'for type' do
[
:'ssh-dss', :dsa,
:'ssh-rsa', :rsa,
:'ecdsa-sha2-nistp256',
:'ecdsa-sha2-nistp384',
:'ecdsa-sha2-nistp521',
- :ed25519, :'ssh-ed25519',
+ :ed25519, :'ssh-ed25519'
].each do |keytype|
it "supports #{keytype}" do
- described_class.new(:name => "whev", :type => keytype, :user => "nobody")
+ described_class.new(name: 'whev', type: keytype, user: 'nobody')
end
end
- it "aliases :rsa to :ssh-rsa" do
- key = described_class.new(:name => "whev", :type => :rsa, :user => "nobody")
+ it 'aliases :rsa to :ssh-rsa' do
+ key = described_class.new(name: 'whev', type: :rsa, user: 'nobody')
expect(key.should(:type)).to eq :'ssh-rsa'
end
- it "aliases :dsa to :ssh-dss" do
- key = described_class.new(:name => "whev", :type => :dsa, :user => "nobody")
+ it 'aliases :dsa to :ssh-dss' do
+ key = described_class.new(name: 'whev', type: :dsa, user: 'nobody')
expect(key.should(:type)).to eq :'ssh-dss'
end
it "doesn't support values other than ssh-dss, ssh-rsa, dsa, rsa" do
- expect { described_class.new(:name => "whev", :type => :something) }.to raise_error(Puppet::Error,/Invalid value/)
+ expect { described_class.new(name: 'whev', type: :something) }.to raise_error(Puppet::Error, %r{Invalid value})
end
-
end
- describe "for key" do
-
- it "supports a valid key like a 1024 bit rsa key" do
- expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :key => 'AAAAB3NzaC1yc2EAAAADAQABAAAAgQDCPfzW2ry7XvMc6E5Kj2e5fF/YofhKEvsNMUogR3PGL/HCIcBlsEjKisrY0aYgD8Ikp7ZidpXLbz5dBsmPy8hJiBWs5px9ZQrB/EOQAwXljvj69EyhEoGawmxQMtYw+OAIKHLJYRuk1QiHAMHLp5piqem8ZCV2mLb9AsJ6f7zUVw==')}.to_not raise_error
+ describe 'for key' do
+ # rubocop:disable Metrics/LineLength
+ it 'supports a valid key like a 1024 bit rsa key' do
+ expect { described_class.new(name: 'whev', type: :rsa, user: 'nobody', key: 'AAAAB3NzaC1yc2EAAAADAQABAAAAgQDCPfzW2ry7XvMc6E5Kj2e5fF/YofhKEvsNMUogR3PGL/HCIcBlsEjKisrY0aYgD8Ikp7ZidpXLbz5dBsmPy8hJiBWs5px9ZQrB/EOQAwXljvj69EyhEoGawmxQMtYw+OAIKHLJYRuk1QiHAMHLp5piqem8ZCV2mLb9AsJ6f7zUVw==') }.not_to raise_error
end
+ # rubocop:enable Metrics/LineLength
- it "supports a valid key like a 4096 bit rsa key" do
- expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :key => 'AAAAB3NzaC1yc2EAAAADAQABAAACAQDEY4pZFyzSfRc9wVWI3DfkgT/EL033UZm/7x1M+d+lBD00qcpkZ6CPT7lD3Z+vylQlJ5S8Wcw6C5Smt6okZWY2WXA9RCjNJMIHQbJAzwuQwgnwU/1VMy9YPp0tNVslg0sUUgpXb13WW4mYhwxyGmIVLJnUrjrQmIFhtfHsJAH8ZVqCWaxKgzUoC/YIu1u1ScH93lEdoBPLlwm6J0aiM7KWXRb7Oq1nEDZtug1zpX5lhgkQWrs0BwceqpUbY+n9sqeHU5e7DCyX/yEIzoPRW2fe2Gx1Iq6JKM/5NNlFfaW8rGxh3Z3S1NpzPHTRjw8js3IeGiV+OPFoaTtM1LsWgPDSBlzIdyTbSQR7gKh0qWYCNV/7qILEfa0yIFB5wIo4667iSPZw2pNgESVtenm8uXyoJdk8iWQ4mecdoposV/znknNb2GPgH+n/2vme4btZ0Sl1A6rev22GQjVgbWOn8zaDglJ2vgCN1UAwmq41RXprPxENGeLnWQppTnibhsngu0VFllZR5kvSIMlekLRSOFLFt92vfd+tk9hZIiKm9exxcbVCGGQPsf6dZ27rTOmg0xM2Sm4J6RRKuz79HQgA4Eg18+bqRP7j/itb89DmtXEtoZFAsEJw8IgIfeGGDtHTkfAlAC92mtK8byeaxGq57XCTKbO/r5gcOMElZHy1AcB8kw==')}.to_not raise_error
+ # rubocop:disable Metrics/LineLength
+ it 'supports a valid key like a 4096 bit rsa key' do
+ expect { described_class.new(name: 'whev', type: :rsa, user: 'nobody', key: 'AAAAB3NzaC1yc2EAAAADAQABAAACAQDEY4pZFyzSfRc9wVWI3DfkgT/EL033UZm/7x1M+d+lBD00qcpkZ6CPT7lD3Z+vylQlJ5S8Wcw6C5Smt6okZWY2WXA9RCjNJMIHQbJAzwuQwgnwU/1VMy9YPp0tNVslg0sUUgpXb13WW4mYhwxyGmIVLJnUrjrQmIFhtfHsJAH8ZVqCWaxKgzUoC/YIu1u1ScH93lEdoBPLlwm6J0aiM7KWXRb7Oq1nEDZtug1zpX5lhgkQWrs0BwceqpUbY+n9sqeHU5e7DCyX/yEIzoPRW2fe2Gx1Iq6JKM/5NNlFfaW8rGxh3Z3S1NpzPHTRjw8js3IeGiV+OPFoaTtM1LsWgPDSBlzIdyTbSQR7gKh0qWYCNV/7qILEfa0yIFB5wIo4667iSPZw2pNgESVtenm8uXyoJdk8iWQ4mecdoposV/znknNb2GPgH+n/2vme4btZ0Sl1A6rev22GQjVgbWOn8zaDglJ2vgCN1UAwmq41RXprPxENGeLnWQppTnibhsngu0VFllZR5kvSIMlekLRSOFLFt92vfd+tk9hZIiKm9exxcbVCGGQPsf6dZ27rTOmg0xM2Sm4J6RRKuz79HQgA4Eg18+bqRP7j/itb89DmtXEtoZFAsEJw8IgIfeGGDtHTkfAlAC92mtK8byeaxGq57XCTKbO/r5gcOMElZHy1AcB8kw==') }.not_to raise_error # rubocop:disable Metrics/LineLength
end
+ # rubocop:enable Metrics/LineLength
- it "supports a valid key like a 1024 bit dsa key" do
- expect { described_class.new(:name => "whev", :type => :dsa, :user => "nobody", :key => 'AAAAB3NzaC1kc3MAAACBAI80iR78QCgpO4WabVqHHdEDigOjUEHwIjYHIubR/7u7DYrXY+e+TUmZ0CVGkiwB/0yLHK5dix3Y/bpj8ZiWCIhFeunnXccOdE4rq5sT2V3l1p6WP33RpyVYbLmeuHHl5VQ1CecMlca24nHhKpfh6TO/FIwkMjghHBfJIhXK+0w/AAAAFQDYzLupuMY5uz+GVrcP+Kgd8YqMmwAAAIB3SVN71whLWjFPNTqGyyIlMy50624UfNOaH4REwO+Of3wm/cE6eP8n75vzTwQGBpJX3BPaBGW1S1Zp/DpTOxhCSAwZzAwyf4WgW7YyAOdxN3EwTDJZeyiyjWMAOjW9/AOWt9gtKg0kqaylbMHD4kfiIhBzo31ZY81twUzAfN7angAAAIBfva8sTSDUGKsWWIXkdbVdvM4X14K4gFdy0ZJVzaVOtZ6alysW6UQypnsl6jfnbKvsZ0tFgvcX/CPyqNY/gMR9lyh/TCZ4XQcbqeqYPuceGehz+jL5vArfqsW2fJYFzgCcklmr/VxtP5h6J/T0c9YcDgc/xIfWdZAlznOnphI/FA==')}.to_not raise_error
+ # rubocop:disable Metrics/LineLength
+ it 'supports a valid key like a 1024 bit dsa key' do
+ expect { described_class.new(name: 'whev', type: :dsa, user: 'nobody', key: 'AAAAB3NzaC1kc3MAAACBAI80iR78QCgpO4WabVqHHdEDigOjUEHwIjYHIubR/7u7DYrXY+e+TUmZ0CVGkiwB/0yLHK5dix3Y/bpj8ZiWCIhFeunnXccOdE4rq5sT2V3l1p6WP33RpyVYbLmeuHHl5VQ1CecMlca24nHhKpfh6TO/FIwkMjghHBfJIhXK+0w/AAAAFQDYzLupuMY5uz+GVrcP+Kgd8YqMmwAAAIB3SVN71whLWjFPNTqGyyIlMy50624UfNOaH4REwO+Of3wm/cE6eP8n75vzTwQGBpJX3BPaBGW1S1Zp/DpTOxhCSAwZzAwyf4WgW7YyAOdxN3EwTDJZeyiyjWMAOjW9/AOWt9gtKg0kqaylbMHD4kfiIhBzo31ZY81twUzAfN7angAAAIBfva8sTSDUGKsWWIXkdbVdvM4X14K4gFdy0ZJVzaVOtZ6alysW6UQypnsl6jfnbKvsZ0tFgvcX/CPyqNY/gMR9lyh/TCZ4XQcbqeqYPuceGehz+jL5vArfqsW2fJYFzgCcklmr/VxtP5h6J/T0c9YcDgc/xIfWdZAlznOnphI/FA==') }.not_to raise_error # rubocop:disable Metrics/LineLength
end
+ # rubocop:enable Metrics/LineLength
it "doesn't support whitespaces" do
- expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :key => 'AAA FA==')}.to raise_error(Puppet::Error,/Key must not contain whitespace/)
+ expect { described_class.new(name: 'whev', type: :rsa, user: 'nobody', key: 'AAA FA==') }.to raise_error(Puppet::Error, %r{Key must not contain whitespace})
end
-
end
- describe "for options" do
-
- it "supports flags as options" do
- expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'cert-authority')}.to_not raise_error
- expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'no-port-forwarding')}.to_not raise_error
+ describe 'for options' do
+ it 'supports flags as options' do
+ expect { described_class.new(name: 'whev', type: :rsa, user: 'nobody', options: 'cert-authority') }.not_to raise_error
+ expect { described_class.new(name: 'whev', type: :rsa, user: 'nobody', options: 'no-port-forwarding') }.not_to raise_error
end
- it "supports key-value pairs as options" do
- expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'command="command"')}.to_not raise_error
+ it 'supports key-value pairs as options' do
+ expect { described_class.new(name: 'whev', type: :rsa, user: 'nobody', options: 'command="command"') }.not_to raise_error
end
- it "supports key-value pairs where value consist of multiple items" do
- expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'from="*.domain1,host1.domain2"')}.to_not raise_error
+ it 'supports key-value pairs where value consist of multiple items' do
+ expect { described_class.new(name: 'whev', type: :rsa, user: 'nobody', options: 'from="*.domain1,host1.domain2"') }.not_to raise_error
end
- it "supports environments as options" do
- expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'environment="NAME=value"')}.to_not raise_error
+ it 'supports environments as options' do
+ expect { described_class.new(name: 'whev', type: :rsa, user: 'nobody', options: 'environment="NAME=value"') }.not_to raise_error
end
- it "supports multiple options as an array" do
- expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => ['cert-authority','environment="NAME=value"'])}.to_not raise_error
+ it 'supports multiple options as an array' do
+ expect { described_class.new(name: 'whev', type: :rsa, user: 'nobody', options: ['cert-authority', 'environment="NAME=value"']) }.not_to raise_error
end
it "doesn't support a comma separated list" do
- expect { described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => 'cert-authority,no-port-forwarding')}.to raise_error(Puppet::Error, /must be provided as an array/)
+ expect { described_class.new(name: 'whev', type: :rsa, user: 'nobody', options: 'cert-authority,no-port-forwarding') }.to raise_error(Puppet::Error, %r{must be provided as an array})
end
- it "uses :absent as a default value" do
- expect(described_class.new(:name => "whev", :type => :rsa, :user => "nobody").should(:options)).to eq [:absent]
+ it 'uses :absent as a default value' do
+ expect(described_class.new(name: 'whev', type: :rsa, user: 'nobody').should(:options)).to eq [:absent]
end
- it "property should return well formed string of arrays from is_to_s" do
- resource = described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => ["a","b","c"])
- expect(resource.property(:options).is_to_s(["a","b","c"])).to eq "['a', 'b', 'c']"
+ it 'property should return well formed string of arrays from is_to_s' do
+ resource = described_class.new(name: 'whev', type: :rsa, user: 'nobody', options: ['a', 'b', 'c'])
+ expect(resource.property(:options).is_to_s(['a', 'b', 'c'])).to eq "['a', 'b', 'c']"
end
- it "property should return well formed string of arrays from should_to_s" do
- resource = described_class.new(:name => "whev", :type => :rsa, :user => "nobody", :options => ["a","b","c"])
- expect(resource.property(:options).should_to_s(["a","b","c"])).to eq "['a', 'b', 'c']"
+ it 'property should return well formed string of arrays from should_to_s' do
+ resource = described_class.new(name: 'whev', type: :rsa, user: 'nobody', options: ['a', 'b', 'c'])
+ expect(resource.property(:options).should_to_s(['a', 'b', 'c'])).to eq "['a', 'b', 'c']"
end
-
end
- describe "for user" do
-
- it "supports present users" do
- described_class.new(:name => "whev", :type => :rsa, :user => "root")
+ describe 'for user' do
+ it 'supports present users' do
+ described_class.new(name: 'whev', type: :rsa, user: 'root')
end
- it "supports absent users" do
- described_class.new(:name => "whev", :type => :rsa, :user => "ihopeimabsent")
+ it 'supports absent users' do
+ described_class.new(name: 'whev', type: :rsa, user: 'ihopeimabsent')
end
-
end
- describe "for target" do
-
- it "supports absolute paths" do
- described_class.new(:name => "whev", :type => :rsa, :target => "/tmp/here")
+ describe 'for target' do
+ it 'supports absolute paths' do
+ described_class.new(name: 'whev', type: :rsa, target: '/tmp/here')
end
it "uses the user's path if not explicitly specified" do
- expect(described_class.new(:name => "whev", :user => 'root').should(:target)).to eq File.expand_path("~root/.ssh/authorized_keys")
+ expect(described_class.new(name: 'whev', user: 'root').should(:target)).to eq File.expand_path('~root/.ssh/authorized_keys')
end
it "doesn't consider the user's path if explicitly specified" do
- expect(described_class.new(:name => "whev", :user => 'root', :target => '/tmp/here').should(:target)).to eq '/tmp/here'
+ expect(described_class.new(name: 'whev', user: 'root', target: '/tmp/here').should(:target)).to eq '/tmp/here'
end
- it "informs about an absent user" do
+ it 'informs about an absent user' do
Puppet::Log.level = :debug
- described_class.new(:name => "whev", :user => 'idontexist').should(:target)
- expect(@logs.map(&:message)).to include("The required user is not yet present on the system")
+ logs = []
+ Puppet::Util::Log.with_destination(Puppet::Test::LogCollector.new(logs)) do
+ described_class.new(name: 'whev', user: 'idontexist').should(:target)
+ end
+ expect(logs.map(&:message)).to include('The required user is not yet present on the system')
end
-
end
-
end
- describe "when neither user nor target is specified" do
-
- it "raises an error" do
- expect do
+ describe 'when neither user nor target is specified' do
+ it 'raises an error' do
+ expect {
described_class.new(
- :name => "Test",
- :key => "AAA",
- :type => "ssh-rsa",
- :ensure => :present)
- end.to raise_error(Puppet::Error,/user.*or.*target.*mandatory/)
+ name: 'Test',
+ key: 'AAA',
+ type: 'ssh-rsa',
+ ensure: :present,
+ )
+ }.to raise_error(Puppet::Error, %r{user.*or.*target.*mandatory})
end
-
end
- describe "when both target and user are specified" do
-
- it "uses target" do
+ describe 'when both target and user are specified' do
+ it 'uses target' do
resource = described_class.new(
- :name => "Test",
- :user => "root",
- :target => "/tmp/blah"
+ name: 'Test',
+ user: 'root',
+ target: '/tmp/blah',
)
- expect(resource.should(:target)).to eq "/tmp/blah"
+ expect(resource.should(:target)).to eq '/tmp/blah'
end
-
end
-
- describe "when user is specified" do
-
- it "determines target" do
+ describe 'when user is specified' do
+ it 'determines target' do
resource = described_class.new(
- :name => "Test",
- :user => "root"
+ name: 'Test',
+ user: 'root',
)
- target = File.expand_path("~root/.ssh/authorized_keys")
+ target = File.expand_path('~root/.ssh/authorized_keys')
expect(resource.should(:target)).to eq target
end
# Bug #2124 - ssh_authorized_key always changes target if target is not defined
it "doesn't raise spurious change events" do
- resource = described_class.new(:name => "Test", :user => "root")
- target = File.expand_path("~root/.ssh/authorized_keys")
+ resource = described_class.new(name: 'Test', user: 'root')
+ target = File.expand_path('~root/.ssh/authorized_keys')
expect(resource.property(:target).safe_insync?(target)).to eq true
end
-
end
- describe "when calling validate" do
-
+ describe 'when calling validate' do
it "doesn't crash on a non-existent user" do
resource = described_class.new(
- :name => "Test",
- :user => "ihopesuchuserdoesnotexist"
+ name: 'Test',
+ user: 'ihopesuchuserdoesnotexist',
)
resource.validate
end
-
end
-
end
diff --git a/spec/unit/type/sshkey_spec.rb b/spec/unit/type/sshkey_spec.rb
index d16e595..452610e 100644
--- a/spec/unit/type/sshkey_spec.rb
+++ b/spec/unit/type/sshkey_spec.rb
@@ -1,14 +1,11 @@
-#! /usr/bin/env ruby
require 'spec_helper'
-
describe Puppet::Type.type(:sshkey) do
-
- it "uses :name as its namevar" do
+ it 'uses :name as its namevar' do
expect(described_class.key_attributes).to eq [:name]
end
- describe "when validating attributes" do
+ describe 'when validating attributes' do
[:name, :provider].each do |param|
it "has a #{param} parameter" do
expect(described_class.attrtype(param)).to eq :param
@@ -22,56 +19,54 @@ describe Puppet::Type.type(:sshkey) do
end
end
- describe "when validating values" do
-
+ describe 'when validating values' do
[
:'ssh-dss', :dsa,
:'ssh-rsa', :rsa,
:'ecdsa-sha2-nistp256',
:'ecdsa-sha2-nistp384',
:'ecdsa-sha2-nistp521',
- :'ssh-ed25519', :ed25519,
+ :'ssh-ed25519', :ed25519
].each do |keytype|
it "supports #{keytype} as a type value" do
- described_class.new(:name => "foo", :type => keytype)
+ described_class.new(name: 'foo', type: keytype)
end
end
- it "aliases :rsa to :ssh-rsa" do
- key = described_class.new(:name => "foo", :type => :rsa)
+ it 'aliases :rsa to :ssh-rsa' do
+ key = described_class.new(name: 'foo', type: :rsa)
expect(key.should(:type)).to eq :'ssh-rsa'
end
- it "aliases :dsa to :ssh-dss" do
- key = described_class.new(:name => "foo", :type => :dsa)
+ it 'aliases :dsa to :ssh-dss' do
+ key = described_class.new(name: 'foo', type: :dsa)
expect(key.should(:type)).to eq :'ssh-dss'
end
it "doesn't support values other than ssh-dss, ssh-rsa, dsa, rsa for type" do
expect {
- described_class.new(:name => "whev", :type => :'ssh-dsa')
- }.to raise_error(Puppet::Error, /Invalid value.*ssh-dsa/)
+ described_class.new(name: 'whev', type: :'ssh-dsa')
+ }.to raise_error(Puppet::Error, %r{Invalid value.*ssh-dsa})
end
- it "accepts one host_alias" do
- described_class.new(:name => "foo", :host_aliases => 'foo.bar.tld')
+ it 'accepts one host_alias' do
+ described_class.new(name: 'foo', host_aliases: 'foo.bar.tld')
end
- it "accepts multiple host_aliases as an array" do
- described_class.new(:name => "foo", :host_aliases => ['foo.bar.tld','10.0.9.9'])
+ it 'accepts multiple host_aliases as an array' do
+ described_class.new(name: 'foo', host_aliases: ['foo.bar.tld', '10.0.9.9'])
end
it "doesn't accept spaces in any host_alias" do
expect {
- described_class.new(:name => "foo", :host_aliases => ['foo.bar.tld','foo bar'])
- }.to raise_error(Puppet::Error, /cannot include whitespace/)
+ described_class.new(name: 'foo', host_aliases: ['foo.bar.tld', 'foo bar'])
+ }.to raise_error(Puppet::Error, %r{cannot include whitespace})
end
it "doesn't accept aliases in the resourcename" do
expect {
- described_class.new(:name => 'host,host.domain,ip')
- }.to raise_error(Puppet::Error, /No comma in resourcename/)
+ described_class.new(name: 'host,host.domain,ip')
+ }.to raise_error(Puppet::Error, %r{No comma in resourcename})
end
-
end
end