From d714f122d19155afa00b2b990a9267b422e5946d Mon Sep 17 00:00:00 2001 From: david22swan Date: Wed, 29 Nov 2017 10:25:11 +0000 Subject: [PATCH] Rubocop Implemented (#735) * Rubocop Implemented --- .rubocop.yml | 586 +------ .rubocop_todo.yml | 0 .sync.yml | 3 + .travis.yml | 2 + lib/facter/ip6tables_version.rb | 4 +- lib/facter/iptables_persistent_version.rb | 16 +- lib/facter/iptables_version.rb | 4 +- lib/puppet/provider/firewall.rb | 13 +- lib/puppet/provider/firewall/ip6tables.rb | 281 ++- lib/puppet/provider/firewall/iptables.rb | 569 +++--- .../provider/firewallchain/iptables_chain.rb | 126 +- lib/puppet/type/firewall.rb | 688 ++++---- lib/puppet/type/firewallchain.rb | 101 +- lib/puppet/util/firewall.rb | 214 ++- lib/puppet/util/ipcidr.rb | 62 +- spec/acceptance/change_source_spec.rb | 35 +- spec/acceptance/class_spec.rb | 16 +- spec/acceptance/connlimit_spec.rb | 36 +- spec/acceptance/connmark_spec.rb | 14 +- spec/acceptance/firewall_bridging_spec.rb | 375 ++-- spec/acceptance/firewall_clusterip_spec.rb | 3 +- spec/acceptance/firewall_dscp_spec.rb | 55 +- spec/acceptance/firewall_gid_spec.rb | 80 +- spec/acceptance/firewall_iptmodules_spec.rb | 147 +- spec/acceptance/firewall_mss_spec.rb | 55 +- spec/acceptance/firewall_spec.rb | 1525 ++++++++--------- spec/acceptance/firewall_tee_spec.rb | 29 +- spec/acceptance/firewall_time_spec.rb | 44 +- spec/acceptance/firewall_uid_spec.rb | 80 +- spec/acceptance/firewallchain_spec.rb | 66 +- spec/acceptance/hashlimit_spec.rb | 82 +- spec/acceptance/invert_spec.rb | 39 +- spec/acceptance/ip6_fragment_spec.rb | 53 +- spec/acceptance/isfragment_spec.rb | 63 +- spec/acceptance/match_mark_spec.rb | 28 +- spec/acceptance/nflog_spec.rb | 95 +- spec/acceptance/params_spec.rb | 127 +- spec/acceptance/purge_spec.rb | 110 +- spec/acceptance/resource_cmd_spec.rb | 7 +- spec/acceptance/rules_spec.rb | 495 +++--- spec/acceptance/socket_spec.rb | 64 +- spec/acceptance/standard_usage_spec.rb | 11 +- spec/spec_helper_acceptance.rb | 16 +- spec/spec_helper_local.rb | 8 +- .../classes/firewall_linux_archlinux_spec.rb | 65 +- .../classes/firewall_linux_debian_spec.rb | 176 +- .../classes/firewall_linux_gentoo_spec.rb | 73 +- .../classes/firewall_linux_redhat_spec.rb | 178 +- spec/unit/classes/firewall_linux_spec.rb | 67 +- spec/unit/classes/firewall_spec.rb | 40 +- spec/unit/documentation/readme_spec.rb | 4 +- .../iptables_persistent_version_spec.rb | 85 +- spec/unit/facter/iptables_spec.rb | 16 +- spec/unit/puppet/provider/ip6tables_spec.rb | 29 +- .../puppet/provider/iptables_chain_spec.rb | 423 +++-- spec/unit/puppet/provider/iptables_spec.rb | 276 ++- spec/unit/puppet/type/firewall_spec.rb | 613 +++---- spec/unit/puppet/type/firewallchain_spec.rb | 117 +- spec/unit/puppet/util/firewall_spec.rb | 84 +- spec/unit/puppet/util/ipcidr_spec.rb | 74 +- 60 files changed, 4123 insertions(+), 4624 deletions(-) create mode 100644 .rubocop_todo.yml diff --git a/.rubocop.yml b/.rubocop.yml index 5aadd1b..d973ebd 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,508 +1,100 @@ -require: rubocop-rspec +--- +require: + - rubocop-rspec AllCops: - TargetRubyVersion: 1.9 + TargetRubyVersion: '2.1' Include: - - ./**/*.rb + - "./**/*.rb" Exclude: - - vendor/**/* - - .vendor/**/* - - pkg/**/* - - spec/fixtures/**/* -Lint/ConditionPosition: - Enabled: True - -Lint/ElseLayout: - Enabled: True - -Lint/UnreachableCode: - Enabled: True - -Lint/UselessComparison: - Enabled: True - -Lint/EnsureReturn: - Enabled: True - -Lint/HandleExceptions: - Enabled: True - -Lint/LiteralInCondition: - Enabled: True - -Lint/ShadowingOuterLocalVariable: - Enabled: True - -Lint/LiteralInInterpolation: - Enabled: True - -Style/HashSyntax: - Enabled: True - -Style/RedundantReturn: - Enabled: True - -Lint/AmbiguousOperator: - Enabled: True - -Lint/AssignmentInCondition: - Enabled: True - -Style/SpaceBeforeComment: - Enabled: True - -Style/AndOr: - Enabled: True - -Style/RedundantSelf: - Enabled: True - -# Method length is not necessarily an indicator of code quality -Metrics/MethodLength: - Enabled: False - -# Module length is not necessarily an indicator of code quality -Metrics/ModuleLength: - Enabled: False - -Style/WhileUntilModifier: - Enabled: True - -Lint/AmbiguousRegexpLiteral: - Enabled: True - -Lint/Eval: - Enabled: True - -Lint/BlockAlignment: - Enabled: True - -Lint/DefEndAlignment: - Enabled: True - -Lint/EndAlignment: - Enabled: True - -Lint/DeprecatedClassMethods: - Enabled: True - -Lint/Loop: - Enabled: True - -Lint/ParenthesesAsGroupedExpression: - Enabled: True - -Lint/RescueException: - Enabled: True - -Lint/StringConversionInInterpolation: - Enabled: True - -Lint/UnusedBlockArgument: - Enabled: True - -Lint/UnusedMethodArgument: - Enabled: True - -Lint/UselessAccessModifier: - Enabled: True - -Lint/UselessAssignment: - Enabled: True - -Lint/Void: - Enabled: True - -Style/AccessModifierIndentation: - Enabled: True - -Style/AccessorMethodName: - Enabled: True - -Style/Alias: - Enabled: True - -Style/AlignArray: - Enabled: True - -Style/AlignHash: - Enabled: True - -Style/AlignParameters: - Enabled: True - -Metrics/BlockNesting: - Enabled: True - -Style/AsciiComments: - Enabled: True - -Style/Attr: - Enabled: True - -Style/BracesAroundHashParameters: - Enabled: True - -Style/CaseEquality: - Enabled: True - -Style/CaseIndentation: - Enabled: True - -Style/CharacterLiteral: - Enabled: True - -Style/ClassAndModuleCamelCase: - Enabled: True - -Style/ClassAndModuleChildren: - Enabled: False - -Style/ClassCheck: - Enabled: True - -# Class length is not necessarily an indicator of code quality -Metrics/ClassLength: - Enabled: False - -Style/ClassMethods: - Enabled: True - -Style/ClassVars: - Enabled: True - -Style/WhenThen: - Enabled: True - -Style/WordArray: - Enabled: True - -Style/UnneededPercentQ: - Enabled: True - -Style/Tab: - Enabled: True - -Style/SpaceBeforeSemicolon: - Enabled: True - -Style/TrailingBlankLines: - Enabled: True - -Style/SpaceInsideBlockBraces: - Enabled: True - -Style/SpaceInsideBrackets: - Enabled: True - -Style/SpaceInsideHashLiteralBraces: - Enabled: True - -Style/SpaceInsideParens: - Enabled: True - -Style/LeadingCommentSpace: - Enabled: True - -Style/SpaceBeforeFirstArg: - Enabled: True - -Style/SpaceAfterColon: - Enabled: True - -Style/SpaceAfterComma: - Enabled: True - -Style/SpaceAfterMethodName: - Enabled: True - -Style/SpaceAfterNot: - Enabled: True - -Style/SpaceAfterSemicolon: - Enabled: True - -Style/SpaceAroundEqualsInParameterDefault: - Enabled: True - -Style/SpaceAroundOperators: - Enabled: True - -Style/SpaceBeforeBlockBraces: - Enabled: True - -Style/SpaceBeforeComma: - Enabled: True - -Style/CollectionMethods: - Enabled: True - -Style/CommentIndentation: - Enabled: True - -Style/ColonMethodCall: - Enabled: True - -Style/CommentAnnotation: - Enabled: True - -# 'Complexity' is very relative -Metrics/CyclomaticComplexity: - Enabled: False - -Style/ConstantName: - Enabled: True - -Style/Documentation: - Enabled: False - -Style/DefWithParentheses: - Enabled: True - -Style/PreferredHashMethods: - Enabled: True - -Style/DotPosition: - EnforcedStyle: trailing - -Style/DoubleNegation: - Enabled: True - -Style/EachWithObject: - Enabled: True - -Style/EmptyLineBetweenDefs: - Enabled: True - -Style/IndentArray: - Enabled: True - -Style/IndentHash: - Enabled: True - -Style/IndentationConsistency: - Enabled: True - -Style/IndentationWidth: - Enabled: True - -Style/EmptyLines: - Enabled: True - -Style/EmptyLinesAroundAccessModifier: - Enabled: True - -Style/EmptyLiteral: - Enabled: True - -# Configuration parameters: AllowURI, URISchemes. + - bin/* + - ".vendor/**/*" + - Gemfile + - Rakefile + - pkg/**/* + - spec/fixtures/**/* + - vendor/**/* +inherit_from: .rubocop_todo.yml Metrics/LineLength: - Enabled: False - -Style/MethodCallParentheses: - Enabled: True - -Style/MethodDefParentheses: - Enabled: True - -Style/LineEndConcatenation: - Enabled: True - -Style/TrailingWhitespace: - Enabled: True - -Style/StringLiterals: - Enabled: True - -Style/TrailingCommaInArguments: - Enabled: True - -Style/TrailingCommaInLiteral: - Enabled: True - -Style/GlobalVars: - Enabled: True - -Style/GuardClause: - Enabled: True - -Style/IfUnlessModifier: - Enabled: True - -Style/MultilineIfThen: - Enabled: True - -Style/NegatedIf: - Enabled: True - -Style/NegatedWhile: - Enabled: True - -Style/Next: - Enabled: True - -Style/SingleLineBlockParams: - Enabled: True - -Style/SingleLineMethods: - Enabled: True - -Style/SpecialGlobalVars: - Enabled: True - -Style/TrivialAccessors: - Enabled: True - -Style/UnlessElse: - Enabled: True - -Style/VariableInterpolation: - Enabled: True - -Style/VariableName: - Enabled: True - -Style/WhileUntilDo: - Enabled: True - -Style/EvenOdd: - Enabled: True - -Style/FileName: - Enabled: True - -Style/For: - Enabled: True - -Style/Lambda: - Enabled: True - -Style/MethodName: - Enabled: True - -Style/MultilineTernaryOperator: - Enabled: True - -Style/NestedTernaryOperator: - Enabled: True - -Style/NilComparison: - Enabled: True - + Description: People have wide screens, use them. + Max: 200 +RSpec/BeforeAfterAll: + Description: Beware of using after(:all) as it may cause state to leak between tests. + A necessary evil in acceptance testing. + Exclude: + - spec/acceptance/**/*.rb +RSpec/HookArgument: + Description: Prefer explicit :each argument, matching existing module's style + EnforcedStyle: each +Style/BlockDelimiters: + Description: Prefer braces for chaining. Mostly an aesthetical choice. Better to + be consistent then. + EnforcedStyle: braces_for_chaining +Style/ClassAndModuleChildren: + Description: Compact style reduces the required amount of indentation. + EnforcedStyle: compact +Style/EmptyElse: + Description: Enforce against empty else clauses, but allow `nil` for clarity. + EnforcedStyle: empty Style/FormatString: - Enabled: True - -Style/MultilineBlockChain: - Enabled: True - -Style/Semicolon: - Enabled: True - -Style/SignalException: - Enabled: True - -Style/NonNilCheck: - Enabled: True - -Style/Not: - Enabled: True - -Style/NumericLiterals: - Enabled: True - -Style/OneLineConditional: - Enabled: True - -Style/OpMethod: - Enabled: True - -Style/ParenthesesAroundCondition: - Enabled: True - -Style/PercentLiteralDelimiters: - Enabled: True - -Style/PerlBackrefs: - Enabled: True - -Style/PredicateName: - Enabled: True - -Style/RedundantException: - Enabled: True - -Style/SelfAssignment: - Enabled: True - -Style/Proc: - Enabled: True - -Style/RaiseArgs: - Enabled: True - -Style/RedundantBegin: - Enabled: True - -Style/RescueModifier: - Enabled: True - -# based on https://github.com/voxpupuli/modulesync_config/issues/168 + Description: Following the main puppet project's style, prefer the % format format. + EnforcedStyle: percent +Style/FormatStringToken: + Description: Following the main puppet project's style, prefer the simpler template + tokens over annotated ones. + EnforcedStyle: template +Style/Lambda: + Description: Prefer the keyword for easier discoverability. + EnforcedStyle: literal Style/RegexpLiteral: + Description: Community preference. See https://github.com/voxpupuli/modulesync_config/issues/168 EnforcedStyle: percent_r - Enabled: True - -Lint/UnderscorePrefixedVariableName: - Enabled: True - -Metrics/ParameterLists: - Enabled: False - -Lint/RequireParentheses: - Enabled: True - -Style/SpaceBeforeFirstArg: - Enabled: True - -Style/ModuleFunction: - Enabled: True - -Lint/Debugger: - Enabled: True - -Style/IfWithSemicolon: - Enabled: True - -Style/Encoding: - Enabled: True - -Style/BlockDelimiters: - Enabled: True - -Style/MultilineBlockLayout: - Enabled: True - -# 'Complexity' is very relative +Style/TernaryParentheses: + Description: Checks for use of parentheses around ternary conditions. Enforce parentheses + on complex expressions for better readability, but seriously consider breaking + it up. + EnforcedStyle: require_parentheses_when_complex +Style/TrailingCommaInArguments: + Description: Prefer always trailing comma on multiline argument lists. This makes + diffs, and re-ordering nicer. + EnforcedStyleForMultiline: comma +Style/TrailingCommaInLiteral: + Description: Prefer always trailing comma on multiline literals. This makes diffs, + and re-ordering nicer. + EnforcedStyleForMultiline: comma +Style/SymbolArray: + Description: Using percent style obscures symbolic intent of array's contents. + EnforcedStyle: brackets +Style/CollectionMethods: + Enabled: true +Style/MethodCalledOnDoEndBlock: + Enabled: true +Style/StringMethods: + Enabled: true Metrics/AbcSize: - Enabled: False - -# 'Complexity' is very relative + Enabled: false +Metrics/BlockLength: + Enabled: false +Metrics/ClassLength: + Enabled: false +Metrics/CyclomaticComplexity: + Enabled: false +Metrics/MethodLength: + Enabled: false +Metrics/ModuleLength: + Enabled: false +Metrics/ParameterLists: + Enabled: false Metrics/PerceivedComplexity: - Enabled: False - -Lint/UselessAssignment: - Enabled: True - -Style/ClosingParenthesisIndentation: - Enabled: False - -# RSpec - -# We don't use rspec in this way + Enabled: false RSpec/DescribeClass: - Enabled: False - -# Example length is not necessarily an indicator of code quality -RSpec/ExampleLength: - Enabled: False - + Enabled: false +RSpec/MessageExpectation: + Enabled: false +Style/AsciiComments: + Enabled: false +Style/IfUnlessModifier: + Enabled: false +Style/SymbolProc: + Enabled: false RSpec/NamedSubject: - Enabled: False + Enabled: false \ No newline at end of file diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml new file mode 100644 index 0000000..e69de29 diff --git a/.sync.yml b/.sync.yml index 728465c..89d925b 100644 --- a/.sync.yml +++ b/.sync.yml @@ -10,3 +10,6 @@ appveyor.yml: - set: docker/centos-7 options: env: PUPPET_INSTALL_TYPE=agent BEAKER_debug=true BEAKER_set=@@SET@@ SPEC_OPTS=""--tag docker" + extras: + - rvm: 2.1.9 + script: bundle exec rake rubocop \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index adc67f3..f63b4a6 100644 --- a/.travis.yml +++ b/.travis.yml @@ -28,5 +28,7 @@ matrix: - rvm: 2.1.9 bundler_args: --without system_tests env: PUPPET_GEM_VERSION="~> 4.0" + - rvm: 2.1.9 + script: bundle exec rake rubocop notifications: email: false diff --git a/lib/facter/ip6tables_version.rb b/lib/facter/ip6tables_version.rb index f2540c6..fded4bc 100644 --- a/lib/facter/ip6tables_version.rb +++ b/lib/facter/ip6tables_version.rb @@ -1,9 +1,9 @@ Facter.add(:ip6tables_version) do - confine :kernel => :Linux + confine kernel: :Linux setcode do version = Facter::Util::Resolution.exec('ip6tables --version') if version - version.match(/\d+\.\d+\.\d+/).to_s + version.match(%r{\d+\.\d+\.\d+}).to_s else nil end diff --git a/lib/facter/iptables_persistent_version.rb b/lib/facter/iptables_persistent_version.rb index 4dbf6bc..ac225f5 100644 --- a/lib/facter/iptables_persistent_version.rb +++ b/lib/facter/iptables_persistent_version.rb @@ -1,19 +1,19 @@ Facter.add(:iptables_persistent_version) do - confine :operatingsystem => %w{Debian Ubuntu} + confine operatingsystem: %w[Debian Ubuntu] setcode do # Throw away STDERR because dpkg >= 1.16.7 will make some noise if the # package isn't currently installed. os = Facter.value(:operatingsystem) os_release = Facter.value(:operatingsystemrelease) - if (os == 'Debian' and (Puppet::Util::Package.versioncmp(os_release, '8.0') >= 0)) or - (os == 'Ubuntu' and (Puppet::Util::Package.versioncmp(os_release, '14.10') >= 0)) - cmd = "dpkg-query -Wf '${Version}' netfilter-persistent 2>/dev/null" - else - cmd = "dpkg-query -Wf '${Version}' iptables-persistent 2>/dev/null" - end + cmd = if (os == 'Debian' && (Puppet::Util::Package.versioncmp(os_release, '8.0') >= 0)) || + (os == 'Ubuntu' && (Puppet::Util::Package.versioncmp(os_release, '14.10') >= 0)) + "dpkg-query -Wf '${Version}' netfilter-persistent 2>/dev/null" + else + "dpkg-query -Wf '${Version}' iptables-persistent 2>/dev/null" + end version = Facter::Util::Resolution.exec(cmd) - if version.nil? or !version.match(/\d+\.\d+/) + if version.nil? || !version.match(%r{\d+\.\d+}) nil else version diff --git a/lib/facter/iptables_version.rb b/lib/facter/iptables_version.rb index 7da5937..3253b97 100644 --- a/lib/facter/iptables_version.rb +++ b/lib/facter/iptables_version.rb @@ -1,9 +1,9 @@ Facter.add(:iptables_version) do - confine :kernel => :Linux + confine kernel: :Linux setcode do version = Facter::Util::Resolution.exec('iptables --version') if version - version.match(/\d+\.\d+\.\d+/).to_s + version.match(%r{\d+\.\d+\.\d+}).to_s else nil end diff --git a/lib/puppet/provider/firewall.rb b/lib/puppet/provider/firewall.rb index c6b0b10..851b4b3 100644 --- a/lib/puppet/provider/firewall.rb +++ b/lib/puppet/provider/firewall.rb @@ -1,11 +1,14 @@ +# +# firewall.rb +# class Puppet::Provider::Firewall < Puppet::Provider - # Prefetch our rule list. This is ran once every time before any other # action (besides initialization of each object). def self.prefetch(resources) - debug("[prefetch(resources)]") + debug('[prefetch(resources)]') instances.each do |prov| - if resource = resources[prov.name] || resources[prov.name.downcase] + resource = resources[prov.name] || resources[prov.name.downcase] + if resource resource.provider = prov end end @@ -15,7 +18,7 @@ class Puppet::Provider::Firewall < Puppet::Provider # existing status with properties[:foo]. def properties if @property_hash.empty? - @property_hash = query || {:ensure => :absent} + @property_hash = query || { ensure: :absent } @property_hash[:ensure] = :absent if @property_hash.empty? end @property_hash.dup @@ -25,7 +28,7 @@ class Puppet::Provider::Firewall < Puppet::Provider # getting some double entendre here.... def query self.class.instances.each do |instance| - if instance.name == self.name or instance.name.downcase == self.name + if instance.name == name || instance.name.downcase == name return instance.properties end end diff --git a/lib/puppet/provider/firewall/ip6tables.rb b/lib/puppet/provider/firewall/ip6tables.rb index c4b421c..d3c1b3c 100644 --- a/lib/puppet/provider/firewall/ip6tables.rb +++ b/lib/puppet/provider/firewall/ip6tables.rb @@ -1,5 +1,5 @@ -Puppet::Type.type(:firewall).provide :ip6tables, :parent => :iptables, :source => :ip6tables do - @doc = "Ip6tables type provider" +Puppet::Type.type(:firewall).provide :ip6tables, parent: :iptables, source: :ip6tables do + @doc = 'Ip6tables type provider' has_feature :iptables has_feature :connection_limiting @@ -35,28 +35,22 @@ Puppet::Type.type(:firewall).provide :ip6tables, :parent => :iptables, :source = has_feature :queue_num has_feature :queue_bypass - optional_commands({ - :ip6tables => 'ip6tables', - :ip6tables_save => 'ip6tables-save', - }) + optional_commands(ip6tables: 'ip6tables', + ip6tables_save: 'ip6tables-save') - confine :kernel => :linux + confine kernel: :linux ip6tables_version = Facter.value('ip6tables_version') - if (ip6tables_version and Puppet::Util::Package.versioncmp(ip6tables_version, '1.4.1') < 0) - mark_flag = '--set-mark' - else - mark_flag = '--set-xmark' - end - + mark_flag = if ip6tables_version && Puppet::Util::Package.versioncmp(ip6tables_version, '1.4.1') < 0 + '--set-mark' + else + '--set-xmark' + end def initialize(*args) ip6tables_version = Facter.value('ip6tables_version') - if ip6tables_version and ip6tables_version.match /1\.3\.\d/ - raise ArgumentError, 'The ip6tables provider is not supported on version 1.3 of iptables' - else - super - end + raise ArgumentError, 'The ip6tables provider is not supported on version 1.3 of iptables' if ip6tables_version && ip6tables_version.match(%r{1\.3\.\d}) + super end def self.iptables(*args) @@ -67,107 +61,107 @@ Puppet::Type.type(:firewall).provide :ip6tables, :parent => :iptables, :source = ip6tables_save(*args) end - @protocol = "IPv6" + @protocol = 'IPv6' @resource_map = { - :burst => "--limit-burst", - :checksum_fill => "--checksum-fill", - :clamp_mss_to_pmtu => "--clamp-mss-to-pmtu", - :connlimit_above => "-m connlimit --connlimit-above", - :connlimit_mask => "--connlimit-mask", - :connmark => "-m connmark --mark", - :ctstate => "-m conntrack --ctstate", - :destination => "-d", - :dport => ["-m multiport --dports", "--dport"], - :dst_range => '--dst-range', - :dst_type => "--dst-type", - :gateway => "--gateway", - :gid => "--gid-owner", - :hop_limit => "-m hl --hl-eq", - :icmp => "-m icmp6 --icmpv6-type", - :iniface => "-i", - :ipsec_dir => "-m policy --dir", - :ipsec_policy => "--pol", - :ipset => "-m set --match-set", - :isfirstfrag => "-m frag --fragid 0 --fragfirst", - :ishasmorefrags => "-m frag --fragid 0 --fragmore", - :islastfrag => "-m frag --fragid 0 --fraglast", - :jump => "-j", - :length => "-m length --length", - :limit => "-m limit --limit", - :log_level => "--log-level", - :log_prefix => "--log-prefix", - :log_uid => "--log-uid", - :mask => "--mask", - :match_mark => "-m mark --mark", - :name => "-m comment --comment", - :mac_source => ["-m mac --mac-source", "--mac-source"], - :mss => "-m tcpmss --mss", - :outiface => "-o", - :pkttype => "-m pkttype --pkt-type", - :port => '-m multiport --ports', - :proto => "-p", - :queue_num => "--queue-num", - :queue_bypass => "--queue-bypass", - :rdest => "--rdest", - :reap => "--reap", - :recent => "-m recent", - :reject => "--reject-with", - :rhitcount => "--hitcount", - :rname => "--name", - :rseconds => "--seconds", - :rsource => "--rsource", - :rttl => "--rttl", - :set_dscp => '--set-dscp', - :set_dscp_class => '--set-dscp-class', - :set_mark => mark_flag, - :set_mss => '--set-mss', - :socket => "-m socket", - :source => "-s", - :sport => ["-m multiport --sports", "--sport"], - :src_range => '--src-range', - :src_type => "--src-type", - :stat_every => '--every', - :stat_mode => "-m statistic --mode", - :stat_packet => '--packet', - :stat_probability => '--probability', - :state => "-m state --state", - :string => "-m string --string", - :string_algo => "--algo", - :string_from => "--from", - :string_to => "--to", - :table => "-t", - :tcp_flags => "-m tcp --tcp-flags", - :todest => "--to-destination", - :toports => "--to-ports", - :tosource => "--to-source", - :uid => "--uid-owner", - :physdev_in => "--physdev-in", - :physdev_out => "--physdev-out", - :physdev_is_bridged => "--physdev-is-bridged", - :physdev_is_in => "--physdev-is-in", - :physdev_is_out => "--physdev-is-out", - :date_start => "--datestart", - :date_stop => "--datestop", - :time_start => "--timestart", - :time_stop => "--timestop", - :month_days => "--monthdays", - :week_days => "--weekdays", - :time_contiguous => "--contiguous", - :kernel_timezone => "--kerneltz", - :src_cc => "--source-country", - :dst_cc => "--destination-country", - :hashlimit_name => "--hashlimit-name", - :hashlimit_upto => "--hashlimit-upto", - :hashlimit_above => "--hashlimit-above", - :hashlimit_burst => "--hashlimit-burst", - :hashlimit_mode => "--hashlimit-mode", - :hashlimit_srcmask => "--hashlimit-srcmask", - :hashlimit_dstmask => "--hashlimit-dstmask", - :hashlimit_htable_size => "--hashlimit-htable-size", - :hashlimit_htable_max => "--hashlimit-htable-max", - :hashlimit_htable_expire => "--hashlimit-htable-expire", - :hashlimit_htable_gcinterval => "--hashlimit-htable-gcinterval", + burst: '--limit-burst', + checksum_fill: '--checksum-fill', + clamp_mss_to_pmtu: '--clamp-mss-to-pmtu', + connlimit_above: '-m connlimit --connlimit-above', + connlimit_mask: '--connlimit-mask', + connmark: '-m connmark --mark', + ctstate: '-m conntrack --ctstate', + destination: '-d', + dport: ['-m multiport --dports', '--dport'], + dst_range: '--dst-range', + dst_type: '--dst-type', + gateway: '--gateway', + gid: '--gid-owner', + hop_limit: '-m hl --hl-eq', + icmp: '-m icmp6 --icmpv6-type', + iniface: '-i', + ipsec_dir: '-m policy --dir', + ipsec_policy: '--pol', + ipset: '-m set --match-set', + isfirstfrag: '-m frag --fragid 0 --fragfirst', + ishasmorefrags: '-m frag --fragid 0 --fragmore', + islastfrag: '-m frag --fragid 0 --fraglast', + jump: '-j', + length: '-m length --length', + limit: '-m limit --limit', + log_level: '--log-level', + log_prefix: '--log-prefix', + log_uid: '--log-uid', + mask: '--mask', + match_mark: '-m mark --mark', + name: '-m comment --comment', + mac_source: ['-m mac --mac-source', '--mac-source'], + mss: '-m tcpmss --mss', + outiface: '-o', + pkttype: '-m pkttype --pkt-type', + port: '-m multiport --ports', + proto: '-p', + queue_num: '--queue-num', + queue_bypass: '--queue-bypass', + rdest: '--rdest', + reap: '--reap', + recent: '-m recent', + reject: '--reject-with', + rhitcount: '--hitcount', + rname: '--name', + rseconds: '--seconds', + rsource: '--rsource', + rttl: '--rttl', + set_dscp: '--set-dscp', + set_dscp_class: '--set-dscp-class', + set_mark: mark_flag, + set_mss: '--set-mss', + socket: '-m socket', + source: '-s', + sport: ['-m multiport --sports', '--sport'], + src_range: '--src-range', + src_type: '--src-type', + stat_every: '--every', + stat_mode: '-m statistic --mode', + stat_packet: '--packet', + stat_probability: '--probability', + state: '-m state --state', + string: '-m string --string', + string_algo: '--algo', + string_from: '--from', + string_to: '--to', + table: '-t', + tcp_flags: '-m tcp --tcp-flags', + todest: '--to-destination', + toports: '--to-ports', + tosource: '--to-source', + uid: '--uid-owner', + physdev_in: '--physdev-in', + physdev_out: '--physdev-out', + physdev_is_bridged: '--physdev-is-bridged', + physdev_is_in: '--physdev-is-in', + physdev_is_out: '--physdev-is-out', + date_start: '--datestart', + date_stop: '--datestop', + time_start: '--timestart', + time_stop: '--timestop', + month_days: '--monthdays', + week_days: '--weekdays', + time_contiguous: '--contiguous', + kernel_timezone: '--kerneltz', + src_cc: '--source-country', + dst_cc: '--destination-country', + hashlimit_name: '--hashlimit-name', + hashlimit_upto: '--hashlimit-upto', + hashlimit_above: '--hashlimit-above', + hashlimit_burst: '--hashlimit-burst', + hashlimit_mode: '--hashlimit-mode', + hashlimit_srcmask: '--hashlimit-srcmask', + hashlimit_dstmask: '--hashlimit-dstmask', + hashlimit_htable_size: '--hashlimit-htable-size', + hashlimit_htable_max: '--hashlimit-htable-max', + hashlimit_htable_expire: '--hashlimit-htable-expire', + hashlimit_htable_gcinterval: '--hashlimit-htable-gcinterval', } @@ -206,27 +200,27 @@ Puppet::Type.type(:firewall).provide :ip6tables, :parent => :iptables, :source = # ones. # @module_to_argument_mapping = { - :physdev => [:physdev_in, :physdev_out, :physdev_is_bridged, :physdev_is_in, :physdev_is_out], - :addrtype => [:src_type, :dst_type], - :iprange => [:src_range, :dst_range], - :owner => [:uid, :gid], - :time => [:time_start, :time_stop, :month_days, :week_days, :date_start, :date_stop, :time_contiguous, :kernel_timezone], - :geoip => [:src_cc, :dst_cc], - :hashlimit => [:hashlimit_upto, :hashlimit_above, :hashlimit_name, :hashlimit_burst, :hashlimit_mode, :hashlimit_srcmask, :hashlimit_dstmask, - :hashlimit_htable_size, :hashlimit_htable_max, :hashlimit_htable_expire, :hashlimit_htable_gcinterval], + physdev: [:physdev_in, :physdev_out, :physdev_is_bridged, :physdev_is_in, :physdev_is_out], + addrtype: [:src_type, :dst_type], + iprange: [:src_range, :dst_range], + owner: [:uid, :gid], + time: [:time_start, :time_stop, :month_days, :week_days, :date_start, :date_stop, :time_contiguous, :kernel_timezone], + geoip: [:src_cc, :dst_cc], + hashlimit: [:hashlimit_upto, :hashlimit_above, :hashlimit_name, :hashlimit_burst, :hashlimit_mode, :hashlimit_srcmask, :hashlimit_dstmask, + :hashlimit_htable_size, :hashlimit_htable_max, :hashlimit_htable_expire, :hashlimit_htable_gcinterval], } # Create property methods dynamically (@resource_map.keys << :chain << :table << :action).each do |property| - if @known_booleans.include?(property) then + if @known_booleans.include?(property) # The boolean properties default to '' which should be read as false - define_method "#{property}" do - @property_hash[property] = :false if @property_hash[property] == nil + define_method property.to_s do + @property_hash[property] = :false if @property_hash[property].nil? @property_hash[property.to_sym] end else - define_method "#{property}" do + define_method property.to_s do @property_hash[property.to_sym] end end @@ -234,11 +228,11 @@ Puppet::Type.type(:firewall).provide :ip6tables, :parent => :iptables, :source = if property == :chain define_method "#{property}=" do |value| if @property_hash[:chain] != value - raise ArgumentError, "Modifying the chain for existing rules is not supported." + raise ArgumentError, 'Modifying the chain for existing rules is not supported.' end end else - define_method "#{property}=" do |value| + define_method "#{property}=" do |_value| @property_hash[:needs_change] = true end end @@ -252,17 +246,16 @@ Puppet::Type.type(:firewall).provide :ip6tables, :parent => :iptables, :source = # I put it when calling the command. So compability with manual changes # not provided with current parser [georg.koester]) @resource_list = [:table, :source, :destination, :iniface, :outiface, :physdev_in, - :physdev_out, :physdev_is_bridged, :physdev_is_in, :physdev_is_out, - :proto, :ishasmorefrags, :islastfrag, :isfirstfrag, :src_range, :dst_range, - :tcp_flags, :uid, :gid, :mac_source, :sport, :dport, :port, :src_type, - :dst_type, :socket, :pkttype, :ipsec_dir, :ipsec_policy, :state, - :ctstate, :icmp, :hop_limit, :limit, :burst, :length, :recent, :rseconds, :reap, - :rhitcount, :rttl, :rname, :mask, :rsource, :rdest, :ipset, :string, :string_algo, - :string_from, :string_to, :jump, :clamp_mss_to_pmtu, :gateway, :todest, - :tosource, :toports, :checksum_fill, :log_level, :log_prefix, :log_uid, :reject, :set_mss, :set_dscp, :set_dscp_class, :mss, :queue_num, :queue_bypass, - :set_mark, :match_mark, :connlimit_above, :connlimit_mask, :connmark, :time_start, :time_stop, :month_days, :week_days, :date_start, :date_stop, :time_contiguous, :kernel_timezone, - :src_cc, :dst_cc, :hashlimit_upto, :hashlimit_above, :hashlimit_name, :hashlimit_burst, - :hashlimit_mode, :hashlimit_srcmask, :hashlimit_dstmask, :hashlimit_htable_size, - :hashlimit_htable_max, :hashlimit_htable_expire, :hashlimit_htable_gcinterval, :name] - + :physdev_out, :physdev_is_bridged, :physdev_is_in, :physdev_is_out, + :proto, :ishasmorefrags, :islastfrag, :isfirstfrag, :src_range, :dst_range, + :tcp_flags, :uid, :gid, :mac_source, :sport, :dport, :port, :src_type, + :dst_type, :socket, :pkttype, :ipsec_dir, :ipsec_policy, :state, + :ctstate, :icmp, :hop_limit, :limit, :burst, :length, :recent, :rseconds, :reap, + :rhitcount, :rttl, :rname, :mask, :rsource, :rdest, :ipset, :string, :string_algo, + :string_from, :string_to, :jump, :clamp_mss_to_pmtu, :gateway, :todest, + :tosource, :toports, :checksum_fill, :log_level, :log_prefix, :log_uid, :reject, :set_mss, :set_dscp, :set_dscp_class, :mss, :queue_num, :queue_bypass, + :set_mark, :match_mark, :connlimit_above, :connlimit_mask, :connmark, :time_start, :time_stop, :month_days, :week_days, :date_start, :date_stop, :time_contiguous, :kernel_timezone, + :src_cc, :dst_cc, :hashlimit_upto, :hashlimit_above, :hashlimit_name, :hashlimit_burst, + :hashlimit_mode, :hashlimit_srcmask, :hashlimit_dstmask, :hashlimit_htable_size, + :hashlimit_htable_max, :hashlimit_htable_expire, :hashlimit_htable_gcinterval, :name] end diff --git a/lib/puppet/provider/firewall/iptables.rb b/lib/puppet/provider/firewall/iptables.rb index 16eaa30..bc918b9 100644 --- a/lib/puppet/provider/firewall/iptables.rb +++ b/lib/puppet/provider/firewall/iptables.rb @@ -1,10 +1,10 @@ require 'puppet/provider/firewall' require 'digest/md5' -Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Firewall do +Puppet::Type.type(:firewall).provide :iptables, parent: Puppet::Provider::Firewall do include Puppet::Util::Firewall - @doc = "Iptables type provider" + @doc = 'Iptables type provider' has_feature :iptables has_feature :connection_limiting @@ -43,132 +43,130 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir has_feature :queue_num has_feature :queue_bypass - optional_commands({ - :iptables => 'iptables', - :iptables_save => 'iptables-save', - }) + optional_commands(iptables: 'iptables', + iptables_save: 'iptables-save') - defaultfor :kernel => :linux - confine :kernel => :linux + defaultfor kernel: :linux + confine kernel: :linux iptables_version = Facter.value('iptables_version') - if (iptables_version and Puppet::Util::Package.versioncmp(iptables_version, '1.4.1') < 0) - mark_flag = '--set-mark' - else - mark_flag = '--set-xmark' - end + mark_flag = if iptables_version && Puppet::Util::Package.versioncmp(iptables_version, '1.4.1') < 0 + '--set-mark' + else + '--set-xmark' + end - @protocol = "IPv4" + @protocol = 'IPv4' @resource_map = { - :burst => "--limit-burst", - :checksum_fill => "--checksum-fill", - :clamp_mss_to_pmtu => "--clamp-mss-to-pmtu", - :connlimit_above => "-m connlimit --connlimit-above", - :connlimit_mask => "--connlimit-mask", - :connmark => "-m connmark --mark", - :ctstate => "-m conntrack --ctstate", - :destination => "-d", - :dport => ["-m multiport --dports", "--dport"], - :dst_range => "--dst-range", - :dst_type => "--dst-type", - :gateway => "--gateway", - :gid => "--gid-owner", - :icmp => "-m icmp --icmp-type", - :iniface => "-i", - :ipsec_dir => "-m policy --dir", - :ipsec_policy => "--pol", - :ipset => "-m set --match-set", - :isfragment => "-f", - :jump => "-j", - :goto => "-g", - :length => "-m length --length", - :limit => "-m limit --limit", - :log_level => "--log-level", - :log_prefix => "--log-prefix", - :log_uid => "--log-uid", - :mac_source => ["-m mac --mac-source", "--mac-source"], - :mask => '--mask', - :match_mark => "-m mark --mark", - :mss => '-m tcpmss --mss', - :name => "-m comment --comment", - :nflog_group => "--nflog-group", - :nflog_prefix => "--nflog-prefix", - :nflog_range => "--nflog-range", - :nflog_threshold => "--nflog-threshold", - :outiface => "-o", - :pkttype => "-m pkttype --pkt-type", - :port => '-m multiport --ports', - :proto => "-p", - :queue_num => "--queue-num", - :queue_bypass => "--queue-bypass", - :random => "--random", - :rdest => "--rdest", - :reap => "--reap", - :recent => "-m recent", - :reject => "--reject-with", - :rhitcount => "--hitcount", - :rname => "--name", - :rseconds => "--seconds", - :rsource => "--rsource", - :rttl => "--rttl", - :set_dscp => '--set-dscp', - :set_dscp_class => '--set-dscp-class', - :set_mark => mark_flag, - :set_mss => '--set-mss', - :socket => "-m socket", - :source => "-s", - :sport => ["-m multiport --sports", "--sport"], - :src_range => "--src-range", - :src_type => "--src-type", - :stat_every => '--every', - :stat_mode => "-m statistic --mode", - :stat_packet => '--packet', - :stat_probability => '--probability', - :state => "-m state --state", - :string => "-m string --string", - :string_algo => "--algo", - :string_from => "--from", - :string_to => "--to", - :table => "-t", - :tcp_flags => "-m tcp --tcp-flags", - :todest => "--to-destination", - :toports => "--to-ports", - :tosource => "--to-source", - :to => "--to", - :uid => "--uid-owner", - :physdev_in => "--physdev-in", - :physdev_out => "--physdev-out", - :physdev_is_bridged => "--physdev-is-bridged", - :physdev_is_in => "--physdev-is-in", - :physdev_is_out => "--physdev-is-out", - :date_start => "--datestart", - :date_stop => "--datestop", - :time_start => "--timestart", - :time_stop => "--timestop", - :month_days => "--monthdays", - :week_days => "--weekdays", - :time_contiguous => "--contiguous", - :kernel_timezone => "--kerneltz", - :clusterip_new => "--new", - :clusterip_hashmode => "--hashmode", - :clusterip_clustermac => "--clustermac", - :clusterip_total_nodes => "--total-nodes", - :clusterip_local_node => "--local-node", - :clusterip_hash_init => "--hash-init", - :src_cc => "--source-country", - :dst_cc => "--destination-country", - :hashlimit_name => "--hashlimit-name", - :hashlimit_upto => "--hashlimit-upto", - :hashlimit_above => "--hashlimit-above", - :hashlimit_burst => "--hashlimit-burst", - :hashlimit_mode => "--hashlimit-mode", - :hashlimit_srcmask => "--hashlimit-srcmask", - :hashlimit_dstmask => "--hashlimit-dstmask", - :hashlimit_htable_size => "--hashlimit-htable-size", - :hashlimit_htable_max => "--hashlimit-htable-max", - :hashlimit_htable_expire => "--hashlimit-htable-expire", - :hashlimit_htable_gcinterval => "--hashlimit-htable-gcinterval", + burst: '--limit-burst', + checksum_fill: '--checksum-fill', + clamp_mss_to_pmtu: '--clamp-mss-to-pmtu', + connlimit_above: '-m connlimit --connlimit-above', + connlimit_mask: '--connlimit-mask', + connmark: '-m connmark --mark', + ctstate: '-m conntrack --ctstate', + destination: '-d', + dport: ['-m multiport --dports', '--dport'], + dst_range: '--dst-range', + dst_type: '--dst-type', + gateway: '--gateway', + gid: '--gid-owner', + icmp: '-m icmp --icmp-type', + iniface: '-i', + ipsec_dir: '-m policy --dir', + ipsec_policy: '--pol', + ipset: '-m set --match-set', + isfragment: '-f', + jump: '-j', + goto: '-g', + length: '-m length --length', + limit: '-m limit --limit', + log_level: '--log-level', + log_prefix: '--log-prefix', + log_uid: '--log-uid', + mac_source: ['-m mac --mac-source', '--mac-source'], + mask: '--mask', + match_mark: '-m mark --mark', + mss: '-m tcpmss --mss', + name: '-m comment --comment', + nflog_group: '--nflog-group', + nflog_prefix: '--nflog-prefix', + nflog_range: '--nflog-range', + nflog_threshold: '--nflog-threshold', + outiface: '-o', + pkttype: '-m pkttype --pkt-type', + port: '-m multiport --ports', + proto: '-p', + queue_num: '--queue-num', + queue_bypass: '--queue-bypass', + random: '--random', + rdest: '--rdest', + reap: '--reap', + recent: '-m recent', + reject: '--reject-with', + rhitcount: '--hitcount', + rname: '--name', + rseconds: '--seconds', + rsource: '--rsource', + rttl: '--rttl', + set_dscp: '--set-dscp', + set_dscp_class: '--set-dscp-class', + set_mark: mark_flag, + set_mss: '--set-mss', + socket: '-m socket', + source: '-s', + sport: ['-m multiport --sports', '--sport'], + src_range: '--src-range', + src_type: '--src-type', + stat_every: '--every', + stat_mode: '-m statistic --mode', + stat_packet: '--packet', + stat_probability: '--probability', + state: '-m state --state', + string: '-m string --string', + string_algo: '--algo', + string_from: '--from', + string_to: '--to', + table: '-t', + tcp_flags: '-m tcp --tcp-flags', + todest: '--to-destination', + toports: '--to-ports', + tosource: '--to-source', + to: '--to', + uid: '--uid-owner', + physdev_in: '--physdev-in', + physdev_out: '--physdev-out', + physdev_is_bridged: '--physdev-is-bridged', + physdev_is_in: '--physdev-is-in', + physdev_is_out: '--physdev-is-out', + date_start: '--datestart', + date_stop: '--datestop', + time_start: '--timestart', + time_stop: '--timestop', + month_days: '--monthdays', + week_days: '--weekdays', + time_contiguous: '--contiguous', + kernel_timezone: '--kerneltz', + clusterip_new: '--new', + clusterip_hashmode: '--hashmode', + clusterip_clustermac: '--clustermac', + clusterip_total_nodes: '--total-nodes', + clusterip_local_node: '--local-node', + clusterip_hash_init: '--hash-init', + src_cc: '--source-country', + dst_cc: '--destination-country', + hashlimit_name: '--hashlimit-name', + hashlimit_upto: '--hashlimit-upto', + hashlimit_above: '--hashlimit-above', + hashlimit_burst: '--hashlimit-burst', + hashlimit_mode: '--hashlimit-mode', + hashlimit_srcmask: '--hashlimit-srcmask', + hashlimit_dstmask: '--hashlimit-dstmask', + hashlimit_htable_size: '--hashlimit-htable-size', + hashlimit_htable_max: '--hashlimit-htable-max', + hashlimit_htable_expire: '--hashlimit-htable-expire', + hashlimit_htable_gcinterval: '--hashlimit-htable-gcinterval', } # These are known booleans that do not take a value, but we want to munge @@ -206,14 +204,14 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir # ones. # @module_to_argument_mapping = { - :physdev => [:physdev_in, :physdev_out, :physdev_is_bridged, :physdev_is_in, :physdev_is_out], - :addrtype => [:src_type, :dst_type], - :iprange => [:src_range, :dst_range], - :owner => [:uid, :gid], - :time => [:time_start, :time_stop, :month_days, :week_days, :date_start, :date_stop, :time_contiguous, :kernel_timezone], - :geoip => [:src_cc, :dst_cc], - :hashlimit => [:hashlimit_upto, :hashlimit_above, :hashlimit_name, :hashlimit_burst, :hashlimit_mode, :hashlimit_srcmask, :hashlimit_dstmask, - :hashlimit_htable_size, :hashlimit_htable_max, :hashlimit_htable_expire, :hashlimit_htable_gcinterval], + physdev: [:physdev_in, :physdev_out, :physdev_is_bridged, :physdev_is_in, :physdev_is_out], + addrtype: [:src_type, :dst_type], + iprange: [:src_range, :dst_range], + owner: [:uid, :gid], + time: [:time_start, :time_stop, :month_days, :week_days, :date_start, :date_stop, :time_contiguous, :kernel_timezone], + geoip: [:src_cc, :dst_cc], + hashlimit: [:hashlimit_upto, :hashlimit_above, :hashlimit_name, :hashlimit_burst, :hashlimit_mode, :hashlimit_srcmask, :hashlimit_dstmask, + :hashlimit_htable_size, :hashlimit_htable_max, :hashlimit_htable_expire, :hashlimit_htable_gcinterval], } def self.munge_resource_map_from_existing_values(resource_map_original, compare) @@ -224,14 +222,12 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir if resource_map_original[argument].is_a?(Array) if compare.include?(resource_map_original[argument].first) resource_map_new[argument] = resource_map_original[argument].clone - resource_map_new[argument][0] = "-m #{ipt_module.to_s} #{resource_map_original[argument].first}" - break - end - else - if compare.include?(resource_map_original[argument]) - resource_map_new[argument] = "-m #{ipt_module.to_s} #{resource_map_original[argument]}" + resource_map_new[argument][0] = "-m #{ipt_module} #{resource_map_original[argument].first}" break end + elsif compare.include?(resource_map_original[argument]) + resource_map_new[argument] = "-m #{ipt_module} #{resource_map_original[argument]}" + break end end end @@ -244,31 +240,29 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir module_to_argument_mapping.each do |ipt_module, arg_array| arg_array.each do |argument| - if compare[argument] - if resource_map_original[argument].is_a?(Array) - resource_map_new[argument] = resource_map_original[argument].clone - resource_map_new[argument][0] = "-m #{ipt_module.to_s} #{resource_map_original[argument].first}" - else - resource_map_new[argument] = "-m #{ipt_module.to_s} #{resource_map_original[argument]}" - end - break + next unless compare[argument] + if resource_map_original[argument].is_a?(Array) + resource_map_new[argument] = resource_map_original[argument].clone + resource_map_new[argument][0] = "-m #{ipt_module} #{resource_map_original[argument].first}" + else + resource_map_new[argument] = "-m #{ipt_module} #{resource_map_original[argument]}" end + break end end resource_map_new end - # Create property methods dynamically (@resource_map.keys << :chain << :table << :action).each do |property| - if @known_booleans.include?(property) then + if @known_booleans.include?(property) # The boolean properties default to '' which should be read as false - define_method "#{property}" do - @property_hash[property] = :false if @property_hash[property] == nil + define_method property.to_s do + @property_hash[property] = :false if @property_hash[property].nil? @property_hash[property.to_sym] end else - define_method "#{property}" do + define_method property.to_s do @property_hash[property.to_sym] end end @@ -276,11 +270,11 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir if property == :chain define_method "#{property}=" do |value| if @property_hash[:chain] != value - raise ArgumentError, "Modifying the chain for existing rules is not supported." + raise ArgumentError, 'Modifying the chain for existing rules is not supported.' end end else - define_method "#{property}=" do |value| + define_method "#{property}=" do |_value| @property_hash[:needs_change] = true end end @@ -306,7 +300,8 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir :month_days, :week_days, :date_start, :date_stop, :time_contiguous, :kernel_timezone, :src_cc, :dst_cc, :hashlimit_upto, :hashlimit_above, :hashlimit_name, :hashlimit_burst, :hashlimit_mode, :hashlimit_srcmask, :hashlimit_dstmask, :hashlimit_htable_size, - :hashlimit_htable_max, :hashlimit_htable_expire, :hashlimit_htable_gcinterval, :name] + :hashlimit_htable_max, :hashlimit_htable_expire, :hashlimit_htable_gcinterval, :name + ] def insert debug 'Inserting rule %s' % resource[:name] @@ -326,14 +321,14 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir # Check to see if the iptables rule is already gone. This can sometimes # happen as a side effect of other resource changes. If it's not gone, # raise the error as per usual. - raise e unless self.resource.property(:ensure).insync?(:absent) + raise e unless resource.property(:ensure).insync?(:absent) # If it's already gone, there is no error. Still record a change, but # adjust the change message to indicate ambiguity over what work Puppet # actually did to remove the resource, vs. what could have been a side # effect of something else puppet did. - resource.property(:ensure).singleton_class.send(:define_method, :change_to_s) do |a,b| - "ensured absent" + resource.property(:ensure).singleton_class.send(:define_method, :change_to_s) do |_a, _b| + 'ensured absent' end end end @@ -344,9 +339,9 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir # Flush the property hash once done. def flush - debug("[flush]") + debug('[flush]') if @property_hash.delete(:needs_change) - notice("Properties changed - updating rule") + notice('Properties changed - updating rule') update end persist_iptables(self.class.instance_variable_get(:@protocol)) @@ -354,18 +349,19 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir end def self.instances - debug "[instances]" + debug '[instances]' table = nil rules = [] counter = 1 # String#lines would be nice, but we need to support Ruby 1.8.5 iptables_save.split("\n").each do |line| - unless line =~ /^\#\s+|^\:\S+|^COMMIT|^FATAL/ - if line =~ /^\*/ - table = line.sub(/\*/, "") + unless line =~ %r{^\#\s+|^\:\S+|^COMMIT|^FATAL} + if line =~ %r{^\*} + table = line.sub(%r{\*}, '') else - if hash = rule_to_hash(line, table, counter) + hash = rule_to_hash(line, table, counter) + if hash rules << new(hash) counter += 1 end @@ -385,30 +381,30 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir #################### # The match for ttl - values = values.gsub(/(!\s+)?-m ttl (!\s+)?--ttl-(eq|lt|gt) [0-9]+/, '') + values = values.gsub(%r{(!\s+)?-m ttl (!\s+)?--ttl-(eq|lt|gt) [0-9]+}, '') # --tcp-flags takes two values; we cheat by adding " around it # so it behaves like --comment - values = values.gsub(/(!\s+)?--tcp-flags (\S*) (\S*)/, '--tcp-flags "\1\2 \3"') + values = values.gsub(%r{(!\s+)?--tcp-flags (\S*) (\S*)}, '--tcp-flags "\1\2 \3"') # --match-set can have multiple values with weird iptables format - if values =~ /-m set (!\s+)?--match-set/ - values = values.gsub(/(!\s+)?--match-set (\S*) (\S*)/, '--match-set \1\2 \3') + if values =~ %r{-m set (!\s+)?--match-set} + values = values.gsub(%r{(!\s+)?--match-set (\S*) (\S*)}, '--match-set \1\2 \3') ind = values.index('-m set --match-set') - sets = values.scan(/-m set --match-set ((?:!\s+)?\S* \S*)/) - values = values.gsub(/-m set --match-set (!\s+)?\S* \S* /, '') + sets = values.scan(%r{-m set --match-set ((?:!\s+)?\S* \S*)}) + values = values.gsub(%r{-m set --match-set (!\s+)?\S* \S* }, '') values.insert(ind, "-m set --match-set \"#{sets.join(';')}\" ") end # we do a similar thing for negated address masks (source and destination). - values = values.gsub(/(-\S+) (!)\s?(\S*)/,'\1 "\2 \3"') + values = values.gsub(%r{(-\S+) (!)\s?(\S*)}, '\1 "\2 \3"') # fix negated physdev rules - values = values.gsub(/-m physdev ! (--physdev-is-\S+)/, '-m physdev \1 "!"') + values = values.gsub(%r{-m physdev ! (--physdev-is-\S+)}, '-m physdev \1 "!"') # the actual rule will have the ! mark before the option. - values = values.gsub(/(!)\s*(-\S+)\s*(\S*)/, '\2 "\1 \3"') + values = values.gsub(%r{(!)\s*(-\S+)\s*(\S*)}, '\2 "\1 \3"') # The match extension for tcp & udp are optional and throws off the @resource_map. - values = values.gsub(/(?!-m tcp --tcp-flags)-m (tcp|udp) /, '') + values = values.gsub(%r{(?!-m tcp --tcp-flags)-m (tcp|udp) }, '') # There is a bug in EL5 which puts 2 spaces before physdev, so we fix it - values = values.gsub(/\s{2}--physdev/, ' --physdev') + values = values.gsub(%r{\s{2}--physdev}, ' --physdev') # '--pol ipsec' takes many optional arguments; we cheat again by adding " around them - values = values.sub(/ + values = values.sub(%r{ --pol\sipsec (\s--strict)? (\s--reqid\s\S+)? @@ -417,42 +413,41 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir (\s--mode\s\S+)? (\s--tunnel-dst\s\S+)? (\s--tunnel-src\s\S+)? - (\s--next)?/x, - '--pol "ipsec\1\2\3\4\5\6\7\8" ' - ) + (\s--next)?}x, + '--pol "ipsec\1\2\3\4\5\6\7\8" ') # on some iptables versions, --connlimit-saddr switch is added after the rule is applied - values = values.gsub(/--connlimit-saddr/, '') + values = values.gsub(%r{--connlimit-saddr}, '') resource_map = munge_resource_map_from_existing_values(@resource_map, values) # Trick the system for booleans @known_booleans.each do |bool| # append "true" because all params are expected to have values - if bool == :isfragment then - # -f requires special matching: - # only replace those -f that are not followed by an l to - # distinguish between -f and the '-f' inside of --tcp-flags. - values = values.sub(/\s-f(?!l)(?=.*--comment)/, ' -f true') - else - # append `true` to booleans that are not already negated (followed by "!") - values = values.sub(/#{resource_map[bool]}(?! "!")/, "#{resource_map[bool]} true") - end + values = if bool == :isfragment + # -f requires special matching: + # only replace those -f that are not followed by an l to + # distinguish between -f and the '-f' inside of --tcp-flags. + values.sub(%r{\s-f(?!l)(?=.*--comment)}, ' -f true') + else + # append `true` to booleans that are not already negated (followed by "!") + values.sub(%r{#{resource_map[bool]}(?! "!")}, "#{resource_map[bool]} true") + end end ############ # Populate parser_list with used value, in the correct order ############ - map_index={} - resource_map.each_pair do |map_k,map_v| + map_index = {} + resource_map.each_pair do |map_k, map_v| [map_v].flatten.each do |v| - ind=values.index(/\s#{v}\s/) + ind = values.index(%r{\s#{v}\s}) next unless ind - map_index[map_k]=ind - end + map_index[map_k] = ind + end end # Generate parser_list based on the index of the found option - parser_list=[] - map_index.sort_by{|k,v| v}.each{|mapi| parser_list << mapi.first } + parser_list = [] + map_index.sort_by { |_k, v| v }.each { |mapi| parser_list << mapi.first } ############ # MAIN PARSE @@ -462,7 +457,7 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir parser_list.reverse.each do |k| resource_map_key = resource_map[k] [resource_map_key].flatten.each do |opt| - if values.slice!(/\s#{opt}/) + if values.slice!(%r{\s#{opt}}) keys << k break end @@ -470,20 +465,20 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir end # Manually remove chain - if values =~ /(\s|^)-A\s/ - values = values.sub(/(\s|^)-A\s/, '\1') + if values =~ %r{(\s|^)-A\s} + values = values.sub(%r{(\s|^)-A\s}, '\1') keys << :chain end # Manually remove table (used in some tests) - if values =~ /^-t\s/ - values = values.sub(/^-t\s/, '') + if values =~ %r{^-t\s} + values = values.sub(%r{^-t\s}, '') keys << :table end - valrev = values.scan(/("([^"\\]|\\.)*"|\S+)/).transpose[0].reverse + valrev = values.scan(%r{("([^"\\]|\\.)*"|\S+)}).transpose[0].reverse - if keys.length != valrev.length then + if keys.length != valrev.length warning "Skipping unparsable iptables rule: keys (#{keys.length}) and values (#{valrev.length}) count mismatch on line: #{line}" return end @@ -492,11 +487,11 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir # string, handling any quoted characters present in the value, and then # zipping the values with the array of keys. keys.zip(valrev) do |f, v| - if v =~ /^".*"$/ then - hash[f] = v.sub(/^"(.*)"$/, '\1').gsub(/\\(\\|'|")/, '\1') - else - hash[f] = v.dup - end + hash[f] = if v =~ %r{^".*"$} + v.sub(%r{^"(.*)"$}, '\1').gsub(%r{\\(\\|'|")}, '\1') + else + v.dup + end end ##################### @@ -504,10 +499,10 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir ##################### [:dport, :sport, :port, :state, :ctstate].each do |prop| - hash[prop] = hash[prop].split(',') if ! hash[prop].nil? + hash[prop] = hash[prop].split(',') unless hash[prop].nil? end - hash[:ipset] = hash[:ipset].split(';') if ! hash[:ipset].nil? + hash[:ipset] = hash[:ipset].split(';') unless hash[:ipset].nil? ## clean up DSCP class to HEX mappings valid_dscp_classes = { @@ -530,13 +525,13 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir '0x28' => 'cs5', '0x30' => 'cs6', '0x38' => 'cs7', - '0x2e' => 'ef' + '0x2e' => 'ef', } [:set_dscp_class].each do |prop| [:set_dscp].each do |dmark| next unless hash[dmark] hash[prop] = valid_dscp_classes[hash[dmark]] - end + end end # Convert booleans removing the previous cludge we did @@ -551,12 +546,12 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir # the types expectations. [:dport, :sport, :port].each do |prop| next unless hash[prop] - hash[prop] = hash[prop].collect do |elem| - elem.gsub(/:/,'-') + hash[prop] = hash[prop].map do |elem| + elem.tr(':', '-') end end if hash[:length] - hash[:length].gsub!(/:/,'-') + hash[:length].tr!(':', '-') end # Invert any rules that are prefixed with a '!' @@ -578,23 +573,25 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir :src_type, :state, ].each do |prop| - if hash[prop] and hash[prop].is_a?(Array) + if hash[prop] && hash[prop].is_a?(Array) # find if any are negated, then negate all if so should_negate = hash[prop].index do |value| - value.match(/^(!)\s+/) + value.match(%r{^(!)\s+}) end - hash[prop] = hash[prop].collect { |v| - "! #{v.sub(/^!\s+/,'')}" - } if should_negate - elsif hash[prop] - m = hash[prop].match(/^(!?)\s?(.*)/) - neg = "! " if m[1] == "!" - if [:source,:destination].include?(prop) - # Normalise all rules to CIDR notation. - hash[prop] = "#{neg}#{Puppet::Util::IPCidr.new(m[2]).cidr}" - else - hash[prop] = "#{neg}#{m[2]}" + if should_negate + hash[prop] = hash[prop].map do |v| + "! #{v.sub(%r{^!\s+}, '')}" + end end + elsif hash[prop] + m = hash[prop].match(%r{^(!?)\s?(.*)}) + neg = '! ' if m[1] == '!' + hash[prop] = if [:source, :destination].include?(prop) + # Normalise all rules to CIDR notation. + "#{neg}#{Puppet::Util::IPCidr.new(m[2]).cidr}" + else + "#{neg}#{m[2]}" + end end end @@ -608,39 +605,39 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir # Puppet-firewall requires that all rules have comments (resource names) and match this # regex and will fail if a rule in iptables does not have a comment. We get around this # by appending a high level - if ! hash[:name] + if !hash[:name] num = 9000 + counter hash[:name] = "#{num} #{Digest::MD5.hexdigest(line)}" - elsif not /^\d+[[:graph:][:space:]]+$/ =~ hash[:name] + elsif not %r{^\d+[[:graph:][:space:]]+$} =~ hash[:name] # rubocop:disable Style/Not : Making this change breaks the code num = 9000 + counter - hash[:name] = "#{num} #{/([[:graph:][:space:]]+)/.match(hash[:name])[1]}" + hash[:name] = "#{num} #{%r{([[:graph:][:space:]]+)}.match(hash[:name])[1]}" end # Iptables defaults to log_level '4', so it is omitted from the output of iptables-save. # If the :jump value is LOG and you don't have a log-level set, we assume it to be '4'. - if hash[:jump] == 'LOG' && ! hash[:log_level] + if hash[:jump] == 'LOG' && !hash[:log_level] hash[:log_level] = '4' end # Iptables defaults to burst '5', so it is ommitted from the output of iptables-save. # If the :limit value is set and you don't have a burst set, we assume it to be '5'. - if hash[:limit] && ! hash[:burst] + if hash[:limit] && !hash[:burst] hash[:burst] = '5' end hash[:line] = line - hash[:provider] = self.name.to_s + hash[:provider] = name.to_s hash[:table] = table hash[:ensure] = :present # Munge some vars here ... # Proto should equal 'all' if undefined - hash[:proto] = "all" if !hash.include?(:proto) + hash[:proto] = 'all' unless hash.include?(:proto) # If the jump parameter is set to one of: ACCEPT, REJECT or DROP then # we should set the action parameter instead. - if ['ACCEPT','REJECT','DROP'].include?(hash[:jump]) then + if %w[ACCEPT REJECT DROP].include?(hash[:jump]) hash[:action] = hash[:jump].downcase hash.delete(:jump) end @@ -649,28 +646,28 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir def insert_args args = [] - args << ["-I", resource[:chain], insert_order] + args << ['-I', resource[:chain], insert_order] args << general_args args end def update_args args = [] - args << ["-R", resource[:chain], insert_order] + args << ['-R', resource[:chain], insert_order] args << general_args args end def delete_args # Split into arguments - line = properties[:line].gsub(/^\-A /, '-D ').split(/\s+(?=(?:[^"]|"[^"]*")*$)/).map{|v| v.gsub(/^"/, '').gsub(/"$/, '')} - line.unshift("-t", properties[:table]) + line = properties[:line].gsub(%r{^\-A }, '-D ').split(%r{\s+(?=(?:[^"]|"[^"]*")*$)}).map { |v| v.gsub(%r{^"}, '').gsub(%r{"$}, '') } + line.unshift('-t', properties[:table]) end # This method takes the resource, and attempts to generate the command line # arguments for iptables. def general_args - debug "Current resource: %s" % resource.class + debug 'Current resource: %s' % resource.class args = [] resource_list = self.class.instance_variable_get('@resource_list') @@ -682,30 +679,25 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir # puppet is running at the same time something else is managing the rules # note: --wait wasn't added untip iptables version 1.4.20 iptables_version = Facter.value('iptables_version') - if (iptables_version && Puppet::Util::Package.versioncmp(iptables_version, '1.4.20') >= 0) + if iptables_version && Puppet::Util::Package.versioncmp(iptables_version, '1.4.20') >= 0 args << ['--wait'] end - #nflog options are not available on older OSes - [:nflog_group,:nflog_prefix,:nflog_threshold,:nflog_range].each do |nflog_feature| - fail "#{nflog_feature} is not available on iptables version #{iptables_version}" if resource[nflog_feature] && (iptables_version && iptables_version < '1.3.7') + # nflog options are not available on older OSes + [:nflog_group, :nflog_prefix, :nflog_threshold, :nflog_range].each do |nflog_feature| + raise "#{nflog_feature} is not available on iptables version #{iptables_version}" if resource[nflog_feature] && (iptables_version && iptables_version < '1.3.7') end resource_list.each do |res| resource_value = nil - if (resource[res]) then + if resource[res] resource_value = resource[res] # If socket is true then do not add the value as -m socket is standalone - if known_booleans.include?(res) then - if resource[res] == :true then - resource_value = nil - else - # If the property is not :true then we don't want to add the value - # to the args list - next - end + if known_booleans.include?(res) + next unless resource[res] == :true && known_booleans.include?(res) + resource_value = nil end - elsif res == :jump and resource[:action] then + elsif res == :jump && resource[:action] # In this case, we are substituting jump for action resource_value = resource[:action].to_s.upcase else @@ -716,54 +708,55 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir args = args.flatten # On negations, the '!' has to be before the option (eg: "! -d 1.2.3.4") - if resource_value.is_a?(String) and resource_value.sub!(/^!\s*/, '') then + if resource_value.is_a?(String) && resource_value.sub!(%r{^!\s*}, '') # we do this after adding the 'dash' argument because of ones like "-m multiport --dports", where we want it before the "--dports" but after "-m multiport". # so we insert before whatever the last argument is args.insert(-2, '!') - elsif resource_value.is_a?(Symbol) and resource_value.to_s.match(/^!/) then - #ruby 1.8.7 can't .match Symbols ------------------ ^ - resource_value = resource_value.to_s.sub!(/^!\s*/, '').to_sym + elsif resource_value.is_a?(Symbol) && resource_value.to_s.match(%r{^!}) + # ruby 1.8.7 can't .match Symbols ------------------ ^ + resource_value = resource_value.to_s.sub!(%r{^!\s*}, '').to_sym args.insert(-2, '!') - elsif resource_value.is_a?(Array) and res != :ipset + elsif resource_value.is_a?(Array) && res != :ipset should_negate = resource_value.index do |value| - #ruby 1.8.7 can't .match symbols - value.to_s.match(/^(!)\s+/) + # ruby 1.8.7 can't .match symbols + value.to_s.match(%r{^(!)\s+}) end if should_negate - resource_value, wrong_values = resource_value.collect do |value| + resource_value, wrong_values = resource_value.map { |value| + # rubocop:disable Metrics/BlockNesting if value.is_a?(String) - wrong = value if ! value.match(/^!\s+/) - [value.sub(/^!\s*/, ''),wrong] + wrong = value unless value =~ %r{^!\s+} + [value.sub(%r{^!\s*}, ''), wrong] else - [value,nil] + [value, nil] end - end.transpose + }.transpose wrong_values = wrong_values.compact - if ! wrong_values.empty? - fail "All values of the '#{res}' property must be prefixed with a '!' when inverting, but '#{wrong_values.join("', '")}' #{wrong_values.length>1?"are":"is"} not prefixed; aborting" + unless wrong_values.empty? + raise "All values of the '#{res}' property must be prefixed with a '!' when inverting, but '#{wrong_values.join("', '")}' #{(wrong_values.length > 1) ? 'are' : 'is'} not prefixed; aborting" # rubocop:disable Metrics/LineLength : Line length cannot be reduced end args.insert(-2, '!') + # rubocop:enable Metrics/BlockNesting end end - # For sport and dport, convert hyphens to colons since the type # expects hyphens for ranges of ports. - if [:sport, :dport, :port].include?(res) then - resource_value = resource_value.collect do |elem| - elem.gsub(/-/, ':') + if [:sport, :dport, :port].include?(res) + resource_value = resource_value.map do |elem| + elem.tr('-', ':') end end # ipset can accept multiple values with weird iptables arguments if res == :ipset resource_value.join(" #{[resource_map[res]].flatten.first} ").split(' ').each do |a| - if a.sub!(/^!\s*/, '') + if a.sub!(%r{^!\s*}, '') # Negate ipset options args.insert(-2, '!') end - args << a if a.length > 0 + args << a unless a.empty? end # our tcp_flags takes a single string with comma lists separated # by space @@ -783,12 +776,12 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir end def insert_order - debug("[insert_order]") + debug('[insert_order]') rules = [] # Find list of current rules based on chain and table self.class.instances.each do |rule| - if rule.chain == resource[:chain].to_s and rule.table == resource[:table].to_s + if rule.chain == resource[:chain].to_s && rule.table == resource[:table].to_s rules << rule.name end end @@ -800,21 +793,21 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir my_rule = resource[:name].to_s rules << my_rule - unmanaged_rule_regex = /^9[0-9]{3}\s.*$/ + unmanaged_rule_regex = %r{^9[0-9]{3}\s.*$} # Find if this is a new rule or an existing rule, then find how many # unmanaged rules preceed it. if rules.length == rules.uniq.length # This is a new rule so find its ordered location. new_rule_location = rules.sort.uniq.index(my_rule) - if new_rule_location == 0 - # The rule will be the first rule in the chain because nothing came - # before it. - offset_rule = rules[0] - else - # This rule will come after other managed rules, so find the rule - # immediately preceeding it. - offset_rule = rules.sort.uniq[new_rule_location - 1] - end + offset_rule = if new_rule_location.zero? + # The rule will be the first rule in the chain because nothing came + # before it. + rules[0] + else + # This rule will come after other managed rules, so find the rule + # immediately preceeding it. + rules.sort.uniq[new_rule_location - 1] + end else # This is a pre-existing rule, so find the offset from the original # ordering. @@ -822,19 +815,19 @@ Puppet::Type.type(:firewall).provide :iptables, :parent => Puppet::Provider::Fir end # Count how many unmanaged rules are ahead of the target rule so we know # how much to add to the insert order - unnamed_offset = rules[0..rules.index(offset_rule)].inject(0) do |sum,rule| + unnamed_offset = rules[0..rules.index(offset_rule)].reduce(0) do |sum, rule| # This regex matches the names given to unmanaged rules (a number # 9000-9999 followed by an MD5 hash). sum + (rule.match(unmanaged_rule_regex) ? 1 : 0) end # We want our rule to come before unmanaged rules if it's not a 9-rule - if offset_rule.match(unmanaged_rule_regex) and ! my_rule.match(/^9/) + if offset_rule.match(unmanaged_rule_regex) && !my_rule.match(%r{^9}) unnamed_offset -= 1 end # Insert our new or updated rule in the correct order of named rules, but # offset for unnamed rules. - rules.reject{|r|r.match(unmanaged_rule_regex)}.sort.index(my_rule) + 1 + unnamed_offset + rules.reject { |r| r.match(unmanaged_rule_regex) }.sort.index(my_rule) + 1 + unnamed_offset end end diff --git a/lib/puppet/provider/firewallchain/iptables_chain.rb b/lib/puppet/provider/firewallchain/iptables_chain.rb index ec10ecc..5bc03c3 100644 --- a/lib/puppet/provider/firewallchain/iptables_chain.rb +++ b/lib/puppet/provider/firewallchain/iptables_chain.rb @@ -1,49 +1,47 @@ Puppet::Type.type(:firewallchain).provide :iptables_chain do include Puppet::Util::Firewall - @doc = "Iptables chain provider" + @doc = 'Iptables chain provider' has_feature :iptables_chain has_feature :policy - optional_commands({ - :iptables => 'iptables', - :iptables_save => 'iptables-save', - :ip6tables => 'ip6tables', - :ip6tables_save => 'ip6tables-save', - :ebtables => 'ebtables', - :ebtables_save => 'ebtables-save', - }) + optional_commands(iptables: 'iptables', + iptables_save: 'iptables-save', + ip6tables: 'ip6tables', + ip6tables_save: 'ip6tables-save', + ebtables: 'ebtables', + ebtables_save: 'ebtables-save') - defaultfor :kernel => :linux - confine :kernel => :linux + defaultfor kernel: :linux + confine kernel: :linux # chain name is greedy so we anchor from the end. # [\d+:\d+] doesn't exist on ebtables - Mapping = { - :IPv4 => { - :tables => method(:iptables), - :save => method(:iptables_save), - :re => /^:(.+)\s(\S+)\s\[\d+:\d+\]$/, + MAPPING = { + IPv4: { + tables: method(:iptables), + save: method(:iptables_save), + re: %r{^:(.+)\s(\S+)\s\[\d+:\d+\]$}, }, - :IPv6 => { - :tables => method(:ip6tables), - :save => method(:ip6tables_save), - :re => /^:(.+)\s(\S+)\s\[\d+:\d+\]$/, + IPv6: { + tables: method(:ip6tables), + save: method(:ip6tables_save), + re: %r{^:(.+)\s(\S+)\s\[\d+:\d+\]$}, }, - :ethernet => { - :tables => method(:ebtables), - :save => method(:ebtables_save), - :re => /^:(.+)\s(\S+)$/, - } - } - InternalChains = /^(PREROUTING|POSTROUTING|BROUTING|INPUT|FORWARD|OUTPUT)$/ - Tables = 'nat|mangle|filter|raw|rawpost|broute|security' - Nameformat = /^(.+):(#{Tables}):(IP(v[46])?|ethernet)$/ + ethernet: { + tables: method(:ebtables), + save: method(:ebtables_save), + re: %r{^:(.+)\s(\S+)$}, + }, + }.freeze + INTERNAL_CHAINS = %r{^(PREROUTING|POSTROUTING|BROUTING|INPUT|FORWARD|OUTPUT)$} + TABLES = 'nat|mangle|filter|raw|rawpost|broute|security'.freeze + NAME_FORMAT = %r{^(.+):(#{TABLES}):(IP(v[46])?|ethernet)$} def create allvalidchains do |t, chain, table, protocol| - if chain =~ InternalChains + if chain =~ INTERNAL_CHAINS # can't create internal chains warning "Attempting to create internal chain #{@resource[:name]}" end @@ -51,9 +49,9 @@ Puppet::Type.type(:firewallchain).provide :iptables_chain do debug "Skipping Inserting chain #{chain} on table #{table} (#{protocol}) already exists" else debug "Inserting chain #{chain} on table #{table} (#{protocol}) using #{t}" - t.call ['-t',table,'-N',chain] + t.call ['-t', table, '-N', chain] unless @resource[:policy].nil? - t.call ['-t',table,'-P',chain,@resource[:policy].to_s.upcase] + t.call ['-t', table, '-P', chain, @resource[:policy].to_s.upcase] end end end @@ -61,18 +59,18 @@ Puppet::Type.type(:firewallchain).provide :iptables_chain do def destroy allvalidchains do |t, chain, table| - if chain =~ InternalChains + if chain =~ INTERNAL_CHAINS # can't delete internal chains warning "Attempting to destroy internal chain #{@resource[:name]}" end debug "Deleting chain #{chain} on table #{table}" - t.call ['-t',table,'-X',chain] + t.call ['-t', table, '-X', chain] end end def exists? - allvalidchains do |t, chain| - if chain =~ InternalChains + allvalidchains do |_t, chain| + if chain =~ INTERNAL_CHAINS # If the chain isn't present, it's likely because the module isn't loaded. # If this is true, then we fall into 2 cases # 1) It'll be loaded on demand @@ -88,7 +86,7 @@ Puppet::Type.type(:firewallchain).provide :iptables_chain do def policy=(value) return if value == :empty allvalidchains do |t, chain, table| - p = ['-t',table,'-P',chain,value.to_s.upcase] + p = ['-t', table, '-P', chain, value.to_s.upcase] debug "[set policy] #{t} #{p}" t.call p end @@ -96,21 +94,22 @@ Puppet::Type.type(:firewallchain).provide :iptables_chain do def policy debug "[get policy] #{@resource[:name]} =#{@property_hash[:policy].to_s.downcase}" - return @property_hash[:policy].to_s.downcase + @property_hash[:policy].to_s.downcase end def self.prefetch(resources) - debug("[prefetch(resources)]") + debug('[prefetch(resources)]') instances.each do |prov| - if resource = resources[prov.name] + resource = resources[prov.name] + if resource resource.provider = prov end end end def flush - debug("[flush]") - persist_iptables(@resource[:name].match(Nameformat)[3]) + debug('[flush]') + persist_iptables(@resource[:name].match(NAME_FORMAT)[3]) # Clear the property hash so we re-initialize with updated values @property_hash.clear end @@ -119,7 +118,7 @@ Puppet::Type.type(:firewallchain).provide :iptables_chain do # existing status with properties[:foo]. def properties if @property_hash.empty? - @property_hash = query || {:ensure => :absent} + @property_hash = query || { ensure: :absent } end @property_hash.dup end @@ -127,8 +126,8 @@ Puppet::Type.type(:firewallchain).provide :iptables_chain do # Pull the current state of the list from the full list. def query self.class.instances.each do |instance| - if instance.name == self.name - debug "query found #{self.name}" % instance.properties.inspect + if instance.name == name + debug "query found #{name}" % instance.properties.inspect return instance.properties end end @@ -136,44 +135,41 @@ Puppet::Type.type(:firewallchain).provide :iptables_chain do end def self.instances - debug "[instances]" + debug '[instances]' table = nil chains = [] - Mapping.each { |p, c| + MAPPING.each do |p, c| begin c[:save].call.each_line do |line| - if line =~ c[:re] then - name = $1 + ':' + (table == 'filter' ? 'filter' : table) + ':' + p.to_s - policy = $2 == '-' ? nil : $2.downcase.to_sym + if line =~ c[:re] + name = Regexp.last_match(1) + ':' + ((table == 'filter') ? 'filter' : table) + ':' + p.to_s + policy = (Regexp.last_match(2) == '-') ? nil : Regexp.last_match(2).downcase.to_sym - chains << new({ - :name => name, - :policy => policy, - :ensure => :present, - }) + chains << new(name: name, + policy: policy, + ensure: :present) debug "[instance] '#{name}' #{policy}" - elsif line =~ /^\*(\S+)/ - table = $1 + elsif line =~ %r{^\*(\S+)} + table = Regexp.last_match(1) else next end end - rescue Puppet::Error + rescue Puppet::Error # rubocop:disable Lint/HandleExceptions # ignore command not found for ebtables or anything that doesn't exist end - } + end chains end def allvalidchains - @resource[:name].match(Nameformat) - chain = $1 - table = $2 - protocol = $3 - yield Mapping[protocol.to_sym][:tables],chain,table,protocol.to_sym + @resource[:name].match(NAME_FORMAT) + chain = Regexp.last_match(1) + table = Regexp.last_match(2) + protocol = Regexp.last_match(3) + yield MAPPING[protocol.to_sym][:tables], chain, table, protocol.to_sym end - end diff --git a/lib/puppet/type/firewall.rb b/lib/puppet/type/firewall.rb index 6b706a3..1307f13 100644 --- a/lib/puppet/type/firewall.rb +++ b/lib/puppet/type/firewall.rb @@ -6,7 +6,7 @@ # In this case I'm trying the relative path first, then falling back to normal # mechanisms. This should be fixed in future versions of puppet but it looks # like we'll need to maintain this for some time perhaps. -$LOAD_PATH.unshift(File.join(File.dirname(__FILE__),"..","..")) +$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', '..')) require 'puppet/util/firewall' Puppet::Type.newtype(:firewall) do @@ -28,49 +28,49 @@ Puppet::Type.newtype(:firewall) do installed. EOS - feature :connection_limiting, "Connection limiting features." - feature :hop_limiting, "Hop limiting features." - feature :rate_limiting, "Rate limiting features." - feature :recent_limiting, "The netfilter recent module" - feature :snat, "Source NATing" - feature :dnat, "Destination NATing" - feature :netmap, "NET MAPping" - feature :interface_match, "Interface matching" - feature :icmp_match, "Matching ICMP types" - feature :owner, "Matching owners" - feature :state_match, "Matching stateful firewall states" - feature :reject_type, "The ability to control reject messages" - feature :log_level, "The ability to control the log level" - feature :log_prefix, "The ability to add prefixes to log messages" - feature :log_uid, "Add UIDs to log messages" - feature :mark, "Match or Set the netfilter mark value associated with the packet" - feature :mss, "Match a given TCP MSS value or range." - feature :tcp_flags, "The ability to match on particular TCP flag settings" - feature :pkttype, "Match a packet type" - feature :socket, "Match open sockets" - feature :isfragment, "Match fragments" - feature :address_type, "The ability match on source or destination address type" - feature :iprange, "The ability match on source or destination IP range " - feature :ishasmorefrags, "Match a non-last fragment of a fragmented ipv6 packet - might be first" - feature :islastfrag, "Match the last fragment of an ipv6 packet" - feature :isfirstfrag, "Match the first fragment of a fragmented ipv6 packet" - feature :ipsec_policy, "Match IPsec policy" - feature :ipsec_dir, "Match IPsec policy direction" - feature :mask, "Ability to match recent rules based on the ipv4 mask" - feature :nflog_group, "netlink group to subscribe to for logging" - feature :nflog_prefix, "" - feature :nflog_range, "" - feature :nflog_threshold, "" - feature :ipset, "Match against specified ipset list" - feature :clusterip, "Configure a simple cluster of nodes that share a certain IP and MAC address without an explicit load balancer in front of them." - feature :length, "Match the length of layer-3 payload" - feature :string_matching, "String matching features" - feature :queue_num, "Which NFQUEUE to send packets to" - feature :queue_bypass, "If nothing is listening on queue_num, allow packets to bypass the queue" - feature :hashlimit, "Hashlimit features" + feature :connection_limiting, 'Connection limiting features.' + feature :hop_limiting, 'Hop limiting features.' + feature :rate_limiting, 'Rate limiting features.' + feature :recent_limiting, 'The netfilter recent module' + feature :snat, 'Source NATing' + feature :dnat, 'Destination NATing' + feature :netmap, 'NET MAPping' + feature :interface_match, 'Interface matching' + feature :icmp_match, 'Matching ICMP types' + feature :owner, 'Matching owners' + feature :state_match, 'Matching stateful firewall states' + feature :reject_type, 'The ability to control reject messages' + feature :log_level, 'The ability to control the log level' + feature :log_prefix, 'The ability to add prefixes to log messages' + feature :log_uid, 'Add UIDs to log messages' + feature :mark, 'Match or Set the netfilter mark value associated with the packet' + feature :mss, 'Match a given TCP MSS value or range.' + feature :tcp_flags, 'The ability to match on particular TCP flag settings' + feature :pkttype, 'Match a packet type' + feature :socket, 'Match open sockets' + feature :isfragment, 'Match fragments' + feature :address_type, 'The ability match on source or destination address type' + feature :iprange, 'The ability match on source or destination IP range ' + feature :ishasmorefrags, 'Match a non-last fragment of a fragmented ipv6 packet - might be first' + feature :islastfrag, 'Match the last fragment of an ipv6 packet' + feature :isfirstfrag, 'Match the first fragment of a fragmented ipv6 packet' + feature :ipsec_policy, 'Match IPsec policy' + feature :ipsec_dir, 'Match IPsec policy direction' + feature :mask, 'Ability to match recent rules based on the ipv4 mask' + feature :nflog_group, 'netlink group to subscribe to for logging' + feature :nflog_prefix, '' + feature :nflog_range, '' + feature :nflog_threshold, '' + feature :ipset, 'Match against specified ipset list' + feature :clusterip, 'Configure a simple cluster of nodes that share a certain IP and MAC address without an explicit load balancer in front of them.' + feature :length, 'Match the length of layer-3 payload' + feature :string_matching, 'String matching features' + feature :queue_num, 'Which NFQUEUE to send packets to' + feature :queue_bypass, 'If nothing is listening on queue_num, allow packets to bypass the queue' + feature :hashlimit, 'Hashlimit features' # provider specific features - feature :iptables, "The provider provides iptables features." + feature :iptables, 'The provider provides iptables features.' ensurable do desc <<-EOS @@ -102,7 +102,7 @@ Puppet::Type.newtype(:firewall) do isnamevar # Keep rule names simple - they must start with a number - newvalues(/^\d+[[:graph:][:space:]]+$/) + newvalues(%r{^\d+[[:graph:][:space:]]+$}) end newproperty(:action) do @@ -140,19 +140,19 @@ Puppet::Type.newtype(:firewall) do when :ip6tables protocol = :IPv6 else - self.fail("cannot work out protocol family") + raise('cannot work out protocol family') end begin @resource.host_to_mask(value, protocol) - rescue Exception => e - self.fail("host_to_ip failed for #{value}, exception #{e}") + rescue StandardError => e + raise("host_to_ip failed for #{value}, exception #{e}") end end end # Source IP range - newproperty(:src_range, :required_features => :iprange) do + newproperty(:src_range, required_features: :iprange) do desc <<-EOS The source IP range. For example: @@ -162,19 +162,17 @@ Puppet::Type.newtype(:firewall) do EOS validate do |value| - if matches = /^([^\-\/]+)-([^\-\/]+)$/.match(value) - start_addr = matches[1] - end_addr = matches[2] - - [start_addr, end_addr].each do |addr| - begin - @resource.host_to_ip(addr) - rescue Exception - self.fail("Invalid IP address \"#{addr}\" in range \"#{value}\"") - end + matches = %r{^([^\-\/]+)-([^\-\/]+)$}.match(value) + raise(ArgumentError, "The source IP range must be in 'IP1-IP2' format.") unless matches + start_addr = matches[1] + end_addr = matches[2] + + [start_addr, end_addr].each do |addr| + begin + @resource.host_to_ip(addr) + rescue StandardError + raise("Invalid IP address \"#{addr}\" in range \"#{value}\"") end - else - raise(ArgumentError, "The source IP range must be in 'IP1-IP2' format.") end end end @@ -199,19 +197,19 @@ Puppet::Type.newtype(:firewall) do when :ip6tables protocol = :IPv6 else - self.fail("cannot work out protocol family") + raise('cannot work out protocol family') end begin @resource.host_to_mask(value, protocol) - rescue Exception => e - self.fail("host_to_ip failed for #{value}, exception #{e}") + rescue StandardError => e + raise("host_to_ip failed for #{value}, exception #{e}") end end end # Destination IP range - newproperty(:dst_range, :required_features => :iprange) do + newproperty(:dst_range, required_features: :iprange) do desc <<-EOS The destination IP range. For example: @@ -221,24 +219,22 @@ Puppet::Type.newtype(:firewall) do EOS validate do |value| - if matches = /^([^\-\/]+)-([^\-\/]+)$/.match(value) - start_addr = matches[1] - end_addr = matches[2] - - [start_addr, end_addr].each do |addr| - begin - @resource.host_to_ip(addr) - rescue Exception - self.fail("Invalid IP address \"#{addr}\" in range \"#{value}\"") - end + matches = %r{^([^\-\/]+)-([^\-\/]+)$}.match(value) + raise(ArgumentError, "The destination IP range must be in 'IP1-IP2' format.") unless matches + start_addr = matches[1] + end_addr = matches[2] + + [start_addr, end_addr].each do |addr| + begin + @resource.host_to_ip(addr) + rescue StandardError + raise("Invalid IP address \"#{addr}\" in range \"#{value}\"") end - else - raise(ArgumentError, "The destination IP range must be in 'IP1-IP2' format.") end end end - newproperty(:sport, :array_matching => :all) do + newproperty(:sport, array_matching: :all) do desc <<-EOS The source port to match for this filter (if the protocol supports ports). Will accept a single element or an array. @@ -258,7 +254,7 @@ Puppet::Type.newtype(:firewall) do @resource.string_to_port(value, :proto) end - def is_to_s(value) + def to_s?(value) should_to_s(value) end @@ -268,7 +264,7 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:dport, :array_matching => :all) do + newproperty(:dport, array_matching: :all) do desc <<-EOS The destination port to match for this filter (if the protocol supports ports). Will accept a single element or an array. @@ -288,7 +284,7 @@ Puppet::Type.newtype(:firewall) do @resource.string_to_port(value, :proto) end - def is_to_s(value) + def to_s?(value) should_to_s(value) end @@ -298,7 +294,7 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:port, :array_matching => :all) do + newproperty(:port, array_matching: :all) do desc <<-EOS DEPRECATED @@ -316,7 +312,7 @@ Puppet::Type.newtype(:firewall) do This would cover ports 1 to 1024. EOS - validate do |value| + validate do |_value| Puppet.warning('Passing port to firewall is deprecated and will be removed. Use dport and/or sport instead.') end @@ -324,7 +320,7 @@ Puppet::Type.newtype(:firewall) do @resource.string_to_port(value, :proto) end - def is_to_s(value) + def to_s?(value) should_to_s(value) end @@ -334,7 +330,7 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:dst_type, :required_features => :address_type) do + newproperty(:dst_type, required_features: :address_type) do desc <<-EOS The destination address type. For example: @@ -357,12 +353,12 @@ Puppet::Type.newtype(:firewall) do EOS newvalues(*[:UNSPEC, :UNICAST, :LOCAL, :BROADCAST, :ANYCAST, :MULTICAST, - :BLACKHOLE, :UNREACHABLE, :PROHIBIT, :THROW, :NAT, :XRESOLVE].collect do |address_type| - [address_type, "! #{address_type}".to_sym] - end.flatten) + :BLACKHOLE, :UNREACHABLE, :PROHIBIT, :THROW, :NAT, :XRESOLVE].map { |address_type| + [address_type, "! #{address_type}".to_sym] + }.flatten) end - newproperty(:src_type, :required_features => :address_type) do + newproperty(:src_type, required_features: :address_type) do desc <<-EOS The source address type. For example: @@ -385,9 +381,9 @@ Puppet::Type.newtype(:firewall) do EOS newvalues(*[:UNSPEC, :UNICAST, :LOCAL, :BROADCAST, :ANYCAST, :MULTICAST, - :BLACKHOLE, :UNREACHABLE, :PROHIBIT, :THROW, :NAT, :XRESOLVE].collect do |address_type| - [address_type, "! #{address_type}".to_sym] - end.flatten) + :BLACKHOLE, :UNREACHABLE, :PROHIBIT, :THROW, :NAT, :XRESOLVE].map { |address_type| + [address_type, "! #{address_type}".to_sym] + }.flatten) end newproperty(:proto) do @@ -396,10 +392,10 @@ Puppet::Type.newtype(:firewall) do *tcp*. EOS - newvalues(*[:ip, :tcp, :udp, :icmp, :"ipv6-icmp", :esp, :ah, :vrrp, :igmp, :ipencap, :ipv4, :ipv6, :ospf, :gre, :cbt, :sctp, :pim, :all].collect do |proto| + newvalues(*[:ip, :tcp, :udp, :icmp, :"ipv6-icmp", :esp, :ah, :vrrp, :igmp, :ipencap, :ipv4, :ipv6, :ospf, :gre, :cbt, :sctp, :pim, :all].map { |proto| [proto, "! #{proto}".to_sym] - end.flatten) - defaultto "tcp" + }.flatten) + defaultto 'tcp' end # tcp-specific @@ -410,7 +406,7 @@ Puppet::Type.newtype(:firewall) do end # tcp-specific - newproperty(:tcp_flags, :required_features => :tcp_flags) do + newproperty(:tcp_flags, required_features: :tcp_flags) do desc <<-EOS Match when the TCP flags are as specified. Is a string with a list of comma-separated flag names for the mask, @@ -424,9 +420,8 @@ Puppet::Type.newtype(:firewall) do EOS end - # Iptables specific - newproperty(:chain, :required_features => :iptables) do + newproperty(:chain, required_features: :iptables) do desc <<-EOS Name of the chain to use. Can be one of the built-ins: @@ -441,11 +436,11 @@ Puppet::Type.newtype(:firewall) do The default value is 'INPUT'. EOS - defaultto "INPUT" - newvalue(/^[a-zA-Z0-9\-_]+$/) + defaultto 'INPUT' + newvalue(%r{^[a-zA-Z0-9\-_]+$}) end - newproperty(:table, :required_features => :iptables) do + newproperty(:table, required_features: :iptables) do desc <<-EOS Table to use. Can be one of: @@ -459,10 +454,10 @@ Puppet::Type.newtype(:firewall) do EOS newvalues(:nat, :mangle, :filter, :raw, :rawpost) - defaultto "filter" + defaultto 'filter' end - newproperty(:jump, :required_features => :iptables) do + newproperty(:jump, required_features: :iptables) do desc <<-EOS The value for the iptables --jump parameter. Normal values are: @@ -487,24 +482,23 @@ Puppet::Type.newtype(:firewall) do EOS validate do |value| - unless value =~ /^[a-zA-Z0-9\-_]+$/ + unless value =~ %r{^[a-zA-Z0-9\-_]+$} raise ArgumentError, <<-EOS Jump destination must consist of alphanumeric characters, an underscore or a yphen. EOS end - if ["accept","reject","drop"].include?(value.downcase) + if %w[accept reject drop].include?(value.downcase) raise ArgumentError, <<-EOS Jump destination should not be one of ACCEPT, REJECT or DROP. Use the action property instead. EOS end - end end - newproperty(:goto, :required_features => :iptables) do + newproperty(:goto, required_features: :iptables) do desc <<-EOS The value for the iptables --goto parameter. Normal values are: @@ -521,25 +515,24 @@ Puppet::Type.newtype(:firewall) do EOS validate do |value| - unless value =~ /^[a-zA-Z0-9\-_]+$/ + unless value =~ %r{^[a-zA-Z0-9\-_]+$} raise ArgumentError, <<-EOS Goto destination must consist of alphanumeric characters, an underscore or a yphen. EOS end - if ["accept","reject","drop"].include?(value.downcase) + if %w[accept reject drop].include?(value.downcase) raise ArgumentError, <<-EOS Goto destination should not be one of ACCEPT, REJECT or DROP. Use the action property instead. EOS end - end end # Interface specific matching properties - newproperty(:iniface, :required_features => :interface_match) do + newproperty(:iniface, required_features: :interface_match) do desc <<-EOS Input interface to filter on. Supports interface alias like eth0:0. To negate the match try this: @@ -547,10 +540,10 @@ Puppet::Type.newtype(:firewall) do iniface => '! lo', EOS - newvalues(/^!?\s?[a-zA-Z0-9\-\._\+\:]+$/) + newvalues(%r{^!?\s?[a-zA-Z0-9\-\._\+\:]+$}) end - newproperty(:outiface, :required_features => :interface_match) do + newproperty(:outiface, required_features: :interface_match) do desc <<-EOS Output interface to filter on. Supports interface alias like eth0:0. To negate the match try this: @@ -558,37 +551,37 @@ Puppet::Type.newtype(:firewall) do outiface => '! lo', EOS - newvalues(/^!?\s?[a-zA-Z0-9\-\._\+\:]+$/) + newvalues(%r{^!?\s?[a-zA-Z0-9\-\._\+\:]+$}) end # NAT specific properties - newproperty(:tosource, :required_features => :snat) do + newproperty(:tosource, required_features: :snat) do desc <<-EOS When using jump => "SNAT" you can specify the new source address using this parameter. EOS end - newproperty(:todest, :required_features => :dnat) do + newproperty(:todest, required_features: :dnat) do desc <<-EOS When using jump => "DNAT" you can specify the new destination address using this paramter. EOS end - newproperty(:toports, :required_features => :dnat) do + newproperty(:toports, required_features: :dnat) do desc <<-EOS For DNAT this is the port that will replace the destination port. EOS end - newproperty(:to, :required_features => :netmap) do + newproperty(:to, required_features: :netmap) do desc <<-EOS For NETMAP this will replace the destination IP EOS end - newproperty(:random, :required_features => :dnat) do + newproperty(:random, required_features: :dnat) do desc <<-EOS When using a jump value of "MASQUERADE", "DNAT", "REDIRECT", or "SNAT" this boolean will enable randomized port mapping. @@ -598,7 +591,7 @@ Puppet::Type.newtype(:firewall) do end # Reject ICMP type - newproperty(:reject, :required_features => :reject_type) do + newproperty(:reject, required_features: :reject_type) do desc <<-EOS When combined with jump => "REJECT" you can specify a different icmp response to be sent back to the packet sender. @@ -606,34 +599,34 @@ Puppet::Type.newtype(:firewall) do end # Logging properties - newproperty(:log_level, :required_features => :log_level) do + newproperty(:log_level, required_features: :log_level) do desc <<-EOS When combined with jump => "LOG" specifies the system log level to log to. EOS munge do |value| - if value.kind_of?(String) + if value.is_a?(String) value = @resource.log_level_name_to_number(value) else value end - if value == nil && value != "" - self.fail("Unable to determine log level") + if value.nil? && value != '' + raise('Unable to determine log level') end value end end - newproperty(:log_prefix, :required_features => :log_prefix) do + newproperty(:log_prefix, required_features: :log_prefix) do desc <<-EOS When combined with jump => "LOG" specifies the log prefix to use when logging. EOS end - newproperty(:log_uid, :required_features => :log_uid) do + newproperty(:log_uid, required_features: :log_uid) do desc <<-EOS When combined with jump => "LOG" specifies the uid of the process making the connection. @@ -642,7 +635,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:nflog_group, :required_features => :nflog_group) do + newproperty(:nflog_group, required_features: :nflog_group) do desc <<-EOS Used with the jump target NFLOG. The netlink group (0 - 2^16-1) to which packets are (only applicable @@ -650,13 +643,13 @@ Puppet::Type.newtype(:firewall) do EOS validate do |value| - if value.to_i > (2**16)-1 || value.to_i < 0 - raise ArgumentError, "nflog_group must be between 0 and 2^16-1" + if value.to_i > (2**16) - 1 || value.to_i < 0 + raise ArgumentError, 'nflog_group must be between 0 and 2^16-1' end end munge do |value| - if value.is_a?(String) and value =~ /^[-0-9]+$/ + if value.is_a?(String) && value =~ %r{^[-0-9]+$} Integer(value) else value @@ -664,7 +657,7 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:nflog_prefix, :required_features => :nflog_prefix) do + newproperty(:nflog_prefix, required_features: :nflog_prefix) do desc <<-EOS Used with the jump target NFLOG. A prefix string to include in the log message, up to 64 characters long, @@ -673,12 +666,12 @@ Puppet::Type.newtype(:firewall) do validate do |value| if value.length > 64 - raise ArgumentError, "nflog_prefix must be less than 64 characters." + raise ArgumentError, 'nflog_prefix must be less than 64 characters.' end end end - newproperty(:nflog_range, :required_features => :nflog_range) do + newproperty(:nflog_range, required_features: :nflog_range) do desc <<-EOS Used with the jump target NFLOG. The number of bytes to be copied to userspace (only applicable for nfnetlink_log). @@ -686,7 +679,7 @@ Puppet::Type.newtype(:firewall) do EOS end - newproperty(:nflog_threshold, :required_features => :nflog_threshold) do + newproperty(:nflog_threshold, required_features: :nflog_threshold) do desc <<-EOS Used with the jump target NFLOG. Number of packets to queue inside the kernel before sending them to userspace @@ -695,7 +688,7 @@ Puppet::Type.newtype(:firewall) do EOS munge do |value| - if value.is_a?(String) and value =~ /^[-0-9]+$/ + if value.is_a?(String) && value =~ %r{^[-0-9]+$} Integer(value) else value @@ -704,7 +697,7 @@ Puppet::Type.newtype(:firewall) do end # ICMP matching property - newproperty(:icmp, :required_features => :icmp_match) do + newproperty(:icmp, required_features: :icmp_match) do desc <<-EOS When matching ICMP packets, this is the type of ICMP packet to match. @@ -715,20 +708,20 @@ Puppet::Type.newtype(:firewall) do EOS validate do |value| - if value == "any" + if value == 'any' raise ArgumentError, - "Value 'any' is not valid. This behaviour should be achieved " \ - "by omitting or undefining the ICMP parameter." + "Value 'any' is not valid. This behaviour should be achieved " \ + 'by omitting or undefining the ICMP parameter.' end - if value.kind_of?(Array) + if value.is_a?(Array) raise ArgumentError, - "Argument must not be an array of values. To match multiple " \ - "ICMP types, please use separate rules for each ICMP type." + 'Argument must not be an array of values. To match multiple ' \ + 'ICMP types, please use separate rules for each ICMP type.' end end munge do |value| - if value.kind_of?(String) + if value.is_a?(String) # ICMP codes differ between IPv4 and IPv6. case @resource[:provider] when :iptables @@ -736,7 +729,7 @@ Puppet::Type.newtype(:firewall) do when :ip6tables protocol = 'inet6' else - self.fail("cannot work out protocol family") + raise('cannot work out protocol family') end value = @resource.icmp_name_to_number(value, protocol) @@ -744,17 +737,14 @@ Puppet::Type.newtype(:firewall) do value end - if value == nil && value != "" - self.fail("cannot work out icmp type") + if value.nil? && value != '' + raise('cannot work out icmp type') end value - end end - newproperty(:state, :array_matching => :all, :required_features => - :state_match) do - + newproperty(:state, array_matching: :all, required_features: :state_match) do desc <<-EOS Matches a packet based on its state in the firewall stateful inspection table. Values can be: @@ -766,15 +756,15 @@ Puppet::Type.newtype(:firewall) do * UNTRACKED EOS - newvalues(:INVALID,:ESTABLISHED,:NEW,:RELATED,:UNTRACKED) + newvalues(:INVALID, :ESTABLISHED, :NEW, :RELATED, :UNTRACKED) # States should always be sorted. This normalizes the resource states to # keep it consistent with the sorted result from iptables-save. def should=(values) - @should = super(values).sort_by {|sym| sym.to_s} + @should = super(values).sort_by { |sym| sym.to_s } end - def is_to_s(value) + def to_s?(value) should_to_s(value) end @@ -784,9 +774,7 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:ctstate, :array_matching => :all, :required_features => - :state_match) do - + newproperty(:ctstate, array_matching: :all, required_features: :state_match) do desc <<-EOS Matches a packet based on its state in the firewall stateful inspection table, using the conntrack module. Values can be: @@ -798,15 +786,15 @@ Puppet::Type.newtype(:firewall) do * UNTRACKED EOS - newvalues(:INVALID,:ESTABLISHED,:NEW,:RELATED,:UNTRACKED) + newvalues(:INVALID, :ESTABLISHED, :NEW, :RELATED, :UNTRACKED) # States should always be sorted. This normalizes the resource states to # keep it consistent with the sorted result from iptables-save. def should=(values) - @should = super(values).sort_by {|sym| sym.to_s} + @should = super(values).sort_by { |sym| sym.to_s } end - def is_to_s(value) + def to_s?(value) should_to_s(value) end @@ -816,9 +804,8 @@ Puppet::Type.newtype(:firewall) do end end - # Connection mark - newproperty(:connmark, :required_features => :mark) do + newproperty(:connmark, required_features: :mark) do desc <<-EOS Match the Netfilter mark value associated with the packet. Accepts either of: mark/mask or mark. These will be converted to hex if they are not already. @@ -830,13 +817,13 @@ Puppet::Type.newtype(:firewall) do # Values that can't be converted to hex. # Or contain a trailing slash with no mask. - if mark.nil? or (mark and match[2] and match[3].nil?) - raise ArgumentError, "MARK value must be integer or hex between 0 and 0xffffffff" + if mark.nil? || (mark && match[2] && match[3].nil?) + raise ArgumentError, 'MARK value must be integer or hex between 0 and 0xffffffff' end # There should not be a mask on connmark unless match[3].nil? - raise ArgumentError, "iptables does not support masks on MARK match rules" + raise ArgumentError, 'iptables does not support masks on MARK match rules' end value = mark @@ -845,32 +832,32 @@ Puppet::Type.newtype(:firewall) do end # Connection limiting properties - newproperty(:connlimit_above, :required_features => :connection_limiting) do + newproperty(:connlimit_above, required_features: :connection_limiting) do desc <<-EOS Connection limiting value for matched connections above n. EOS - newvalue(/^\d+$/) + newvalue(%r{^\d+$}) end - newproperty(:connlimit_mask, :required_features => :connection_limiting) do + newproperty(:connlimit_mask, required_features: :connection_limiting) do desc <<-EOS Connection limiting by subnet mask for matched connections. IPv4: 0-32 IPv6: 0-128 EOS - newvalue(/^\d+$/) + newvalue(%r{^\d+$}) end # Hop limiting properties - newproperty(:hop_limit, :required_features => :hop_limiting) do + newproperty(:hop_limit, required_features: :hop_limiting) do desc <<-EOS Hop limiting value for matched packets. EOS - newvalue(/^\d+$/) + newvalue(%r{^\d+$}) end # Rate limiting properties - newproperty(:limit, :required_features => :rate_limiting) do + newproperty(:limit, required_features: :rate_limiting) do desc <<-EOS Rate limiting value for matched packets. The format is: rate/[/second/|/minute|/hour|/day]. @@ -879,14 +866,14 @@ Puppet::Type.newtype(:firewall) do EOS end - newproperty(:burst, :required_features => :rate_limiting) do + newproperty(:burst, required_features: :rate_limiting) do desc <<-EOS Rate limiting burst value (per second) before limit checks apply. EOS - newvalue(/^\d+$/) + newvalue(%r{^\d+$}) end - newproperty(:uid, :required_features => :owner) do + newproperty(:uid, required_features: :owner) do desc <<-EOS UID or Username owner matching rule. Accepts a string argument only, as iptables does not accept multiple uid in a single @@ -900,41 +887,40 @@ Puppet::Type.newtype(:firewall) do # spaces as they are irrelevant with respect to rule sync. # Remove whitespace - is = is.gsub(/\s+/,'') - should = @should.first.to_s.gsub(/\s+/,'') + is = is.gsub(%r{\s+}, '') + should = @should.first.to_s.gsub(%r{\s+}, '') # Keep track of negation, but remove the '!' is_negate = '' should_negate = '' if is.start_with?('!') - is = is.gsub(/^!/,'') + is = is.gsub(%r{^!}, '') is_negate = '!' end if should.start_with?('!') - should = should.gsub(/^!/,'') + should = should.gsub(%r{^!}, '') should_negate = '!' end # If 'should' contains anything other than digits, # we assume that we have to do a lookup to convert # to UID - unless should[/[0-9]+/] == should + unless should[%r{[0-9]+}] == should should = Etc.getpwnam(should).uid end # If 'is' contains anything other than digits, # we assume that we have to do a lookup to convert # to UID - unless is[/[0-9]+/] == is + unless is[%r{[0-9]+}] == is is = Etc.getpwnam(is).uid end - return "#{is_negate}#{is}" == "#{should_negate}#{should}" + "#{is_negate}#{is}" == "#{should_negate}#{should}" end - end - newproperty(:gid, :required_features => :owner) do + newproperty(:gid, required_features: :owner) do desc <<-EOS GID or Group owner matching rule. Accepts a string argument only, as iptables does not accept multiple gid in a single @@ -948,41 +934,41 @@ Puppet::Type.newtype(:firewall) do # spaces as they are irrelevant with respect to rule sync. # Remove whitespace - is = is.gsub(/\s+/,'') - should = @should.first.to_s.gsub(/\s+/,'') + is = is.gsub(%r{\s+}, '') + should = @should.first.to_s.gsub(%r{\s+}, '') # Keep track of negation, but remove the '!' is_negate = '' should_negate = '' if is.start_with?('!') - is = is.gsub(/^!/,'') + is = is.gsub(%r{^!}, '') is_negate = '!' end if should.start_with?('!') - should = should.gsub(/^!/,'') + should = should.gsub(%r{^!}, '') should_negate = '!' end # If 'should' contains anything other than digits, # we assume that we have to do a lookup to convert # to UID - unless should[/[0-9]+/] == should + unless should[%r{[0-9]+}] == should should = Etc.getgrnam(should).gid end # If 'is' contains anything other than digits, # we assume that we have to do a lookup to convert # to UID - unless is[/[0-9]+/] == is + unless is[%r{[0-9]+}] == is is = Etc.getgrnam(is).gid end - return "#{is_negate}#{is}" == "#{should_negate}#{should}" + "#{is_negate}#{is}" == "#{should_negate}#{should}" end end # match mark - newproperty(:match_mark, :required_features => :mark) do + newproperty(:match_mark, required_features: :mark) do desc <<-EOS Match the Netfilter mark value associated with the packet. Accepts either of: mark/mask or mark. These will be converted to hex if they are not already. @@ -991,19 +977,19 @@ Puppet::Type.newtype(:firewall) do mark_regex = %r{\A((?:0x)?[0-9A-F]+)(/)?((?:0x)?[0-9A-F]+)?\z}i match = value.to_s.match(mark_regex) if match.nil? - raise ArgumentError, "Match MARK value must be integer or hex between 0 and 0xffffffff" + raise ArgumentError, 'Match MARK value must be integer or hex between 0 and 0xffffffff' end mark = @resource.to_hex32(match[1]) # Values that can't be converted to hex. # Or contain a trailing slash with no mask. - if mark.nil? or (mark and match[2] and match[3].nil?) - raise ArgumentError, "Match MARK value must be integer or hex between 0 and 0xffffffff" + if mark.nil? || (mark && match[2] && match[3].nil?) + raise ArgumentError, 'Match MARK value must be integer or hex between 0 and 0xffffffff' end # There should not be a mask on match_mark unless match[3].nil? - raise ArgumentError, "iptables does not support masks on MARK match rules" + raise ArgumentError, 'iptables does not support masks on MARK match rules' end value = mark @@ -1011,7 +997,7 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:set_mark, :required_features => :mark) do + newproperty(:set_mark, required_features: :mark) do desc <<-EOS Set the Netfilter mark value associated with the packet. Accepts either of: mark/mask or mark. These will be converted to hex if they are not already. @@ -1024,13 +1010,13 @@ Puppet::Type.newtype(:firewall) do # Values that can't be converted to hex. # Or contain a trailing slash with no mask. - if mark.nil? or (mark and match[2] and match[3].nil?) - raise ArgumentError, "MARK value must be integer or hex between 0 and 0xffffffff" + if mark.nil? || (mark && match[2] && match[3].nil?) + raise ArgumentError, 'MARK value must be integer or hex between 0 and 0xffffffff' end # Old iptables does not support a mask. New iptables will expect one. iptables_version = Facter.value('iptables_version') - mask_required = (iptables_version and Puppet::Util::Package.versioncmp(iptables_version, '1.4.1') >= 0) + mask_required = (iptables_version && Puppet::Util::Package.versioncmp(iptables_version, '1.4.1') >= 0) if mask_required if match[3].nil? @@ -1038,7 +1024,7 @@ Puppet::Type.newtype(:firewall) do else mask = @resource.to_hex32(match[3]) if mask.nil? - raise ArgumentError, "MARK mask must be integer or hex between 0 and 0xffffffff" + raise ArgumentError, 'MARK mask must be integer or hex between 0 and 0xffffffff' end value = "#{mark}/#{mask}" end @@ -1053,7 +1039,7 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:clamp_mss_to_pmtu, :required_features => :iptables) do + newproperty(:clamp_mss_to_pmtu, required_features: :iptables) do desc <<-EOS Sets the clamp mss to pmtu flag. EOS @@ -1061,21 +1047,21 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:set_dscp, :required_features => :iptables) do + newproperty(:set_dscp, required_features: :iptables) do desc <<-EOS Set DSCP Markings. EOS end - newproperty(:set_dscp_class, :required_features => :iptables) do + newproperty(:set_dscp_class, required_features: :iptables) do desc <<-EOS This sets the DSCP field according to a predefined DiffServ class. EOS # iptables uses the cisco DSCP classes as the basis for this flag. Values may be found here: # 'http://www.cisco.com/c/en/us/support/docs/quality-of-service-qos/qos-packet-marking/10103-dscpvalues.html' - valid_codes = [ - 'af11','af12','af13','af21','af22','af23','af31','af32','af33','af41', - 'af42','af43','cs1','cs2','cs3','cs4','cs5','cs6','cs7','ef' + valid_codes = %w[ + af11 af12 af13 af21 af22 af23 af31 af32 af33 af41 + af42 af43 cs1 cs2 cs3 cs4 cs5 cs6 cs7 ef ] munge do |value| unless valid_codes.include? value.downcase @@ -1085,13 +1071,13 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:set_mss, :required_features => :iptables) do + newproperty(:set_mss, required_features: :iptables) do desc <<-EOS Sets the TCP MSS value for packets. EOS end - newproperty(:pkttype, :required_features => :pkttype) do + newproperty(:pkttype, required_features: :pkttype) do desc <<-EOS Sets the packet type to match. EOS @@ -1099,7 +1085,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:unicast, :broadcast, :multicast) end - newproperty(:isfragment, :required_features => :isfragment) do + newproperty(:isfragment, required_features: :isfragment) do desc <<-EOS Set to true to match tcp fragments (requires type to be set to tcp) EOS @@ -1107,7 +1093,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:recent, :required_features => :recent_limiting) do + newproperty(:recent, required_features: :recent_limiting) do desc <<-EOS Enable the recent module. Takes as an argument one of set, update, rcheck or remove. For example: @@ -1137,11 +1123,11 @@ Puppet::Type.newtype(:firewall) do newvalues(:set, :update, :rcheck, :remove) munge do |value| - value = "--" + value + _value = '--' + value end end - newproperty(:rdest, :required_features => :recent_limiting) do + newproperty(:rdest, required_features: :recent_limiting) do desc <<-EOS Recent module; add the destination IP address to the list. Must be boolean true. @@ -1150,7 +1136,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:rsource, :required_features => :recent_limiting) do + newproperty(:rsource, required_features: :recent_limiting) do desc <<-EOS Recent module; add the source IP address to the list. Must be boolean true. @@ -1159,13 +1145,13 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:rname, :required_features => :recent_limiting) do + newproperty(:rname, required_features: :recent_limiting) do desc <<-EOS Recent module; The name of the list. Takes a string argument. EOS end - newproperty(:rseconds, :required_features => :recent_limiting) do + newproperty(:rseconds, required_features: :recent_limiting) do desc <<-EOS Recent module; used in conjunction with one of `recent => 'rcheck'` or `recent => 'update'`. When used, this will narrow the match to only @@ -1174,7 +1160,7 @@ Puppet::Type.newtype(:firewall) do EOS end - newproperty(:reap, :required_features => :recent_limiting) do + newproperty(:reap, required_features: :recent_limiting) do desc <<-EOS Recent module; can only be used in conjunction with the `rseconds` attribute. When used, this will cause entries older than 'seconds' to be @@ -1184,7 +1170,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:rhitcount, :required_features => :recent_limiting) do + newproperty(:rhitcount, required_features: :recent_limiting) do desc <<-EOS Recent module; used in conjunction with `recent => 'update'` or `recent => 'rcheck'. When used, this will narrow the match to only happen when @@ -1193,7 +1179,7 @@ Puppet::Type.newtype(:firewall) do EOS end - newproperty(:rttl, :required_features => :recent_limiting) do + newproperty(:rttl, required_features: :recent_limiting) do desc <<-EOS Recent module; may only be used in conjunction with one of `recent => 'rcheck'` or `recent => 'update'`. When used, this will narrow the match @@ -1207,7 +1193,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:socket, :required_features => :socket) do + newproperty(:socket, required_features: :socket) do desc <<-EOS If true, matches if an open socket can be found by doing a coket lookup on the packet. @@ -1216,7 +1202,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:ishasmorefrags, :required_features => :ishasmorefrags) do + newproperty(:ishasmorefrags, required_features: :ishasmorefrags) do desc <<-EOS If true, matches if the packet has it's 'more fragments' bit set. ipv6. EOS @@ -1224,7 +1210,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:islastfrag, :required_features => :islastfrag) do + newproperty(:islastfrag, required_features: :islastfrag) do desc <<-EOS If true, matches if the packet is the last fragment. ipv6. EOS @@ -1232,7 +1218,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:isfirstfrag, :required_features => :isfirstfrag) do + newproperty(:isfirstfrag, required_features: :isfirstfrag) do desc <<-EOS If true, matches if the packet is the first fragment. Sadly cannot be negated. ipv6. @@ -1241,7 +1227,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:ipsec_policy, :required_features => :ipsec_policy) do + newproperty(:ipsec_policy, required_features: :ipsec_policy) do desc <<-EOS Sets the ipsec policy type. May take a combination of arguments for any flags that can be passed to `--pol ipsec` such as: `--strict`, `--reqid 100`, `--next`, `--proto esp`, etc. EOS @@ -1249,7 +1235,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:none, :ipsec) end - newproperty(:ipsec_dir, :required_features => :ipsec_dir) do + newproperty(:ipsec_dir, required_features: :ipsec_dir) do desc <<-EOS Sets the ipsec policy direction EOS @@ -1271,7 +1257,7 @@ Puppet::Type.newtype(:firewall) do EOS validate do |value| - unless value =~ /^\d+$/ + unless value =~ %r{^\d+$} raise ArgumentError, <<-EOS stat_every value must be a digit EOS @@ -1290,7 +1276,7 @@ Puppet::Type.newtype(:firewall) do Set the initial counter value for the nth mode. Must be between 0 and the value of `stat_every`. Defaults to 0. Requires `stat_mode => 'nth'` EOS - newvalues(/^\d+$/) + newvalues(%r{^\d+$}) end newproperty(:stat_probability) do @@ -1299,13 +1285,13 @@ Puppet::Type.newtype(:firewall) do EOS validate do |value| - unless value =~ /^([01])\.(\d+)$/ + unless value =~ %r{^([01])\.(\d+)$} raise ArgumentError, <<-EOS stat_probability must be between 0.0 and 1.0 EOS end - if $1.to_i == 1 && $2.to_i != 0 + if Regexp.last_match(1).to_i == 1 && Regexp.last_match(2).to_i != 0 raise ArgumentError, <<-EOS start_probability must be between 0.0 and 1.0 EOS @@ -1313,20 +1299,20 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:mask, :required_features => :mask) do + newproperty(:mask, required_features: :mask) do desc <<-EOS Sets the mask to use when `recent` is enabled. EOS end - newproperty(:gateway, :required_features => :iptables) do + newproperty(:gateway, required_features: :iptables) do desc <<-EOS The TEE target will clone a packet and redirect this clone to another machine on the local network segment. gateway is the target host's IP. EOS end - newproperty(:ipset, :required_features => :ipset, :array_matching => :all) do + newproperty(:ipset, required_features: :ipset, array_matching: :all) do desc <<-EOS Matches against the specified ipset list. Requires ipset kernel module. Will accept a single element or an array. @@ -1335,7 +1321,7 @@ Puppet::Type.newtype(:firewall) do For example: 'blacklist src,dst' EOS - def is_to_s(value) + def to_s?(value) should_to_s(value) end @@ -1345,7 +1331,7 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:checksum_fill, :required_features => :iptables) do + newproperty(:checksum_fill, required_features: :iptables) do desc <<-EOS Compute and fill missing packet checksums. EOS @@ -1363,70 +1349,70 @@ Puppet::Type.newtype(:firewall) do desc <<-EOS MAC Source EOS - newvalues(/^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$/i) + newvalues(%r{^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$}i) end - newproperty(:physdev_in, :required_features => :iptables) do + newproperty(:physdev_in, required_features: :iptables) do desc <<-EOS Match if the packet is entering a bridge from the given interface. EOS - newvalues(/^[a-zA-Z0-9\-\._\+]+$/) + newvalues(%r{^[a-zA-Z0-9\-\._\+]+$}) end - newproperty(:physdev_out, :required_features => :iptables) do + newproperty(:physdev_out, required_features: :iptables) do desc <<-EOS Match if the packet is leaving a bridge via the given interface. EOS - newvalues(/^[a-zA-Z0-9\-\._\+]+$/) + newvalues(%r{^[a-zA-Z0-9\-\._\+]+$}) end - newproperty(:physdev_is_bridged, :required_features => :iptables) do + newproperty(:physdev_is_bridged, required_features: :iptables) do desc <<-EOS Match if the packet is transversing a bridge. EOS newvalues(:true, :false) end - newproperty(:physdev_is_in, :required_features => :iptables) do + newproperty(:physdev_is_in, required_features: :iptables) do desc <<-EOS Matches if the packet has entered through a bridge interface. EOS newvalues(:true, :false) end - newproperty(:physdev_is_out, :required_features => :iptables) do + newproperty(:physdev_is_out, required_features: :iptables) do desc <<-EOS Matches if the packet will leave through a bridge interface. EOS newvalues(:true, :false) end - newproperty(:date_start, :required_features => :iptables) do + newproperty(:date_start, required_features: :iptables) do desc <<-EOS Only match during the given time, which must be in ISO 8601 "T" notation. The possible time range is 1970-01-01T00:00:00 to 2038-01-19T04:17:07 EOS end - newproperty(:date_stop, :required_features => :iptables) do + newproperty(:date_stop, required_features: :iptables) do desc <<-EOS Only match during the given time, which must be in ISO 8601 "T" notation. The possible time range is 1970-01-01T00:00:00 to 2038-01-19T04:17:07 EOS end - newproperty(:time_start, :required_features => :iptables) do + newproperty(:time_start, required_features: :iptables) do desc <<-EOS Only match during the given daytime. The possible time range is 00:00:00 to 23:59:59. Leading zeroes are allowed (e.g. "06:03") and correctly interpreted as base-10. EOS munge do |value| - if value =~ /^([0-9]):/ + if value =~ %r{^([0-9]):} value = "0#{value}" end - if value =~ /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/ + if value =~ %r{^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$} value = "#{value}:00" end @@ -1434,18 +1420,18 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:time_stop, :required_features => :iptables) do + newproperty(:time_stop, required_features: :iptables) do desc <<-EOS Only match during the given daytime. The possible time range is 00:00:00 to 23:59:59. Leading zeroes are allowed (e.g. "06:03") and correctly interpreted as base-10. EOS munge do |value| - if value =~ /^([0-9]):/ + if value =~ %r{^([0-9]):} value = "0#{value}" end - if value =~ /^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$/ + if value =~ %r{^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$} value = "#{value}:00" end @@ -1453,7 +1439,7 @@ Puppet::Type.newtype(:firewall) do end end - newproperty(:month_days, :required_features => :iptables) do + newproperty(:month_days, required_features: :iptables) do desc <<-EOS Only match on the given days of the month. Possible values are 1 to 31. Note that specifying 31 will of course not match on months which do not have a 31st day; @@ -1462,16 +1448,16 @@ Puppet::Type.newtype(:firewall) do validate do |value| month = value.to_i - if month >= 1 and month <=31 + if month >= 1 && month <= 31 value else raise ArgumentError, - "month_days must be in the range of 1-31" + 'month_days must be in the range of 1-31' end end end - newproperty(:week_days, :required_features => :iptables) do + newproperty(:week_days, required_features: :iptables) do desc <<-EOS Only match on the given weekdays. Possible values are Mon, Tue, Wed, Thu, Fri, Sat, Sun. EOS @@ -1479,7 +1465,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:Mon, :Tue, :Wed, :Thu, :Fri, :Sat, :Sun) end - newproperty(:time_contiguous, :required_features => :iptables) do + newproperty(:time_contiguous, required_features: :iptables) do desc <<-EOS When time_stop is smaller than time_start value, match this as a single time period instead distinct intervals. EOS @@ -1487,7 +1473,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:kernel_timezone, :required_features => :iptables) do + newproperty(:kernel_timezone, required_features: :iptables) do desc <<-EOS Use the kernel timezone instead of UTC to determine whether a packet meets the time regulations. EOS @@ -1495,7 +1481,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:clusterip_new, :required_features => :clusterip) do + newproperty(:clusterip_new, required_features: :clusterip) do desc <<-EOS Used with the CLUSTERIP jump target. Create a new ClusterIP. You always have to set this on the first rule for a given ClusterIP. @@ -1504,7 +1490,7 @@ Puppet::Type.newtype(:firewall) do newvalues(:true, :false) end - newproperty(:clusterip_hashmode, :required_features => :clusterip) do + newproperty(:clusterip_hashmode, required_features: :clusterip) do desc <<-EOS Used with the CLUSTERIP jump target. Specify the hashing mode. Valid values: sourceip, sourceip-sourceport, sourceip-sourceport-destport. @@ -1513,81 +1499,81 @@ Puppet::Type.newtype(:firewall) do newvalues(:sourceip, :'sourceip-sourceport', :'sourceip-sourceport-destport') end - newproperty(:clusterip_clustermac, :required_features => :clusterip) do + newproperty(:clusterip_clustermac, required_features: :clusterip) do desc <<-EOS Used with the CLUSTERIP jump target. Specify the ClusterIP MAC address. Has to be a link-layer multicast address. EOS - newvalues(/^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$/i) + newvalues(%r{^([0-9a-f]{2}[:]){5}([0-9a-f]{2})$}i) end - newproperty(:clusterip_total_nodes, :required_features => :clusterip) do + newproperty(:clusterip_total_nodes, required_features: :clusterip) do desc <<-EOS Used with the CLUSTERIP jump target. Number of total nodes within this cluster. EOS - newvalues(/\d+/) + newvalues(%r{\d+}) end - newproperty(:clusterip_local_node, :required_features => :clusterip) do + newproperty(:clusterip_local_node, required_features: :clusterip) do desc <<-EOS Used with the CLUSTERIP jump target. Specify the random seed used for hash initialization. EOS - newvalues(/\d+/) + newvalues(%r{\d+}) end - newproperty(:clusterip_hash_init, :required_features => :clusterip) do + newproperty(:clusterip_hash_init, required_features: :clusterip) do desc <<-EOS Used with the CLUSTERIP jump target. Specify the random seed used for hash initialization. EOS end - newproperty(:length, :required_features => :length) do + newproperty(:length, required_features: :length) do desc <<-EOS Sets the length of layer-3 payload to match. EOS munge do |value| - match = value.to_s.match("^([0-9]+)(-)?([0-9]+)?$") + match = value.to_s.match('^([0-9]+)(-)?([0-9]+)?$') if match.nil? - raise ArgumentError, "Length value must either be an integer or a range" + raise ArgumentError, 'Length value must either be an integer or a range' end low = match[1].to_i - if !match[3].nil? + unless match[3].nil? high = match[3].to_i end - if (low < 0 or low > 65535) or \ - (!high.nil? and (high < 0 or high > 65535 or high < low)) - raise ArgumentError, "Length values must be between 0 and 65535" + if (low < 0 || low > 65_535) || \ + (!high.nil? && (high < 0 || high > 65_535 || high < low)) + raise ArgumentError, 'Length values must be between 0 and 65535' end value = low.to_s - if !high.nil? - value << ":" << high.to_s + unless high.nil? + value << ':' << high.to_s end value end end - newproperty(:string, :required_features => :string_matching) do + newproperty(:string, required_features: :string_matching) do desc <<-EOS String matching feature. Matches the packet against the pattern given as an argument. EOS munge do |value| - value = "'" + value + "'" + _value = "'" + value + "'" end end - newproperty(:string_algo, :required_features => :string_matching) do + newproperty(:string_algo, required_features: :string_matching) do desc <<-EOS String matching feature, pattern matching strategy. EOS @@ -1595,37 +1581,37 @@ Puppet::Type.newtype(:firewall) do newvalues(:bm, :kmp) end - newproperty(:string_from, :required_features => :string_matching) do + newproperty(:string_from, required_features: :string_matching) do desc <<-EOS String matching feature, offset from which we start looking for any matching. EOS end - newproperty(:string_to, :required_features => :string_matching) do + newproperty(:string_to, required_features: :string_matching) do desc <<-EOS String matching feature, offset up to which we should scan. EOS end - newproperty(:queue_num, :required_features => :queue_num) do + newproperty(:queue_num, required_features: :queue_num) do desc <<-EOS Used with NFQUEUE jump target. What queue number to send packets to EOS munge do |value| - match = value.to_s.match("^([0-9])*$") + match = value.to_s.match('^([0-9])*$') if match.nil? - raise ArgumentError, "queue_num must be an integer" + raise ArgumentError, 'queue_num must be an integer' end - if match[1].to_i > 65535 || match[1].to_i < 0 - raise ArgumentError, "queue_num must be between 0 and 65535" + if match[1].to_i > 65_535 || match[1].to_i < 0 + raise ArgumentError, 'queue_num must be between 0 and 65535' end value end end - newproperty(:queue_bypass, :required_features => :queue_bypass) do + newproperty(:queue_bypass, required_features: :queue_bypass) do desc <<-EOS Used with NFQUEUE jump target Allow packets to bypass :queue_num if userspace process is not listening @@ -1637,14 +1623,14 @@ Puppet::Type.newtype(:firewall) do desc <<-EOS src attribute for the module geoip EOS - newvalues(/^[A-Z]{2}(,[A-Z]{2})*$/) + newvalues(%r{^[A-Z]{2}(,[A-Z]{2})*$}) end newproperty(:dst_cc) do desc <<-EOS dst attribute for the module geoip EOS - newvalues(/^[A-Z]{2}(,[A-Z]{2})*$/) + newvalues(%r{^[A-Z]{2}(,[A-Z]{2})*$}) end newproperty(:hashlimit_name) do @@ -1674,7 +1660,7 @@ Puppet::Type.newtype(:firewall) do desc <<-EOS Maximum initial number of packets to match: this number gets recharged by one every time the limit specified above is not reached, up to this number; the default is 5. When byte-based rate matching is requested, this option specifies the amount of bytes that can exceed the given rate. This option should be used with caution -- if the entry expires, the burst value is reset too. EOS - newvalue(/^\d+$/) + newvalue(%r{^\d+$}) end newproperty(:hashlimit_mode) do @@ -1726,15 +1712,15 @@ Puppet::Type.newtype(:firewall) do case value(:provider) when :iptables - protocol = "IPv4" + protocol = 'IPv4' when :ip6tables - protocol = "IPv6" + protocol = 'IPv6' end unless protocol.nil? table = value(:table) [value(:chain), value(:jump)].each do |chain| - reqs << "#{chain}:#{table}:#{protocol}" unless ( chain.nil? || (['INPUT', 'OUTPUT', 'FORWARD'].include?(chain) && table == :filter) ) + reqs << "#{chain}:#{table}:#{protocol}" unless chain.nil? || (%w[INPUT OUTPUT FORWARD].include?(chain) && table == :filter) end end @@ -1746,7 +1732,7 @@ Puppet::Type.newtype(:firewall) do autorequire(:package) do case value(:provider) when :iptables, :ip6tables - %w{iptables iptables-persistent iptables-services} + %w[iptables iptables-persistent iptables-services] else [] end @@ -1755,7 +1741,7 @@ Puppet::Type.newtype(:firewall) do autorequire(:service) do case value(:provider) when :iptables, :ip6tables - %w{firewalld iptables ip6tables iptables-persistent netfilter-persistent} + %w[firewalld iptables ip6tables iptables-persistent netfilter-persistent] else [] end @@ -1765,169 +1751,169 @@ Puppet::Type.newtype(:firewall) do if Puppet::Util::Package.versioncmp(Puppet.version, '4.0') >= 0 # On RHEL 7 this needs to be threaded correctly to manage SE Linux permissions after persisting the rules autobefore(:file) do - [ '/etc/sysconfig/iptables', '/etc/sysconfig/ip6tables' ] + ['/etc/sysconfig/iptables', '/etc/sysconfig/ip6tables'] end end validate do - debug("[validate]") + debug('[validate]') # TODO: this is put here to skip validation if ensure is not set. This # is because there is a revalidation stage called later where the values # are not set correctly. I tried tracing it - but have put in this # workaround instead to skip. Must get to the bottom of this. - if ! value(:ensure) + unless value(:ensure) return end # First we make sure the chains and tables are valid combinations - if value(:table).to_s == "filter" && - value(:chain) =~ /PREROUTING|POSTROUTING/ + if value(:table).to_s == 'filter' && + value(:chain) =~ %r{PREROUTING|POSTROUTING} - self.fail "PREROUTING and POSTROUTING cannot be used in table 'filter'" + raise "PREROUTING and POSTROUTING cannot be used in table 'filter'" end - if value(:table).to_s == "nat" && value(:chain) =~ /INPUT|FORWARD/ - self.fail "INPUT and FORWARD cannot be used in table 'nat'" + if value(:table).to_s == 'nat' && value(:chain) =~ %r{INPUT|FORWARD} + raise "INPUT and FORWARD cannot be used in table 'nat'" end - if value(:table).to_s == "raw" && - value(:chain) =~ /INPUT|FORWARD|POSTROUTING/ + if value(:table).to_s == 'raw' && + value(:chain) =~ %r{INPUT|FORWARD|POSTROUTING} - self.fail "INPUT, FORWARD and POSTROUTING cannot be used in table raw" + raise 'INPUT, FORWARD and POSTROUTING cannot be used in table raw' end # Now we analyse the individual properties to make sure they apply to # the correct combinations. if value(:uid) - unless value(:chain).to_s =~ /OUTPUT|POSTROUTING/ - self.fail "Parameter uid only applies to chains " \ - "OUTPUT,POSTROUTING" + unless value(:chain).to_s =~ %r{OUTPUT|POSTROUTING} + raise 'Parameter uid only applies to chains ' \ + 'OUTPUT,POSTROUTING' end end if value(:gid) - unless value(:chain).to_s =~ /OUTPUT|POSTROUTING/ - self.fail "Parameter gid only applies to chains " \ - "OUTPUT,POSTROUTING" + unless value(:chain).to_s =~ %r{OUTPUT|POSTROUTING} + raise 'Parameter gid only applies to chains ' \ + 'OUTPUT,POSTROUTING' end end if value(:set_mark) - unless value(:jump).to_s =~ /MARK/ && - value(:table).to_s =~ /mangle/ - self.fail "Parameter set_mark only applies to " \ - "the mangle table and when jump => MARK" + unless value(:jump).to_s =~ %r{MARK} && + value(:table).to_s =~ %r{mangle} + raise 'Parameter set_mark only applies to ' \ + 'the mangle table and when jump => MARK' end end if value(:dport) - unless value(:proto).to_s =~ /tcp|udp|sctp/ - self.fail "[%s] Parameter dport only applies to sctp, tcp and udp " \ - "protocols. Current protocol is [%s] and dport is [%s]" % - [value(:name), should(:proto), should(:dport)] + unless value(:proto).to_s =~ %r{tcp|udp|sctp} + raise '[%s] Parameter dport only applies to sctp, tcp and udp ' \ + 'protocols. Current protocol is [%s] and dport is [%s]' % + [value(:name), should(:proto), should(:dport)] end end - if value(:jump).to_s == "DSCP" + if value(:jump).to_s == 'DSCP' unless value(:set_dscp) || value(:set_dscp_class) - self.fail "When using jump => DSCP, the set_dscp or set_dscp_class property is required" + raise 'When using jump => DSCP, the set_dscp or set_dscp_class property is required' end end - if value(:jump).to_s == "TCPMSS" + if value(:jump).to_s == 'TCPMSS' unless value(:set_mss) || value(:clamp_mss_to_pmtu) - self.fail "When using jump => TCPMSS, the set_mss or clamp_mss_to_pmtu property is required" + raise 'When using jump => TCPMSS, the set_mss or clamp_mss_to_pmtu property is required' end end - if value(:jump).to_s == "TEE" + if value(:jump).to_s == 'TEE' unless value(:gateway) - self.fail "When using jump => TEE, the gateway property is required" + raise 'When using jump => TEE, the gateway property is required' end end - if value(:jump).to_s == "DNAT" - unless value(:table).to_s =~ /nat/ - self.fail "Parameter jump => DNAT only applies to table => nat" + if value(:jump).to_s == 'DNAT' + unless value(:table).to_s =~ %r{nat} + raise 'Parameter jump => DNAT only applies to table => nat' end unless value(:todest) - self.fail "Parameter jump => DNAT must have todest parameter" + raise 'Parameter jump => DNAT must have todest parameter' end end - if value(:jump).to_s == "SNAT" - unless value(:table).to_s =~ /nat/ - self.fail "Parameter jump => SNAT only applies to table => nat" + if value(:jump).to_s == 'SNAT' + unless value(:table).to_s =~ %r{nat} + raise 'Parameter jump => SNAT only applies to table => nat' end unless value(:tosource) - self.fail "Parameter jump => SNAT must have tosource parameter" + raise 'Parameter jump => SNAT must have tosource parameter' end end - if value(:jump).to_s == "MASQUERADE" - unless value(:table).to_s =~ /nat/ - self.fail "Parameter jump => MASQUERADE only applies to table => nat" + if value(:jump).to_s == 'MASQUERADE' + unless value(:table).to_s =~ %r{nat} + raise 'Parameter jump => MASQUERADE only applies to table => nat' end end if value(:log_prefix) || value(:log_level) || value(:log_uid) - unless value(:jump).to_s == "LOG" - self.fail "Parameter log_prefix, log_level and log_uid require jump => LOG" + unless value(:jump).to_s == 'LOG' + raise 'Parameter log_prefix, log_level and log_uid require jump => LOG' end end - if value(:burst) && ! value(:limit) - self.fail "burst makes no sense without limit" + if value(:burst) && !value(:limit) + raise 'burst makes no sense without limit' end if value(:action) && value(:jump) - self.fail "Only one of the parameters 'action' and 'jump' can be set" + raise "Only one of the parameters 'action' and 'jump' can be set" end - if value(:connlimit_mask) && ! value(:connlimit_above) - self.fail "Parameter 'connlimit_mask' requires 'connlimit_above'" + if value(:connlimit_mask) && !value(:connlimit_above) + raise "Parameter 'connlimit_mask' requires 'connlimit_above'" end - if value(:mask) && ! value(:recent) - self.fail "Mask can only be set if recent is enabled." + if value(:mask) && !value(:recent) + raise 'Mask can only be set if recent is enabled.' end [:stat_packet, :stat_every, :stat_probability].each do |param| - if value(param) && ! value(:stat_mode) - self.fail "Parameter '#{param.to_s}' requires 'stat_mode' to be set" + if value(param) && !value(:stat_mode) + raise "Parameter '#{param}' requires 'stat_mode' to be set" end end if value(:stat_packet) && value(:stat_mode) != :nth - self.fail "Parameter 'stat_packet' requires 'stat_mode' to be set to 'nth'" + raise "Parameter 'stat_packet' requires 'stat_mode' to be set to 'nth'" end if value(:stat_every) && value(:stat_mode) != :nth - self.fail "Parameter 'stat_every' requires 'stat_mode' to be set to 'nth'" + raise "Parameter 'stat_every' requires 'stat_mode' to be set to 'nth'" end if value(:stat_probability) && value(:stat_mode) != :random - self.fail "Parameter 'stat_probability' requires 'stat_mode' to be set to 'random'" + raise "Parameter 'stat_probability' requires 'stat_mode' to be set to 'random'" end if value(:checksum_fill) - unless value(:jump).to_s == "CHECKSUM" && value(:table).to_s == "mangle" - self.fail "Parameter checksum_fill requires jump => CHECKSUM and table => mangle" + unless value(:jump).to_s == 'CHECKSUM' && value(:table).to_s == 'mangle' + raise 'Parameter checksum_fill requires jump => CHECKSUM and table => mangle' end end if value(:queue_num) || value(:queue_bypass) - unless value(:jump).to_s == "NFQUEUE" - self.fail "Paramter queue_number and queue_bypass require jump => NFQUEUE" + unless value(:jump).to_s == 'NFQUEUE' + raise 'Paramter queue_number and queue_bypass require jump => NFQUEUE' end end if value(:hashlimit_name) unless value(:hashlimit_upto) || value(:hashlimit_above) - self.fail "Either hashlimit_upto or hashlimit_above are required" + raise 'Either hashlimit_upto or hashlimit_above are required' end end end diff --git a/lib/puppet/type/firewallchain.rb b/lib/puppet/type/firewallchain.rb index 46cf586..13c44c1 100644 --- a/lib/puppet/type/firewallchain.rb +++ b/lib/puppet/type/firewallchain.rb @@ -4,7 +4,7 @@ # In this case I'm trying the relative path first, then falling back to normal # mechanisms. This should be fixed in future versions of puppet but it looks # like we'll need to maintain this for some time perhaps. -$LOAD_PATH.unshift(File.join(File.dirname(__FILE__),"..","..")) +$LOAD_PATH.unshift(File.join(File.dirname(__FILE__), '..', '..')) require 'puppet/util/firewall' Puppet::Type.newtype(:firewallchain) do @@ -23,8 +23,8 @@ Puppet::Type.newtype(:firewallchain) do those packages to ensure that any required binaries are installed. EOS - feature :iptables_chain, "The provider provides iptables chain features." - feature :policy, "Default policy (inbuilt chains only)" + feature :iptables_chain, 'The provider provides iptables chain features.' + feature :policy, 'Default policy (inbuilt chains only)' ensurable do defaultvalues @@ -40,46 +40,49 @@ Puppet::Type.newtype(:firewallchain) do isnamevar validate do |value| - if value !~ Nameformat then - raise ArgumentError, "Inbuilt chains must be in the form {chain}:{table}:{protocol} where {table} is one of FILTER, NAT, MANGLE, RAW, RAWPOST, BROUTE, SECURITY or empty (alias for filter), chain can be anything without colons or one of PREROUTING, POSTROUTING, BROUTING, INPUT, FORWARD, OUTPUT for the inbuilt chains, and {protocol} being IPv4, IPv6, ethernet (ethernet bridging) got '#{value}' table:'#{$1}' chain:'#{$2}' protocol:'#{$3}'" + if value !~ NAME_FORMAT + raise ArgumentError, 'Inbuilt chains must be in the form {chain}:{table}:{protocol} where {table} is one of FILTER,' \ + ' NAT, MANGLE, RAW, RAWPOST, BROUTE, SECURITY or empty (alias for filter), chain can be anything without colons' \ + ' or one of PREROUTING, POSTROUTING, BROUTING, INPUT, FORWARD, OUTPUT for the inbuilt chains, and {protocol} being' \ + " IPv4, IPv6, ethernet (ethernet bridging) got '#{value}' table:'#{Regexp.last_match(1)}' chain:'#{Regexp.last_match(2)}' protocol:'#{Regexp.last_match(3)}'" else - chain = $1 - table = $2 - protocol = $3 + chain = Regexp.last_match(1) + table = Regexp.last_match(2) + protocol = Regexp.last_match(3) case table when 'filter' - if chain =~ /^(PREROUTING|POSTROUTING|BROUTING)$/ + if chain =~ %r{^(PREROUTING|POSTROUTING|BROUTING)$} raise ArgumentError, "INPUT, OUTPUT and FORWARD are the only inbuilt chains that can be used in table 'filter'" end when 'mangle' - if chain =~ InternalChains && chain == 'BROUTING' + if chain =~ INTERNAL_CHAINS && chain == 'BROUTING' raise ArgumentError, "PREROUTING, POSTROUTING, INPUT, FORWARD and OUTPUT are the only inbuilt chains that can be used in table 'mangle'" end when 'nat' - if chain =~ /^(BROUTING|FORWARD)$/ + if chain =~ %r{^(BROUTING|FORWARD)$} raise ArgumentError, "PREROUTING, POSTROUTING, INPUT, and OUTPUT are the only inbuilt chains that can be used in table 'nat'" end - if Gem::Version.new(Facter['kernelmajversion'].value.dup) < Gem::Version.new('3.7') and protocol =~/^(IP(v6)?)?$/ + if Gem::Version.new(Facter['kernelmajversion'].value.dup) < Gem::Version.new('3.7') && protocol =~ %r{^(IP(v6)?)?$} raise ArgumentError, "table nat isn't valid in IPv6. You must specify ':IPv4' as the name suffix" end when 'raw' - if chain =~ /^(POSTROUTING|BROUTING|INPUT|FORWARD)$/ - raise ArgumentError,'PREROUTING and OUTPUT are the only inbuilt chains in the table \'raw\'' + if chain =~ %r{^(POSTROUTING|BROUTING|INPUT|FORWARD)$} + raise ArgumentError, 'PREROUTING and OUTPUT are the only inbuilt chains in the table \'raw\'' end when 'broute' if protocol != 'ethernet' - raise ArgumentError,'BROUTE is only valid with protocol \'ethernet\'' + raise ArgumentError, 'BROUTE is only valid with protocol \'ethernet\'' end - if chain =~ /^PREROUTING|POSTROUTING|INPUT|FORWARD|OUTPUT$/ - raise ArgumentError,'BROUTING is the only inbuilt chain allowed on on table \'broute\'' + if chain =~ %r{^PREROUTING|POSTROUTING|INPUT|FORWARD|OUTPUT$} + raise ArgumentError, 'BROUTING is the only inbuilt chain allowed on on table \'broute\'' end when 'security' - if chain =~ /^(PREROUTING|POSTROUTING|BROUTING)$/ + if chain =~ %r{^(PREROUTING|POSTROUTING|BROUTING)$} raise ArgumentError, "INPUT, OUTPUT and FORWARD are the only inbuilt chains that can be used in table 'security'" end end - if chain == 'BROUTING' && ( protocol != 'ethernet' || table!='broute') - raise ArgumentError,'BROUTING is the only inbuilt chain allowed on on table \'BROUTE\' with protocol \'ethernet\' i.e. \'broute:BROUTING:enternet\'' + if chain == 'BROUTING' && (protocol != 'ethernet' || table != 'broute') + raise ArgumentError, 'BROUTING is the only inbuilt chain allowed on on table \'BROUTE\' with protocol \'ethernet\' i.e. \'broute:BROUTING:enternet\'' end end end @@ -101,7 +104,7 @@ Puppet::Type.newtype(:firewallchain) do defaultto do # ethernet chain have an ACCEPT default while other haven't got an # allowed value - if @resource[:name] =~ /:ethernet$/ + if @resource[:name] =~ %r{:ethernet$} :accept else nil @@ -109,7 +112,7 @@ Puppet::Type.newtype(:firewallchain) do end end - newparam(:purge, :boolean => true) do + newparam(:purge, boolean: true) do desc <<-EOS Purge unmanaged firewall rules in this chain EOS @@ -140,13 +143,13 @@ Puppet::Type.newtype(:firewallchain) do EOS validate do |value| - unless value.is_a?(Array) or value.is_a?(String) or value == false - self.devfail "Ignore must be a string or an Array" + unless value.is_a?(Array) || value.is_a?(String) || value == false + devfail 'Ignore must be a string or an Array' end end munge do |patterns| # convert into an array of {Regex}es patterns = [patterns] if patterns.is_a?(String) - patterns.map{|p| Regexp.new(p)} + patterns.map { |p| Regexp.new(p) } end end @@ -155,7 +158,7 @@ Puppet::Type.newtype(:firewallchain) do autorequire(:package) do case value(:provider) when :iptables_chain - %w{iptables iptables-persistent iptables-services} + %w[iptables iptables-persistent iptables-services] else [] end @@ -164,52 +167,52 @@ Puppet::Type.newtype(:firewallchain) do autorequire(:service) do case value(:provider) when :iptables, :ip6tables - %w{firewalld iptables ip6tables iptables-persistent netfilter-persistent} + %w[firewalld iptables ip6tables iptables-persistent netfilter-persistent] else [] end end validate do - debug("[validate]") + debug('[validate]') - value(:name).match(Nameformat) - chain = $1 - table = $2 - protocol = $3 + value(:name).match(NAME_FORMAT) + chain = Regexp.last_match(1) + table = Regexp.last_match(2) + protocol = Regexp.last_match(3) # Check that we're not removing an internal chain - if chain =~ InternalChains && value(:ensure) == :absent - self.fail "Cannot remove in-built chains" + if chain =~ INTERNAL_CHAINS && value(:ensure) == :absent + raise 'Cannot remove in-built chains' end if value(:policy).nil? && protocol == 'ethernet' - self.fail "you must set a non-empty policy on all ethernet table chains" + raise 'you must set a non-empty policy on all ethernet table chains' end # Check that we're not setting a policy on a user chain - if chain !~ InternalChains && - !value(:policy).nil? && - protocol != 'ethernet' + if chain !~ INTERNAL_CHAINS && + !value(:policy).nil? && + protocol != 'ethernet' - self.fail "policy can only be set on in-built chains (with the exception of ethernet chains) (table:#{table} chain:#{chain} protocol:#{protocol})" + raise "policy can only be set on in-built chains (with the exception of ethernet chains) (table:#{table} chain:#{chain} protocol:#{protocol})" end # no DROP policy on nat table if table == 'nat' && - value(:policy) == :drop + value(:policy) == :drop - self.fail 'The "nat" table is not intended for filtering, the use of DROP is therefore inhibited' + raise 'The "nat" table is not intended for filtering, the use of DROP is therefore inhibited' end end def generate - return [] unless self.purge? + return [] unless purge? - value(:name).match(Nameformat) - chain = $1 - table = $2 - protocol = $3 + value(:name).match(NAME_FORMAT) + chain = Regexp.last_match(1) + table = Regexp.last_match(2) + protocol = Regexp.last_match(3) provider = case protocol when 'IPv4' @@ -222,13 +225,13 @@ Puppet::Type.newtype(:firewallchain) do rules_resources = Puppet::Type.type(:firewall).instances # Keep only rules in this chain - rules_resources.delete_if { |res| (res[:provider] != provider or res.provider.properties[:table].to_s != table or res.provider.properties[:chain] != chain) } + rules_resources.delete_if { |res| (res[:provider] != provider || res.provider.properties[:table].to_s != table || res.provider.properties[:chain] != chain) } # Remove rules which match our ignore filter - rules_resources.delete_if {|res| value(:ignore).find_index{|f| res.provider.properties[:line].match(f)}} if value(:ignore) + rules_resources.delete_if { |res| value(:ignore).find_index { |f| res.provider.properties[:line].match(f) } } if value(:ignore) # We mark all remaining rules for deletion, and then let the catalog override us on rules which should be present - rules_resources.each {|res| res[:ensure] = :absent} + rules_resources.each { |res| res[:ensure] = :absent } rules_resources end diff --git a/lib/puppet/util/firewall.rb b/lib/puppet/util/firewall.rb index 5f34059..0dc129f 100644 --- a/lib/puppet/util/firewall.rb +++ b/lib/puppet/util/firewall.rb @@ -6,39 +6,39 @@ require 'puppet/util/ipcidr' module Puppet::Util::Firewall # Translate the symbolic names for icmp packet types to integers def icmp_name_to_number(value_icmp, protocol) - if value_icmp =~ /\d{1,2}$/ + if value_icmp =~ %r{\d{1,2}$} value_icmp elsif protocol == 'inet' case value_icmp - when "echo-reply" then "0" - when "destination-unreachable" then "3" - when "source-quench" then "4" - when "redirect" then "6" - when "echo-request" then "8" - when "router-advertisement" then "9" - when "router-solicitation" then "10" - when "time-exceeded" then "11" - when "parameter-problem" then "12" - when "timestamp-request" then "13" - when "timestamp-reply" then "14" - when "address-mask-request" then "17" - when "address-mask-reply" then "18" - else nil + when 'echo-reply' then '0' + when 'destination-unreachable' then '3' + when 'source-quench' then '4' + when 'redirect' then '6' + when 'echo-request' then '8' + when 'router-advertisement' then '9' + when 'router-solicitation' then '10' + when 'time-exceeded' then '11' + when 'parameter-problem' then '12' + when 'timestamp-request' then '13' + when 'timestamp-reply' then '14' + when 'address-mask-request' then '17' + when 'address-mask-reply' then '18' + else nil end elsif protocol == 'inet6' case value_icmp - when "destination-unreachable" then "1" - when "too-big" then "2" - when "time-exceeded" then "3" - when "parameter-problem" then "4" - when "echo-request" then "128" - when "echo-reply" then "129" - when "router-solicitation" then "133" - when "router-advertisement" then "134" - when "neighbour-solicitation" then "135" - when "neighbour-advertisement" then "136" - when "redirect" then "137" - else nil + when 'destination-unreachable' then '1' + when 'too-big' then '2' + when 'time-exceeded' then '3' + when 'parameter-problem' then '4' + when 'echo-request' then '128' + when 'echo-reply' then '129' + when 'router-solicitation' then '133' + when 'router-advertisement' then '134' + when 'neighbour-solicitation' then '135' + when 'neighbour-advertisement' then '136' + when 'redirect' then '137' + else nil end else raise ArgumentError, "unsupported protocol family '#{protocol}'" @@ -47,23 +47,23 @@ module Puppet::Util::Firewall # Convert log_level names to their respective numbers def log_level_name_to_number(value) - #TODO make this 0-7 only - if value =~ /\d/ + # TODO: make this 0-7 only + if value =~ %r{\d} value else case value - when "panic" then "0" - when "alert" then "1" - when "crit" then "2" - when "err" then "3" - when "error" then "3" - when "warn" then "4" - when "warning" then "4" - when "not" then "5" - when "notice" then "5" - when "info" then "6" - when "debug" then "7" - else nil + when 'panic' then '0' + when 'alert' then '1' + when 'crit' then '2' + when 'err' then '3' + when 'error' then '3' + when 'warn' then '4' + when 'warning' then '4' + when 'not' then '5' + when 'notice' then '5' + when 'info' then '6' + when 'debug' then '7' + else nil end end end @@ -76,16 +76,13 @@ module Puppet::Util::Firewall # nothing. def string_to_port(value, proto) proto = proto.to_s - unless proto =~ /^(tcp|udp)$/ + unless proto =~ %r{^(tcp|udp)$} proto = 'tcp' end - m = value.to_s.match(/^(!\s+)?(\S+)/) - if m[2].match(/^\d+(-\d+)?$/) - return "#{m[1]}#{m[2]}" - else - return "#{m[1]}#{Socket.getservbyname(m[2], proto).to_s}" - end + m = value.to_s.match(%r{^(!\s+)?(\S+)}) + return "#{m[1]}#{m[2]}" if m[2] =~ %r{^\d+(-\d+)?$} + "#{m[1]}#{Socket.getservbyname(m[2], proto)}" end # Takes an address and protocol and returns the address in CIDR notation. @@ -117,7 +114,7 @@ module Puppet::Util::Firewall when :IPv6 Socket::AF_INET6 when nil - raise ArgumentError, "Proto must be specified for a hostname" + raise ArgumentError, 'Proto must be specified for a hostname' else raise ArgumentError, "Unsupported address family: #{proto}" end @@ -127,15 +124,15 @@ module Puppet::Util::Firewall begin new_value = Puppet::Util::IPCidr.new(addr, family) break - rescue + rescue # rubocop:disable Lint/HandleExceptions end end - raise "Failed to resolve hostname #{value}" unless new_value != nil + raise "Failed to resolve hostname #{value}" if new_value.nil? value = new_value end - return nil if value.prefixlen == 0 + return nil if value.prefixlen.zero? value.cidr end @@ -146,41 +143,41 @@ module Puppet::Util::Firewall # defined in host_to_ip for the host/address part. # def host_to_mask(value, proto) - match = value.match /(!)\s?(.*)$/ + match = value.match %r{(!)\s?(.*)$} return host_to_ip(value, proto) unless match cidr = host_to_ip(match[2], proto) - return nil if cidr == nil + return nil if cidr.nil? "#{match[1]} #{cidr}" end # Validates the argument is int or hex, and returns valid hex # conversion of the value or nil otherwise. def to_hex32(value) - begin - value = Integer(value) - if value.between?(0, 0xffffffff) - return '0x' + value.to_s(16) - end - rescue ArgumentError - # pass + begin + value = Integer(value) + if value.between?(0, 0xffffffff) + return '0x' + value.to_s(16) end - return nil + rescue ArgumentError # rubocop:disable Lint/HandleExceptions + # pass + end + nil end def persist_iptables(proto) - debug("[persist_iptables]") + debug('[persist_iptables]') # Basic normalisation for older Facter os_key = Facter.value(:osfamily) os_key ||= case Facter.value(:operatingsystem) - when 'RedHat', 'CentOS', 'Fedora', 'Scientific', 'SL', 'SLC', 'Ascendos', 'CloudLinux', 'PSBM', 'OracleLinux', 'OVS', 'OEL', 'Amazon', 'XenServer', 'VirtuozzoLinux' - 'RedHat' - when 'Debian', 'Ubuntu' - 'Debian' - else - Facter.value(:operatingsystem) - end + when 'RedHat', 'CentOS', 'Fedora', 'Scientific', 'SL', 'SLC', 'Ascendos', 'CloudLinux', 'PSBM', 'OracleLinux', 'OVS', 'OEL', 'Amazon', 'XenServer', 'VirtuozzoLinux' + 'RedHat' + when 'Debian', 'Ubuntu' + 'Debian' + else + Facter.value(:operatingsystem) + end # Older iptables-persistent doesn't provide save action. if os_key == 'Debian' @@ -188,7 +185,7 @@ module Puppet::Util::Firewall # that the iptables-persistent package was potentially installed after the initial Fact gathering. Facter.fact(:iptables_persistent_version).flush persist_ver = Facter.value(:iptables_persistent_version) - if (persist_ver and Puppet::Util::Package.versioncmp(persist_ver, '0.5.0') < 0) + if persist_ver && Puppet::Util::Package.versioncmp(persist_ver, '0.5.0') < 0 os_key = 'Debian_manual' end end @@ -199,47 +196,48 @@ module Puppet::Util::Firewall end # RHEL 7 and newer also use systemd to persist iptable rules - if os_key == 'RedHat' && ['RedHat','CentOS','Scientific','SL','SLC','Ascendos','CloudLinux','PSBM','OracleLinux','OVS','OEL','XenServer','VirtuozzoLinux'].include?(Facter.value(:operatingsystem)) && Facter.value(:operatingsystemrelease).to_i >= 7 + if os_key == 'RedHat' && %w[RedHat CentOS Scientific SL SLC Ascendos CloudLinux PSBM OracleLinux OVS OEL XenServer VirtuozzoLinux] + .include?(Facter.value(:operatingsystem)) && Facter.value(:operatingsystemrelease).to_i >= 7 os_key = 'Fedora' end cmd = case os_key.to_sym - when :RedHat - case proto.to_sym - when :IPv4 - %w{/sbin/service iptables save} - when :IPv6 - %w{/sbin/service ip6tables save} - end - when :Fedora - case proto.to_sym - when :IPv4 - %w{/usr/libexec/iptables/iptables.init save} - when :IPv6 - %w{/usr/libexec/iptables/ip6tables.init save} - end - when :Debian - case proto.to_sym - when :IPv4, :IPv6 - if (persist_ver and Puppet::Util::Package.versioncmp(persist_ver, '1.0') > 0) - %w{/usr/sbin/service netfilter-persistent save} - else - %w{/usr/sbin/service iptables-persistent save} - end - end - when :Debian_manual - case proto.to_sym - when :IPv4 - ["/bin/sh", "-c", "/sbin/iptables-save > /etc/iptables/rules"] - end - when :Archlinux - case proto.to_sym - when :IPv4 - ["/bin/sh", "-c", "/usr/sbin/iptables-save > /etc/iptables/iptables.rules"] - when :IPv6 - ["/bin/sh", "-c", "/usr/sbin/ip6tables-save > /etc/iptables/ip6tables.rules"] - end - end + when :RedHat + case proto.to_sym + when :IPv4 + %w[/sbin/service iptables save] + when :IPv6 + %w[/sbin/service ip6tables save] + end + when :Fedora + case proto.to_sym + when :IPv4 + %w[/usr/libexec/iptables/iptables.init save] + when :IPv6 + %w[/usr/libexec/iptables/ip6tables.init save] + end + when :Debian + case proto.to_sym + when :IPv4, :IPv6 + if persist_ver && Puppet::Util::Package.versioncmp(persist_ver, '1.0') > 0 + %w[/usr/sbin/service netfilter-persistent save] + else + %w[/usr/sbin/service iptables-persistent save] + end + end + when :Debian_manual + case proto.to_sym + when :IPv4 + ['/bin/sh', '-c', '/sbin/iptables-save > /etc/iptables/rules'] + end + when :Archlinux + case proto.to_sym + when :IPv4 + ['/bin/sh', '-c', '/usr/sbin/iptables-save > /etc/iptables/iptables.rules'] + when :IPv6 + ['/bin/sh', '-c', '/usr/sbin/ip6tables-save > /etc/iptables/ip6tables.rules'] + end + end # Catch unsupported OSs from the case statement above. if cmd.nil? diff --git a/lib/puppet/util/ipcidr.rb b/lib/puppet/util/ipcidr.rb index 890be12..d5ab06f 100644 --- a/lib/puppet/util/ipcidr.rb +++ b/lib/puppet/util/ipcidr.rb @@ -1,42 +1,36 @@ + require 'ipaddr' -# IPCidr object wrapper for IPAddr -module Puppet - module Util - class IPCidr < IPAddr - def initialize(ipaddr, family = Socket::AF_UNSPEC) - begin - super(ipaddr, family) - rescue ArgumentError => e - if e.message =~ /invalid address/ - raise ArgumentError, "Invalid address from IPAddr.new: #{ipaddr}" - else - raise e - end - end - end +module Puppet::Util + # IPCidr object wrapper for IPAddr + class IPCidr < IPAddr + def initialize(ipaddr, family = Socket::AF_UNSPEC) + super(ipaddr, family) + rescue ArgumentError => e + raise ArgumentError, "Invalid address from IPAddr.new: #{ipaddr}" if e.message =~ %r{invalid address} + raise e + end - def netmask - _to_string(@mask_addr) - end + def netmask + _to_string(@mask_addr) + end - def prefixlen - m = case @family - when Socket::AF_INET - IN4MASK - when Socket::AF_INET6 - IN6MASK - else - raise "unsupported address family" - end - return $1.length if /\A(1*)(0*)\z/ =~ (@mask_addr & m).to_s(2) - raise "bad addr_mask format" - end + def prefixlen + m = case @family + when Socket::AF_INET + IN4MASK + when Socket::AF_INET6 + IN6MASK + else + raise 'unsupported address family' + end + return Regexp.last_match(1).length if %r{\A(1*)(0*)\z} =~ (@mask_addr & m).to_s(2) + raise 'bad addr_mask format' + end - def cidr - cidr = sprintf("%s/%s", self.to_s, self.prefixlen) - cidr - end + def cidr + cidr = '%s/%s' % [to_s, prefixlen] + cidr end end end diff --git a/spec/acceptance/change_source_spec.rb b/spec/acceptance/change_source_spec.rb index 3a5dbeb..adb397e 100644 --- a/spec/acceptance/change_source_spec.rb +++ b/spec/acceptance/change_source_spec.rb @@ -7,8 +7,7 @@ describe 'changing the source' do end describe 'when unmanaged rules exist' do - it 'applies with 8.0.0.1 first' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '101 test source changes': proto => tcp, @@ -22,29 +21,28 @@ describe 'changing the source' do action => accept, source => '8.0.0.2', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies with 8.0.0.1 first' do + apply_manifest(pp1, catch_failures: true) end it 'adds a unmanaged rule without a comment' do shell('iptables -A INPUT -t filter -s 8.0.0.3/32 -p tcp -m multiport --ports 102 -j ACCEPT') - expect(shell('iptables-save').stdout).to match(/-A INPUT -s 8\.0\.0\.3(\/32)? -p tcp -m multiport --ports 102 -j ACCEPT/) + expect(shell('iptables-save').stdout).to match(%r{-A INPUT -s 8\.0\.0\.3(\/32)? -p tcp -m multiport --ports 102 -j ACCEPT}) end it 'contains the changable 8.0.0.1 rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -s 8\.0\.0\.1(\/32)? -p tcp -m multiport --ports 101 -m comment --comment "101 test source changes" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -s 8\.0\.0\.1(\/32)? -p tcp -m multiport --ports 101 -m comment --comment "101 test source changes" -j ACCEPT}) end end - it 'contains the static 8.0.0.2 rule' do + it 'contains the static 8.0.0.2 rule' do # rubocop:disable RSpec/RepeatedExample : The values being matched differ shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -s 8\.0\.0\.2(\/32)? -p tcp -m multiport --ports 100 -m comment --comment "100 test source static" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -s 8\.0\.0\.2(\/32)? -p tcp -m multiport --ports 100 -m comment --comment "100 test source static" -j ACCEPT}) end end - it 'changes to 8.0.0.4 second' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '101 test source changes': proto => tcp, @@ -52,24 +50,25 @@ describe 'changing the source' do action => accept, source => '8.0.0.4', } - EOS - - expect(apply_manifest(pp, :catch_failures => true).stdout).to match(/Notice: \/Stage\[main\]\/Main\/Firewall\[101 test source changes\]\/source: source changed '8\.0\.0\.1\/32' to '8\.0\.0\.4\/32'/) + EOS + it 'changes to 8.0.0.4 second' do + expect(apply_manifest(pp2, catch_failures: true).stdout) + .to match(%r{Notice: \/Stage\[main\]\/Main\/Firewall\[101 test source changes\]\/source: source changed '8\.0\.0\.1\/32' to '8\.0\.0\.4\/32'}) end it 'does not contain the old changing 8.0.0.1 rule' do shell('iptables-save') do |r| - expect(r.stdout).to_not match(/8\.0\.0\.1/) + expect(r.stdout).not_to match(%r{8\.0\.0\.1}) end end - it 'contains the staic 8.0.0.2 rule' do + it 'contains the staic 8.0.0.2 rule' do # rubocop:disable RSpec/RepeatedExample : The values being matched differ shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -s 8\.0\.0\.2(\/32)? -p tcp -m multiport --ports 100 -m comment --comment "100 test source static" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -s 8\.0\.0\.2(\/32)? -p tcp -m multiport --ports 100 -m comment --comment "100 test source static" -j ACCEPT}) end end it 'contains the changing new 8.0.0.4 rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -s 8\.0\.0\.4(\/32)? -p tcp -m multiport --ports 101 -m comment --comment "101 test source changes" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -s 8\.0\.0\.4(\/32)? -p tcp -m multiport --ports 101 -m comment --comment "101 test source changes" -j ACCEPT}) end end end diff --git a/spec/acceptance/class_spec.rb b/spec/acceptance/class_spec.rb index 1a516ab..7433c62 100644 --- a/spec/acceptance/class_spec.rb +++ b/spec/acceptance/class_spec.rb @@ -1,13 +1,13 @@ require 'spec_helper_acceptance' -describe "firewall class" do - it 'should run successfully' do +describe 'firewall class' do + it 'runs successfully' do pp = "class { 'firewall': }" # Run it twice and test for idempotency - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, catch_failures: true) if do_catch_changes - expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + expect(apply_manifest(pp, catch_failures: true).exit_code).to be_zero end end @@ -15,9 +15,9 @@ describe "firewall class" do pp = "class { 'firewall': ensure => stopped }" # Run it twice and test for idempotency - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, catch_failures: true) if do_catch_changes - expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + expect(apply_manifest(pp, catch_failures: true).exit_code).to be_zero end end @@ -25,9 +25,9 @@ describe "firewall class" do pp = "class { 'firewall': ensure => running }" # Run it twice and test for idempotency - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp, catch_failures: true) if do_catch_changes - expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero + expect(apply_manifest(pp, catch_failures: true).exit_code).to be_zero end end end diff --git a/spec/acceptance/connlimit_spec.rb b/spec/acceptance/connlimit_spec.rb index 7c6168c..f291f7b 100644 --- a/spec/acceptance/connlimit_spec.rb +++ b/spec/acceptance/connlimit_spec.rb @@ -6,11 +6,10 @@ describe 'connlimit property' do ip6tables_flush_all_tables end - if default['platform'] !~ /sles-10/ + if default['platform'] !~ %r{sles-10} describe 'connlimit_above' do context '10' do - it 'applies' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '500 - test': proto => tcp, @@ -18,16 +17,16 @@ describe 'connlimit property' do connlimit_above => '10', action => reject, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) + apply_manifest(pp1, catch_changes: do_catch_changes) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - #connlimit-saddr is added in Ubuntu 14.04. - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --dports 2222 -m connlimit --connlimit-above 10 --connlimit-mask 32 (--connlimit-saddr )?-m comment --comment "500 - test" -j REJECT --reject-with icmp-port-unreachable/) + # connlimit-saddr is added in Ubuntu 14.04. + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --dports 2222 -m connlimit --connlimit-above 10 --connlimit-mask 32 (--connlimit-saddr )?-m comment --comment "500 - test" -j REJECT --reject-with icmp-port-unreachable}) # rubocop:disable Metrics/LineLength : Cannot reduce length to required size end end end @@ -35,8 +34,7 @@ describe 'connlimit property' do describe 'connlimit_mask' do context '24' do - it 'applies' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '501 - test': proto => tcp, @@ -45,16 +43,16 @@ describe 'connlimit property' do connlimit_mask => '24', action => reject, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp2, catch_failures: true) + apply_manifest(pp2, catch_changes: do_catch_changes) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - #connlimit-saddr is added in Ubuntu 14.04. - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --dports 2222 -m connlimit --connlimit-above 10 --connlimit-mask 24 (--connlimit-saddr )?-m comment --comment "501 - test" -j REJECT --reject-with icmp-port-unreachable/) + # connlimit-saddr is added in Ubuntu 14.04. + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --dports 2222 -m connlimit --connlimit-above 10 --connlimit-mask 24 (--connlimit-saddr )?-m comment --comment "501 - test" -j REJECT --reject-with icmp-port-unreachable}) # rubocop:disable Metrics/LineLength : Cannot reduce length to required size end end end diff --git a/spec/acceptance/connmark_spec.rb b/spec/acceptance/connmark_spec.rb index 6de9414..7f8de2d 100644 --- a/spec/acceptance/connmark_spec.rb +++ b/spec/acceptance/connmark_spec.rb @@ -1,25 +1,23 @@ require 'spec_helper_acceptance' describe 'connmark property' do - describe 'connmark' do context '50' do - it 'applies' do - pp = <<-EOS + pp = <<-EOS class { '::firewall': } firewall { '502 - test': proto => 'all', connmark => '0x1', action => reject, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -m connmark --mark 0x1 -m comment --comment "502 - test" -j REJECT --reject-with icmp-port-unreachable/) + expect(r.stdout).to match(%r{-A INPUT -m connmark --mark 0x1 -m comment --comment "502 - test" -j REJECT --reject-with icmp-port-unreachable}) end end end diff --git a/spec/acceptance/firewall_bridging_spec.rb b/spec/acceptance/firewall_bridging_spec.rb index be09614..b09c31d 100644 --- a/spec/acceptance/firewall_bridging_spec.rb +++ b/spec/acceptance/firewall_bridging_spec.rb @@ -1,4 +1,4 @@ - require 'spec_helper_acceptance' +require 'spec_helper_acceptance' describe 'firewall bridging' do before :all do @@ -8,8 +8,7 @@ describe 'firewall bridging' do describe 'iptables physdev tests' do context 'physdev_in eth0' do - it 'applies' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '701 - test': chain => 'FORWARD', @@ -18,22 +17,21 @@ describe 'firewall bridging' do action => accept, physdev_in => 'eth0', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) + apply_manifest(pp1, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 -m multiport --ports 701 -m comment --comment "701 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 -m multiport --ports 701 -m comment --comment "701 - test" -j ACCEPT}) end end + end - context 'physdev_out eth1' do - it 'applies' do - pp = <<-EOS + context 'physdev_out eth1' do + pp2 = <<-EOS class { '::firewall': } firewall { '702 - test': chain => 'FORWARD', @@ -42,22 +40,21 @@ describe 'firewall bridging' do action => accept, physdev_out => 'eth1', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp2, catch_failures: true) + apply_manifest(pp2, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-out eth1 -m multiport --ports 702 -m comment --comment "702 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-out eth1 -m multiport --ports 702 -m comment --comment "702 - test" -j ACCEPT}) end end + end - context 'physdev_in eth0 and physdev_out eth1' do - it 'applies' do - pp = <<-EOS + context 'physdev_in eth0 and physdev_out eth1' do + pp3 = <<-EOS class { '::firewall': } firewall { '703 - test': chain => 'FORWARD', @@ -67,22 +64,21 @@ describe 'firewall bridging' do physdev_in => 'eth0', physdev_out => 'eth1', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp3, catch_failures: true) + apply_manifest(pp3, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 -m multiport --ports 703 -m comment --comment "703 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 -m multiport --ports 703 -m comment --comment "703 - test" -j ACCEPT}) end end + end - context 'physdev_is_bridged' do - it 'applies' do - pp = <<-EOS + context 'physdev_is_bridged' do + pp4 = <<-EOS class { '::firewall': } firewall { '704 - test': chain => 'FORWARD', @@ -91,22 +87,21 @@ describe 'firewall bridging' do action => accept, physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp4, catch_failures: true) + apply_manifest(pp4, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-is-bridged -m multiport --ports 704 -m comment --comment "704 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-is-bridged -m multiport --ports 704 -m comment --comment "704 - test" -j ACCEPT}) end end + end - context 'physdev_in eth0 and physdev_is_bridged' do - it 'applies' do - pp = <<-EOS + context 'physdev_in eth0 and physdev_is_bridged' do + pp5 = <<-EOS class { '::firewall': } firewall { '705 - test': chain => 'FORWARD', @@ -116,22 +111,21 @@ describe 'firewall bridging' do physdev_in => 'eth0', physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp5, catch_failures: true) + apply_manifest(pp5, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-is-bridged -m multiport --ports 705 -m comment --comment "705 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-is-bridged -m multiport --ports 705 -m comment --comment "705 - test" -j ACCEPT}) end end + end - context 'physdev_out eth1 and physdev_is_bridged' do - it 'applies' do - pp = <<-EOS + context 'physdev_out eth1 and physdev_is_bridged' do + pp6 = <<-EOS class { '::firewall': } firewall { '706 - test': chain => 'FORWARD', @@ -141,22 +135,21 @@ describe 'firewall bridging' do physdev_out => 'eth1', physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp6, catch_failures: true) + apply_manifest(pp6, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-out eth1 --physdev-is-bridged -m multiport --ports 706 -m comment --comment "706 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-out eth1 --physdev-is-bridged -m multiport --ports 706 -m comment --comment "706 - test" -j ACCEPT}) end end + end - context 'physdev_in eth0 and physdev_out eth1 and physdev_is_bridged' do - it 'applies' do - pp = <<-EOS + context 'physdev_in eth0 and physdev_out eth1 and physdev_is_bridged' do + pp7 = <<-EOS class { '::firewall': } firewall { '707 - test': chain => 'FORWARD', @@ -167,27 +160,25 @@ describe 'firewall bridging' do physdev_out => 'eth1', physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp7, catch_failures: true) + apply_manifest(pp7, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 --physdev-is-bridged -m multiport --ports 707 -m comment --comment "707 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 --physdev-is-bridged -m multiport --ports 707 -m comment --comment "707 - test" -j ACCEPT}) end end - end + end - #iptables version 1.3.5 is not suppored by the ip6tables provider - if default['platform'] !~ /el-5/ and default['platform'] !~ /sles-10/ - describe 'ip6tables physdev tests' do - context 'physdev_in eth0' do - it 'applies' do - pp = <<-EOS + # iptables version 1.3.5 is not suppored by the ip6tables provider + if default['platform'] !~ %r{el-5} && default['platform'] !~ %r{sles-10} + describe 'ip6tables physdev tests' do + context 'physdev_in eth0' do + pp8 = <<-EOS class { '::firewall': } firewall { '701 - test': provider => 'ip6tables', @@ -197,22 +188,21 @@ describe 'firewall bridging' do action => accept, physdev_in => 'eth0', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp8, catch_failures: true) + apply_manifest(pp8, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 -m multiport --ports 701 -m comment --comment "701 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 -m multiport --ports 701 -m comment --comment "701 - test" -j ACCEPT}) end end + end - context 'physdev_out eth1' do - it 'applies' do - pp = <<-EOS + context 'physdev_out eth1' do + pp9 = <<-EOS class { '::firewall': } firewall { '702 - test': provider => 'ip6tables', @@ -222,22 +212,21 @@ describe 'firewall bridging' do action => accept, physdev_out => 'eth1', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp9, catch_failures: true) + apply_manifest(pp9, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-out eth1 -m multiport --ports 702 -m comment --comment "702 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-out eth1 -m multiport --ports 702 -m comment --comment "702 - test" -j ACCEPT}) end end + end - context 'physdev_in eth0 and physdev_out eth1' do - it 'applies' do - pp = <<-EOS + context 'physdev_in eth0 and physdev_out eth1' do + pp10 = <<-EOS class { '::firewall': } firewall { '703 - test': provider => 'ip6tables', @@ -248,22 +237,21 @@ describe 'firewall bridging' do physdev_in => 'eth0', physdev_out => 'eth1', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp10, catch_failures: true) + apply_manifest(pp10, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 -m multiport --ports 703 -m comment --comment "703 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 -m multiport --ports 703 -m comment --comment "703 - test" -j ACCEPT}) end end + end - context 'physdev_is_bridged' do - it 'applies' do - pp = <<-EOS + context 'physdev_is_bridged' do + pp11 = <<-EOS class { '::firewall': } firewall { '704 - test': provider => 'ip6tables', @@ -273,22 +261,21 @@ describe 'firewall bridging' do action => accept, physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp11, catch_failures: true) + apply_manifest(pp11, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-is-bridged -m multiport --ports 704 -m comment --comment "704 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-is-bridged -m multiport --ports 704 -m comment --comment "704 - test" -j ACCEPT}) end end + end - context 'physdev_in eth0 and physdev_is_bridged' do - it 'applies' do - pp = <<-EOS + context 'physdev_in eth0 and physdev_is_bridged' do + pp12 = <<-EOS class { '::firewall': } firewall { '705 - test': provider => 'ip6tables', @@ -299,22 +286,21 @@ describe 'firewall bridging' do physdev_in => 'eth0', physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp12, catch_failures: true) + apply_manifest(pp12, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-is-bridged -m multiport --ports 705 -m comment --comment "705 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-is-bridged -m multiport --ports 705 -m comment --comment "705 - test" -j ACCEPT}) end end + end - context 'physdev_out eth1 and physdev_is_bridged' do - it 'applies' do - pp = <<-EOS + context 'physdev_out eth1 and physdev_is_bridged' do + pp13 = <<-EOS class { '::firewall': } firewall { '706 - test': provider => 'ip6tables', @@ -325,22 +311,21 @@ describe 'firewall bridging' do physdev_out => 'eth1', physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp13, catch_failures: true) + apply_manifest(pp13, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-out eth1 --physdev-is-bridged -m multiport --ports 706 -m comment --comment "706 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-out eth1 --physdev-is-bridged -m multiport --ports 706 -m comment --comment "706 - test" -j ACCEPT}) end end + end - context 'physdev_in eth0 and physdev_out eth1 and physdev_is_bridged' do - it 'applies' do - pp = <<-EOS + context 'physdev_in eth0 and physdev_out eth1 and physdev_is_bridged' do + pp14 = <<-EOS class { '::firewall': } firewall { '707 - test': provider => 'ip6tables', @@ -352,22 +337,21 @@ describe 'firewall bridging' do physdev_out => 'eth1', physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp14, catch_failures: true) + apply_manifest(pp14, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 --physdev-is-bridged -m multiport --ports 707 -m comment --comment "707 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 --physdev-is-bridged -m multiport --ports 707 -m comment --comment "707 - test" -j ACCEPT}) end end + end - context 'physdev_is_in' do - it 'applies' do - pp = <<-EOS + context 'physdev_is_in' do + pp15 = <<-EOS class { '::firewall': } firewall { '708 - test': provider => 'ip6tables', @@ -377,22 +361,21 @@ describe 'firewall bridging' do action => accept, physdev_is_in => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp15, catch_failures: true) + apply_manifest(pp15, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-is-in -m multiport --ports 708 -m comment --comment "708 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-is-in -m multiport --ports 708 -m comment --comment "708 - test" -j ACCEPT}) end end + end - context 'physdev_is_out' do - it 'applies' do - pp = <<-EOS + context 'physdev_is_out' do + pp16 = <<-EOS class { '::firewall': } firewall { '709 - test': provider => 'ip6tables', @@ -402,18 +385,18 @@ describe 'firewall bridging' do action => accept, physdev_is_out => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp16, catch_failures: true) + apply_manifest(pp16, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m physdev\s+--physdev-is-out -m multiport --ports 709 -m comment --comment "709 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m physdev\s+--physdev-is-out -m multiport --ports 709 -m comment --comment "709 - test" -j ACCEPT}) end end end + end end end diff --git a/spec/acceptance/firewall_clusterip_spec.rb b/spec/acceptance/firewall_clusterip_spec.rb index 03fbd90..a3c71ce 100644 --- a/spec/acceptance/firewall_clusterip_spec.rb +++ b/spec/acceptance/firewall_clusterip_spec.rb @@ -1,7 +1,6 @@ # These tests have been commented out, as there are suspicions that the clusterIP ipt module is causing system reboots. - # require 'spec_helper_acceptance' # describe 'firewall type', :unless => UNSUPPORTED_PLATFORMS.include?(fact('osfamily')) do @@ -40,7 +39,7 @@ # it 'should contain the rule' do # pending("MODULES-2124 should be resolved for clusterip RHEL7 support") if default['platform'] =~ /el-7/ # shell('iptables-save') do |r| -# expect(r.stdout).to match(/-A FORWARD -d (1.1.1.1\/32|1.1.1.1) -i eth0 -p tcp -m comment --comment "830 - clusterip test" -j CLUSTERIP --new --hashmode sourceip --clustermac 01:00:5E:00:00:00 --total-nodes 2 --local-node 1 --hash-init 1337/) +# expect(r.stdout).to match(/-A FORWARD -d (1.1.1.1\/32|1.1.1.1) -i eth0 -p tcp -m comment --comment "830 - clusterip test" -j CLUSTERIP --new --hashmode sourceip --clustermac 01:00:5E:00:00:00 --total-nodes 2 --local-node 1 --hash-init 1337/) # rubocop:disable Metrics/LineLength : Cannot reduce length to required size # end # end # end diff --git a/spec/acceptance/firewall_dscp_spec.rb b/spec/acceptance/firewall_dscp_spec.rb index 581f117..8a49de5 100644 --- a/spec/acceptance/firewall_dscp_spec.rb +++ b/spec/acceptance/firewall_dscp_spec.rb @@ -8,8 +8,7 @@ describe 'firewall DSCP' do describe 'dscp ipv4 tests' do context 'set_dscp 0x01' do - it 'applies' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '1000 - set_dscp': @@ -20,21 +19,20 @@ describe 'firewall DSCP' do chain => 'OUTPUT', table => 'mangle', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t mangle') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m multiport --ports 997 -m comment --comment "1000 - set_dscp" -j DSCP --set-dscp 0x01/) + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m multiport --ports 997 -m comment --comment "1000 - set_dscp" -j DSCP --set-dscp 0x01}) end end end context 'set_dscp_class EF' do - it 'applies' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '1001 EF - set_dscp_class': @@ -45,24 +43,23 @@ describe 'firewall DSCP' do chain => 'OUTPUT', table => 'mangle', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp2, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m multiport --ports 997 -m comment --comment "1001 EF - set_dscp_class" -j DSCP --set-dscp 0x2e/) + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m multiport --ports 997 -m comment --comment "1001 EF - set_dscp_class" -j DSCP --set-dscp 0x2e}) end end end end - if default['platform'] !~ /el-5/ and default['platform'] !~ /sles-10/ + if default['platform'] !~ %r{el-5} && default['platform'] !~ %r{sles-10} describe 'dscp ipv6 tests' do context 'set_dscp 0x01' do - it 'applies' do - pp = <<-EOS + pp3 = <<-EOS class { '::firewall': } firewall { '1002 - set_dscp': @@ -74,21 +71,20 @@ describe 'firewall DSCP' do table => 'mangle', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp3, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save -t mangle') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m multiport --ports 997 -m comment --comment "1002 - set_dscp" -j DSCP --set-dscp 0x01/) + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m multiport --ports 997 -m comment --comment "1002 - set_dscp" -j DSCP --set-dscp 0x01}) end end end context 'set_dscp_class EF' do - it 'applies' do - pp = <<-EOS + pp4 = <<-EOS class { '::firewall': } firewall { '1003 EF - set_dscp_class': @@ -100,18 +96,17 @@ describe 'firewall DSCP' do table => 'mangle', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp4, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m multiport --ports 997 -m comment --comment "1003 EF - set_dscp_class" -j DSCP --set-dscp 0x2e/) + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m multiport --ports 997 -m comment --comment "1003 EF - set_dscp_class" -j DSCP --set-dscp 0x2e}) end end end end end - end diff --git a/spec/acceptance/firewall_gid_spec.rb b/spec/acceptance/firewall_gid_spec.rb index 1730e29..8e8a356 100644 --- a/spec/acceptance/firewall_gid_spec.rb +++ b/spec/acceptance/firewall_gid_spec.rb @@ -6,10 +6,9 @@ describe 'firewall gid' do ip6tables_flush_all_tables end - describe "gid tests" do + describe 'gid tests' do context 'gid set to root' do - it 'applies' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '801 - test': chain => 'OUTPUT', @@ -17,22 +16,21 @@ describe 'firewall gid' do gid => 'root', proto => 'all', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) + apply_manifest(pp1, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -m owner --gid-owner (0|root) -m comment --comment "801 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -m owner --gid-owner (0|root) -m comment --comment "801 - test" -j ACCEPT}) + end end end context 'gid set to !root' do - it 'applies' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '802 - test': chain => 'OUTPUT', @@ -40,22 +38,21 @@ describe 'firewall gid' do gid => '!root', proto => 'all', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp2, catch_failures: true) + apply_manifest(pp2, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -m owner ! --gid-owner (0|root) -m comment --comment "802 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -m owner ! --gid-owner (0|root) -m comment --comment "802 - test" -j ACCEPT}) + end end end context 'gid set to 0' do - it 'applies' do - pp = <<-EOS + pp3 = <<-EOS class { '::firewall': } firewall { '803 - test': chain => 'OUTPUT', @@ -63,22 +60,21 @@ describe 'firewall gid' do gid => '0', proto => 'all', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp3, catch_failures: true) + apply_manifest(pp3, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -m owner --gid-owner (0|root) -m comment --comment "803 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -m owner --gid-owner (0|root) -m comment --comment "803 - test" -j ACCEPT}) + end end end context 'gid set to !0' do - it 'applies' do - pp = <<-EOS + pp4 = <<-EOS class { '::firewall': } firewall { '804 - test': chain => 'OUTPUT', @@ -86,19 +82,17 @@ describe 'firewall gid' do gid => '!0', proto => 'all', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp4, catch_failures: true) + apply_manifest(pp4, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -m owner ! --gid-owner (0|root) -m comment --comment "804 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -m owner ! --gid-owner (0|root) -m comment --comment "804 - test" -j ACCEPT}) + end end end - end - end diff --git a/spec/acceptance/firewall_iptmodules_spec.rb b/spec/acceptance/firewall_iptmodules_spec.rb index 24234c0..c9aa52a 100644 --- a/spec/acceptance/firewall_iptmodules_spec.rb +++ b/spec/acceptance/firewall_iptmodules_spec.rb @@ -1,4 +1,4 @@ - require 'spec_helper_acceptance' +require 'spec_helper_acceptance' describe 'firewall iptmodules' do before :all do @@ -8,8 +8,7 @@ describe 'firewall iptmodules' do describe 'iptables ipt_modules tests' do context 'all the modules with multiple args' do - it 'applies' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '801 - ipt_modules tests': proto => tcp, @@ -26,22 +25,21 @@ describe 'firewall iptmodules' do physdev_out => "eth1", physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) + apply_manifest(pp1, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 --physdev-is-bridged -m iprange --src-range 90.0.0.1-90.0.0.2\s+--dst-range 100.0.0.1-100.0.0.2 -m owner --uid-owner (0|root) --gid-owner 404 -m multiport --dports 8080 -m addrtype --src-type LOCAL --dst-type UNICAST -m comment --comment "801 - ipt_modules tests" -j REJECT --reject-with icmp-port-unreachable/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 --physdev-is-bridged -m iprange --src-range 90.0.0.1-90.0.0.2\s+--dst-range 100.0.0.1-100.0.0.2 -m owner --uid-owner (0|root) --gid-owner 404 -m multiport --dports 8080 -m addrtype --src-type LOCAL --dst-type UNICAST -m comment --comment "801 - ipt_modules tests" -j REJECT --reject-with icmp-port-unreachable}) # rubocop:disable Metrics/LineLength : Cannot reduce length to the required size + end end end context 'all the modules with single args' do - it 'applies' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '802 - ipt_modules tests': proto => tcp, @@ -54,26 +52,25 @@ describe 'firewall iptmodules' do physdev_out => "eth1", physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp2, catch_failures: true) + apply_manifest(pp2, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m physdev\s+--physdev-out eth1 --physdev-is-bridged -m iprange --dst-range 100.0.0.1-100.0.0.2 -m owner --gid-owner 404 -m multiport --dports 8080 -m addrtype --dst-type UNICAST -m comment --comment "802 - ipt_modules tests" -j REJECT --reject-with icmp-port-unreachable/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m physdev\s+--physdev-out eth1 --physdev-is-bridged -m iprange --dst-range 100.0.0.1-100.0.0.2 -m owner --gid-owner 404 -m multiport --dports 8080 -m addrtype --dst-type UNICAST -m comment --comment "802 - ipt_modules tests" -j REJECT --reject-with icmp-port-unreachable}) # rubocop:disable Metrics/LineLength : Cannot reduce length to the required size + end end end end - #iptables version 1.3.5 is not suppored by the ip6tables provider - if default['platform'] =~ /debian-7/ or default['platform'] =~ /ubuntu-14\.04/ - describe 'ip6tables ipt_modules tests' do - context 'all the modules with multiple args' do - it 'applies' do - pp = <<-EOS + # iptables version 1.3.5 is not suppored by the ip6tables provider + if default['platform'] =~ %r{debian-7} || default['platform'] =~ %r{ubuntu-14\.04} + describe 'ip6tables ipt_modules tests' do + context 'all the modules with multiple args' do + pp3 = <<-EOS class { '::firewall': } firewall { '801 - ipt_modules tests': proto => tcp, @@ -91,22 +88,21 @@ describe 'firewall iptmodules' do physdev_out => "eth1", physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp3, catch_failures: true) + apply_manifest(pp3, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 --physdev-is-bridged -m iprange --src-range 2001::-2002::\s+--dst-range 2003::-2004:: -m owner --uid-owner (0|root) --gid-owner 404 -m multiport --dports 8080 -m addrtype --src-type LOCAL --dst-type UNICAST -m comment --comment "801 - ipt_modules tests" -j REJECT --reject-with icmp6-port-unreachable/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 --physdev-is-bridged -m iprange --src-range 2001::-2002::\s+--dst-range 2003::-2004:: -m owner --uid-owner (0|root) --gid-owner 404 -m multiport --dports 8080 -m addrtype --src-type LOCAL --dst-type UNICAST -m comment --comment "801 - ipt_modules tests" -j REJECT --reject-with icmp6-port-unreachable}) # rubocop:disable Metrics/LineLength : Cannot reduce length to the required size end end + end - context 'all the modules with single args' do - it 'applies' do - pp = <<-EOS + context 'all the modules with single args' do + pp4 = <<-EOS class { '::firewall': } firewall { '802 - ipt_modules tests': proto => tcp, @@ -120,26 +116,25 @@ describe 'firewall iptmodules' do physdev_out => "eth1", physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp4, catch_failures: true) + apply_manifest(pp4, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m physdev\s+--physdev-out eth1 --physdev-is-bridged -m iprange --dst-range 2003::-2004:: -m owner --gid-owner 404 -m multiport --dports 8080 -m addrtype --dst-type UNICAST -m comment --comment "802 - ipt_modules tests" -j REJECT --reject-with icmp6-port-unreachable/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m physdev\s+--physdev-out eth1 --physdev-is-bridged -m iprange --dst-range 2003::-2004:: -m owner --gid-owner 404 -m multiport --dports 8080 -m addrtype --dst-type UNICAST -m comment --comment "802 - ipt_modules tests" -j REJECT --reject-with icmp6-port-unreachable}) # rubocop:disable Metrics/LineLength : Cannot reduce length to the required size end end end - # Older OSes don't have addrtype so we leave those properties out. - # el-5 doesn't support ipv6 by default - elsif default['platform'] !~ /el-5/ and default['platform'] !~ /sles-10/ - describe 'ip6tables ipt_modules tests' do - context 'all the modules with multiple args' do - it 'applies' do - pp = <<-EOS + end + # Older OSes don't have addrtype so we leave those properties out. + # el-5 doesn't support ipv6 by default + elsif default['platform'] !~ %r{el-5} && default['platform'] !~ %r{sles-10} + describe 'ip6tables ipt_modules tests' do + context 'all the modules with multiple args' do + pp5 = <<-EOS class { '::firewall': } firewall { '801 - ipt_modules tests': proto => tcp, @@ -155,22 +150,21 @@ describe 'firewall iptmodules' do physdev_out => "eth1", physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp5, catch_failures: true) + apply_manifest(pp5, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 --physdev-is-bridged -m iprange --src-range 2001::-2002::\s+--dst-range 2003::-2004:: -m owner --uid-owner (0|root) --gid-owner 404 -m multiport --dports 8080 -m comment --comment "801 - ipt_modules tests" -j REJECT --reject-with icmp6-port-unreachable/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m physdev\s+--physdev-in eth0 --physdev-out eth1 --physdev-is-bridged -m iprange --src-range 2001::-2002::\s+--dst-range 2003::-2004:: -m owner --uid-owner (0|root) --gid-owner 404 -m multiport --dports 8080 -m comment --comment "801 - ipt_modules tests" -j REJECT --reject-with icmp6-port-unreachable}) # rubocop:disable Metrics/LineLength : Cannot reduce length to the required size end end + end - context 'all the modules with single args' do - it 'applies' do - pp = <<-EOS + context 'all the modules with single args' do + pp6 = <<-EOS class { '::firewall': } firewall { '802 - ipt_modules tests': proto => tcp, @@ -183,19 +177,18 @@ describe 'firewall iptmodules' do physdev_out => "eth1", physdev_is_bridged => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end + EOS + it 'applies' do + apply_manifest(pp6, catch_failures: true) + apply_manifest(pp6, catch_changes: do_catch_changes) + end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m physdev\s+--physdev-out eth1 --physdev-is-bridged -m iprange --dst-range 2003::-2004:: -m owner --gid-owner 404 -m multiport --dports 8080 -m comment --comment "802 - ipt_modules tests" -j REJECT --reject-with icmp6-port-unreachable/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m physdev\s+--physdev-out eth1 --physdev-is-bridged -m iprange --dst-range 2003::-2004:: -m owner --gid-owner 404 -m multiport --dports 8080 -m comment --comment "802 - ipt_modules tests" -j REJECT --reject-with icmp6-port-unreachable}) # rubocop:disable Metrics/LineLength : Cannot reduce length to the required size end end end end - + end end diff --git a/spec/acceptance/firewall_mss_spec.rb b/spec/acceptance/firewall_mss_spec.rb index 0a01bde..f1cc391 100644 --- a/spec/acceptance/firewall_mss_spec.rb +++ b/spec/acceptance/firewall_mss_spec.rb @@ -8,8 +8,7 @@ describe 'firewall MSS' do describe 'mss ipv4 tests' do context '1360' do - it 'applies' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '502 - set_mss': @@ -21,21 +20,20 @@ describe 'firewall MSS' do chain => 'FORWARD', table => 'mangle', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t mangle') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1541 -m comment --comment "502 - set_mss" -j TCPMSS --set-mss 1360/) + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1541 -m comment --comment "502 - set_mss" -j TCPMSS --set-mss 1360}) end end end context 'clamp_mss_to_pmtu' do - it 'applies' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '503 - clamp_mss_to_pmtu': @@ -45,24 +43,23 @@ describe 'firewall MSS' do jump => 'TCPMSS', clamp_mss_to_pmtu => true, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp2, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m comment --comment "503 - clamp_mss_to_pmtu" -j TCPMSS --clamp-mss-to-pmtu/) + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m comment --comment "503 - clamp_mss_to_pmtu" -j TCPMSS --clamp-mss-to-pmtu}) end end end end - if default['platform'] !~ /el-5/ and default['platform'] !~ /sles-10/ + if default['platform'] !~ %r{el-5} && default['platform'] !~ %r{sles-10} describe 'mss ipv6 tests' do context '1360' do - it 'applies' do - pp = <<-EOS + pp3 = <<-EOS class { '::firewall': } firewall { '502 - set_mss': @@ -75,21 +72,20 @@ describe 'firewall MSS' do table => 'mangle', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp3, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save -t mangle') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1541 -m comment --comment "502 - set_mss" -j TCPMSS --set-mss 1360/) + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m tcpmss --mss 1361:1541 -m comment --comment "502 - set_mss" -j TCPMSS --set-mss 1360}) end end end context 'clamp_mss_to_pmtu' do - it 'applies' do - pp = <<-EOS + pp4 = <<-EOS class { '::firewall': } firewall { '503 - clamp_mss_to_pmtu': @@ -100,18 +96,17 @@ describe 'firewall MSS' do clamp_mss_to_pmtu => true, provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp4, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m comment --comment "503 - clamp_mss_to_pmtu" -j TCPMSS --clamp-mss-to-pmtu/) + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m tcp --tcp-flags SYN,RST SYN -m comment --comment "503 - clamp_mss_to_pmtu" -j TCPMSS --clamp-mss-to-pmtu}) end end end end end - end diff --git a/spec/acceptance/firewall_spec.rb b/spec/acceptance/firewall_spec.rb index 8eee85b..fe409e7 100644 --- a/spec/acceptance/firewall_spec.rb +++ b/spec/acceptance/firewall_spec.rb @@ -8,26 +8,23 @@ describe 'firewall basics', docker: true do describe 'name' do context 'valid' do - it 'applies cleanly' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '001 - test': ensure => present } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies cleanly' do + apply_manifest(pp1, catch_failures: true) end - end context 'invalid' do - it 'fails' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { 'test': ensure => present } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Invalid value "test"./) + EOS + it 'fails' do + apply_manifest(pp2, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Invalid value "test".}) end end end @@ -35,29 +32,27 @@ describe 'firewall basics', docker: true do describe 'ensure' do context 'default' do - it 'applies' do - pp = <<-EOS + pp3 = <<-EOS class { '::firewall': } firewall { '555 - test': proto => tcp, port => '555', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp3, catch_failures: true) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 555 -m comment --comment "555 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 555 -m comment --comment "555 - test" -j ACCEPT}) + end end end context 'present' do - it 'applies' do - pp = <<-EOS + pp4 = <<-EOS class { '::firewall': } firewall { '555 - test': ensure => present, @@ -65,21 +60,20 @@ describe 'firewall basics', docker: true do port => '555', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp4, catch_failures: true) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 555 -m comment --comment "555 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 555 -m comment --comment "555 - test" -j ACCEPT}) + end end end context 'absent' do - it 'applies' do - pp = <<-EOS + pp5 = <<-EOS class { '::firewall': } firewall { '555 - test': ensure => absent, @@ -87,23 +81,22 @@ describe 'firewall basics', docker: true do port => '555', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp5, catch_failures: true) end - it 'should not contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m multiport --ports 555 -m comment --comment "555 - test" -j ACCEPT/) - end + it 'does not contain the rule' do + shell('iptables-save') do |r| + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m multiport --ports 555 -m comment --comment "555 - test" -j ACCEPT}) + end end end end describe 'source' do context '192.168.2.0/24' do - it 'applies' do - pp = <<-EOS + pp7 = <<-EOS class { '::firewall': } firewall { '556 - test': proto => tcp, @@ -111,22 +104,21 @@ describe 'firewall basics', docker: true do action => accept, source => '192.168.2.0/24', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp7, catch_failures: true) + apply_manifest(pp7, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -s 192.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 556 -m comment --comment "556 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -s 192.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 556 -m comment --comment "556 - test" -j ACCEPT}) + end end end context '! 192.168.2.0/24' do - it 'applies' do - pp = <<-EOS + pp8 = <<-EOS class { '::firewall': } firewall { '556 - test': proto => tcp, @@ -134,23 +126,22 @@ describe 'firewall basics', docker: true do action => accept, source => '! 192.168.2.0/24', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp8, catch_failures: true) + apply_manifest(pp8, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT (! -s|-s !) 192.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 556 -m comment --comment "556 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT (! -s|-s !) 192.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 556 -m comment --comment "556 - test" -j ACCEPT}) + end end end # Invalid address context '256.168.2.0/24' do - it 'applies' do - pp = <<-EOS + pp9 = <<-EOS class { '::firewall': } firewall { '556 - test': proto => tcp, @@ -158,25 +149,24 @@ describe 'firewall basics', docker: true do action => accept, source => '256.168.2.0/24', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/host_to_ip failed for 256.168.2.0\/(24|255\.255\.255\.0)/) + EOS + it 'applies' do + apply_manifest(pp9, expect_failures: true) do |r| + expect(r.stderr).to match(%r{host_to_ip failed for 256.168.2.0\/(24|255\.255\.255\.0)}) end end - it 'should not contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -s 256.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 556 -m comment --comment "556 - test" -j ACCEPT/) - end + it 'does not contain the rule' do + shell('iptables-save') do |r| + expect(r.stdout).not_to match(%r{-A INPUT -s 256.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 556 -m comment --comment "556 - test" -j ACCEPT}) + end end end end describe 'src_range' do context '192.168.1.1-192.168.1.10' do - it 'applies' do - pp = <<-EOS + pp10 = <<-EOS class { '::firewall': } firewall { '557 - test': proto => tcp, @@ -184,23 +174,22 @@ describe 'firewall basics', docker: true do action => accept, src_range => '192.168.1.1-192.168.1.10', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp10, catch_failures: true) + apply_manifest(pp10, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m iprange --src-range 192.168.1.1-192.168.1.10 -m multiport --ports 557 -m comment --comment "557 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -p tcp -m iprange --src-range 192.168.1.1-192.168.1.10 -m multiport --ports 557 -m comment --comment "557 - test" -j ACCEPT}) + end end end # Invalid IP context '392.168.1.1-192.168.1.10' do - it 'applies' do - pp = <<-EOS + pp11 = <<-EOS class { '::firewall': } firewall { '557 - test': proto => tcp, @@ -208,25 +197,24 @@ describe 'firewall basics', docker: true do action => accept, src_range => '392.168.1.1-192.168.1.10', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Invalid IP address "392.168.1.1" in range "392.168.1.1-192.168.1.10"/) + EOS + it 'applies' do + apply_manifest(pp11, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Invalid IP address "392.168.1.1" in range "392.168.1.1-192.168.1.10"}) end end - it 'should not contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m iprange --src-range 392.168.1.1-192.168.1.10 -m multiport --ports 557 -m comment --comment "557 - test" -j ACCEPT/) - end + it 'does not contain the rule' do + shell('iptables-save') do |r| + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m iprange --src-range 392.168.1.1-192.168.1.10 -m multiport --ports 557 -m comment --comment "557 - test" -j ACCEPT}) + end end end end describe 'destination' do context '192.168.2.0/24' do - it 'applies' do - pp = <<-EOS + pp12 = <<-EOS class { '::firewall': } firewall { '558 - test': proto => tcp, @@ -234,22 +222,21 @@ describe 'firewall basics', docker: true do action => accept, destination => '192.168.2.0/24', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp12, catch_failures: true) + apply_manifest(pp12, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -d 192.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 558 -m comment --comment "558 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -d 192.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 558 -m comment --comment "558 - test" -j ACCEPT}) + end end end context '! 192.168.2.0/24' do - it 'applies' do - pp = <<-EOS + pp13 = <<-EOS class { '::firewall': } firewall { '558 - test': proto => tcp, @@ -257,23 +244,22 @@ describe 'firewall basics', docker: true do action => accept, destination => '! 192.168.2.0/24', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp13, catch_failures: true) + apply_manifest(pp13, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT (! -d|-d !) 192.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 558 -m comment --comment "558 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT (! -d|-d !) 192.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 558 -m comment --comment "558 - test" -j ACCEPT}) + end end end # Invalid address context '256.168.2.0/24' do - it 'applies' do - pp = <<-EOS + pp14 = <<-EOS class { '::firewall': } firewall { '558 - test': proto => tcp, @@ -281,25 +267,24 @@ describe 'firewall basics', docker: true do action => accept, destination => '256.168.2.0/24', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/host_to_ip failed for 256.168.2.0\/(24|255\.255\.255\.0)/) + EOS + it 'applies' do + apply_manifest(pp14, expect_failures: true) do |r| + expect(r.stderr).to match(%r{host_to_ip failed for 256.168.2.0\/(24|255\.255\.255\.0)}) end end - it 'should not contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -d 256.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 558 -m comment --comment "558 - test" -j ACCEPT/) - end + it 'does not contain the rule' do + shell('iptables-save') do |r| + expect(r.stdout).not_to match(%r{-A INPUT -d 256.168.2.0\/(24|255\.255\.255\.0) -p tcp -m multiport --ports 558 -m comment --comment "558 - test" -j ACCEPT}) + end end end end describe 'dst_range' do context '192.168.1.1-192.168.1.10' do - it 'applies' do - pp = <<-EOS + pp15 = <<-EOS class { '::firewall': } firewall { '559 - test': proto => tcp, @@ -307,23 +292,22 @@ describe 'firewall basics', docker: true do action => accept, dst_range => '192.168.1.1-192.168.1.10', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp15, catch_failures: true) + apply_manifest(pp15, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m iprange --dst-range 192.168.1.1-192.168.1.10 -m multiport --ports 559 -m comment --comment "559 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -p tcp -m iprange --dst-range 192.168.1.1-192.168.1.10 -m multiport --ports 559 -m comment --comment "559 - test" -j ACCEPT}) + end end end # Invalid IP context '392.168.1.1-192.168.1.10' do - it 'applies' do - pp = <<-EOS + pp16 = <<-EOS class { '::firewall': } firewall { '559 - test': proto => tcp, @@ -331,286 +315,274 @@ describe 'firewall basics', docker: true do action => accept, dst_range => '392.168.1.1-192.168.1.10', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Invalid IP address "392.168.1.1" in range "392.168.1.1-192.168.1.10"/) + EOS + it 'applies' do + apply_manifest(pp16, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Invalid IP address "392.168.1.1" in range "392.168.1.1-192.168.1.10"}) end end - it 'should not contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m iprange --dst-range 392.168.1.1-192.168.1.10 -m multiport --ports 559 -m comment --comment "559 - test" -j ACCEPT/) - end + it 'does not contain the rule' do + shell('iptables-save') do |r| + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m iprange --dst-range 392.168.1.1-192.168.1.10 -m multiport --ports 559 -m comment --comment "559 - test" -j ACCEPT}) + end end end end describe 'sport' do context 'single port' do - it 'applies' do - pp = <<-EOS + pp17 = <<-EOS class { '::firewall': } firewall { '560 - test': proto => tcp, sport => '560', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp17, catch_failures: true) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --sports 560 -m comment --comment "560 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --sports 560 -m comment --comment "560 - test" -j ACCEPT}) + end end end context 'multiple ports' do - it 'applies' do - pp = <<-EOS + pp18 = <<-EOS class { '::firewall': } firewall { '560 - test': proto => tcp, sport => '560-561', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp18, catch_failures: true) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --sports 560:561 -m comment --comment "560 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --sports 560:561 -m comment --comment "560 - test" -j ACCEPT}) + end end end context 'invalid ports' do - it 'applies' do - pp = <<-EOS + pp19 = <<-EOS class { '::firewall': } firewall { '560 - test': proto => tcp, sport => '9999560-561', action => accept, } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/invalid port\/service `9999560' specified/) + EOS + it 'applies' do + apply_manifest(pp19, expect_failures: true) do |r| + expect(r.stderr).to match(%r{invalid port\/service `9999560' specified}) end end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m multiport --sports 9999560-561 -m comment --comment "560 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m multiport --sports 9999560-561 -m comment --comment "560 - test" -j ACCEPT}) + end end end end describe 'dport' do context 'single port' do - it 'applies' do - pp = <<-EOS + pp20 = <<-EOS class { '::firewall': } firewall { '561 - test': proto => tcp, dport => '561', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp20, catch_failures: true) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --dports 561 -m comment --comment "561 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --dports 561 -m comment --comment "561 - test" -j ACCEPT}) + end end end context 'multiple ports' do - it 'applies' do - pp = <<-EOS + pp21 = <<-EOS class { '::firewall': } firewall { '561 - test': proto => tcp, dport => '561-562', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp21, catch_failures: true) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --dports 561:562 -m comment --comment "561 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --dports 561:562 -m comment --comment "561 - test" -j ACCEPT}) + end end end context 'invalid ports' do - it 'applies' do - pp = <<-EOS + pp22 = <<-EOS class { '::firewall': } firewall { '561 - test': proto => tcp, dport => '9999561-562', action => accept, } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/invalid port\/service `9999561' specified/) + EOS + it 'applies' do + apply_manifest(pp22, expect_failures: true) do |r| + expect(r.stderr).to match(%r{invalid port\/service `9999561' specified}) end end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m multiport --dports 9999561-562 -m comment --comment "560 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m multiport --dports 9999561-562 -m comment --comment "560 - test" -j ACCEPT}) + end end end end describe 'port' do context 'single port' do - it 'applies' do - pp = <<-EOS + pp23 = <<-EOS class { '::firewall': } firewall { '562 - test': proto => tcp, port => '562', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp23, catch_failures: true) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 562 -m comment --comment "562 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 562 -m comment --comment "562 - test" -j ACCEPT}) + end end end context 'multiple ports' do - it 'applies' do - pp = <<-EOS + pp24 = <<-EOS class { '::firewall': } firewall { '562 - test': proto => tcp, port => '562-563', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp24, catch_failures: true) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 562:563 -m comment --comment "562 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 562:563 -m comment --comment "562 - test" -j ACCEPT}) + end end end context 'invalid ports' do - it 'applies' do - pp = <<-EOS + pp25 = <<-EOS class { '::firewall': } firewall { '562 - test': proto => tcp, port => '9999562-563', action => accept, } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/invalid port\/service `9999562' specified/) + EOS + it 'applies' do + apply_manifest(pp25, expect_failures: true) do |r| + expect(r.stderr).to match(%r{invalid port\/service `9999562' specified}) end end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m multiport --ports 9999562-563 -m comment --comment "562 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m multiport --ports 9999562-563 -m comment --comment "562 - test" -j ACCEPT}) + end end end end - ['dst_type', 'src_type'].each do |type| - describe "#{type}" do + %w[dst_type src_type].each do |type| + describe type.to_s do context 'MULTICAST' do - it 'applies' do - pp = <<-EOS + pp26 = <<-EOS class { '::firewall': } firewall { '563 - test': proto => tcp, action => accept, #{type} => 'MULTICAST', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp26, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m addrtype\s.*\sMULTICAST -m comment --comment "563 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m addrtype\s.*\sMULTICAST -m comment --comment "563 - test" -j ACCEPT}) end end end context '! MULTICAST' do - it 'applies' do - pp = <<-EOS + pp27 = <<-EOS class { '::firewall': } firewall { '563 - test inversion': proto => tcp, action => accept, #{type} => '! MULTICAST', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp27, catch_failures: true) + apply_manifest(pp27, catch_changes: do_catch_changes) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m addrtype( !\s.*\sMULTICAST|\s.*\s! MULTICAST) -m comment --comment "563 - test inversion" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m addrtype( !\s.*\sMULTICAST|\s.*\s! MULTICAST) -m comment --comment "563 - test inversion" -j ACCEPT}) end end end context 'BROKEN' do - it 'fails' do - pp = <<-EOS + pp28 = <<-EOS class { '::firewall': } firewall { '563 - test': proto => tcp, action => accept, #{type} => 'BROKEN', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Invalid value "BROKEN"./) + EOS + it 'fails' do + apply_manifest(pp28, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Invalid value "BROKEN".}) end end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m addrtype\s.*\sBROKEN -m comment --comment "563 - test" -j ACCEPT/) + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m addrtype\s.*\sBROKEN -m comment --comment "563 - test" -j ACCEPT}) end end end @@ -619,22 +591,21 @@ describe 'firewall basics', docker: true do describe 'tcp_flags' do context 'FIN,SYN ACK' do - it 'applies' do - pp = <<-EOS + pp29 = <<-EOS class { '::firewall': } firewall { '564 - test': proto => tcp, action => accept, tcp_flags => 'FIN,SYN ACK', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp29, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m tcp --tcp-flags FIN,SYN ACK -m comment --comment "564 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m tcp --tcp-flags FIN,SYN ACK -m comment --comment "564 - test" -j ACCEPT}) end end end @@ -642,22 +613,21 @@ describe 'firewall basics', docker: true do describe 'chain' do context 'INPUT' do - it 'applies' do - pp = <<-EOS + pp30 = <<-EOS class { '::firewall': } firewall { '565 - test': proto => tcp, action => accept, chain => 'FORWARD', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp30, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m comment --comment "565 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m comment --comment "565 - test" -j ACCEPT}) end end end @@ -665,28 +635,26 @@ describe 'firewall basics', docker: true do describe 'table' do context 'mangle' do - it 'applies' do - pp = <<-EOS + pp31 = <<-EOS class { '::firewall': } firewall { '566 - test': proto => tcp, action => accept, table => 'mangle', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp31, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t mangle') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m comment --comment "566 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m comment --comment "566 - test" -j ACCEPT}) end end end context 'nat' do - it 'applies' do - pp = <<-EOS + pp32 = <<-EOS class { '::firewall': } firewall { '566 - test2': proto => tcp, @@ -694,14 +662,14 @@ describe 'firewall basics', docker: true do table => 'nat', chain => 'OUTPUT', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp32, catch_failures: true) end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('iptables-save -t nat') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m comment --comment "566 - test2" -j ACCEPT/) + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m comment --comment "566 - test2" -j ACCEPT}) end end end @@ -710,12 +678,10 @@ describe 'firewall basics', docker: true do describe 'jump' do after :all do iptables_flush_all_tables - expect(shell('iptables -t filter -X TEST').stderr).to eq("") end context 'MARK' do - it 'applies' do - pp = <<-EOS + pp33 = <<-EOS class { '::firewall': } firewallchain { 'TEST:filter:IPv4': ensure => present, @@ -725,21 +691,20 @@ describe 'firewall basics', docker: true do chain => 'INPUT', jump => 'TEST', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp33, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m comment --comment "567 - test" -j TEST/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m comment --comment "567 - test" -j TEST}) end end end context 'jump and apply' do - it 'applies' do - pp = <<-EOS + pp34 = <<-EOS class { '::firewall': } firewallchain { 'TEST:filter:IPv4': ensure => present, @@ -750,16 +715,16 @@ describe 'firewall basics', docker: true do action => 'accept', jump => 'TEST', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Only one of the parameters 'action' and 'jump' can be set/) + EOS + it 'applies' do + apply_manifest(pp34, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Only one of the parameters 'action' and 'jump' can be set}) end end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m comment --comment "568 - test" -j TEST/) + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m comment --comment "568 - test" -j TEST}) end end end @@ -767,8 +732,7 @@ describe 'firewall basics', docker: true do describe 'tosource' do context '192.168.1.1' do - it 'applies' do - pp = <<-EOS + pp35 = <<-EOS class { '::firewall': } firewall { '568 - test': proto => tcp, @@ -777,14 +741,14 @@ describe 'firewall basics', docker: true do jump => 'SNAT', tosource => '192.168.1.1', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp35, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t nat') do |r| - expect(r.stdout).to match(/A POSTROUTING -p tcp -m comment --comment "568 - test" -j SNAT --to-source 192.168.1.1/) + expect(r.stdout).to match(%r{A POSTROUTING -p tcp -m comment --comment "568 - test" -j SNAT --to-source 192.168.1.1}) end end end @@ -792,8 +756,7 @@ describe 'firewall basics', docker: true do describe 'todest' do context '192.168.1.1' do - it 'applies' do - pp = <<-EOS + pp36 = <<-EOS class { '::firewall': } firewall { '569 - test': proto => tcp, @@ -803,14 +766,14 @@ describe 'firewall basics', docker: true do source => '200.200.200.200', todest => '192.168.1.1', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp36, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t nat') do |r| - expect(r.stdout).to match(/-A PREROUTING -s 200.200.200.200(\/32)? -p tcp -m comment --comment "569 - test" -j DNAT --to-destination 192.168.1.1/) + expect(r.stdout).to match(%r{-A PREROUTING -s 200.200.200.200(\/32)? -p tcp -m comment --comment "569 - test" -j DNAT --to-destination 192.168.1.1}) end end end @@ -818,8 +781,7 @@ describe 'firewall basics', docker: true do describe 'toports' do context '192.168.1.1' do - it 'applies' do - pp = <<-EOS + pp37 = <<-EOS class { '::firewall': } firewall { '570 - test': proto => icmp, @@ -828,25 +790,23 @@ describe 'firewall basics', docker: true do jump => 'REDIRECT', toports => '2222', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp37, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t nat') do |r| - expect(r.stdout).to match(/-A PREROUTING -p icmp -m comment --comment "570 - test" -j REDIRECT --to-ports 2222/) + expect(r.stdout).to match(%r{-A PREROUTING -p icmp -m comment --comment "570 - test" -j REDIRECT --to-ports 2222}) end end end end - - if default['platform'] !~ /el-5/ and default['platform'] !~ /ubuntu-10\.04/ and default['platform'] !~ /debian-6/ and default['platform'] !~ /sles/ + if default['platform'] !~ %r{el-5} && default['platform'] !~ %r{ubuntu-10\.04} && default['platform'] !~ %r{debian-6} && default['platform'] !~ %r{sles} describe 'checksum_fill' do context 'virbr' do - it 'applies' do - pp = <<-EOS + pp38 = <<-EOS class { '::firewall': } firewall { '576 - test': proto => udp, @@ -858,14 +818,14 @@ describe 'firewall basics', docker: true do checksum_fill => true, provider => iptables, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp38, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t mangle') do |r| - expect(r.stdout).to match(/-A POSTROUTING -o virbr0 -p udp -m multiport --dports 68 -m comment --comment "576 - test" -j CHECKSUM --checksum-fill/) + expect(r.stdout).to match(%r{-A POSTROUTING -o virbr0 -p udp -m multiport --dports 68 -m comment --comment "576 - test" -j CHECKSUM --checksum-fill}) end end end @@ -873,8 +833,7 @@ describe 'firewall basics', docker: true do describe 'checksum_fill6' do context 'virbr' do - it 'applies' do - pp = <<-EOS + pp39 = <<-EOS class { '::firewall': } firewall { '576 - test': proto => udp, @@ -886,14 +845,14 @@ describe 'firewall basics', docker: true do checksum_fill => true, provider => ip6tables, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp39, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save -t mangle') do |r| - expect(r.stdout).to match(/-A POSTROUTING -o virbr0 -p udp -m multiport --dports 68 -m comment --comment "576 - test" -j CHECKSUM --checksum-fill/) + expect(r.stdout).to match(%r{-A POSTROUTING -o virbr0 -p udp -m multiport --dports 68 -m comment --comment "576 - test" -j CHECKSUM --checksum-fill}) end end end @@ -901,11 +860,10 @@ describe 'firewall basics', docker: true do end # RHEL5 does not support --random - if default['platform'] !~ /el-5/ and default['platform'] !~ /sles-10/ + if default['platform'] !~ %r{el-5} && default['platform'] !~ %r{sles-10} describe 'random' do context '192.168.1.1' do - it 'applies' do - pp = <<-EOS + pp40 = <<-EOS class { '::firewall': } firewall { '570 - test 2': proto => all, @@ -915,15 +873,15 @@ describe 'firewall basics', docker: true do source => '172.30.0.0/16', random => true } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp40, catch_failures: true) + apply_manifest(pp40, catch_changes: do_catch_changes) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t nat') do |r| - expect(r.stdout).to match(/-A POSTROUTING -s 172\.30\.0\.0\/16 -m comment --comment "570 - test 2" -j MASQUERADE --random/) + expect(r.stdout).to match(%r{-A POSTROUTING -s 172\.30\.0\.0\/16 -m comment --comment "570 - test 2" -j MASQUERADE --random}) end end end @@ -932,23 +890,22 @@ describe 'firewall basics', docker: true do describe 'icmp' do context 'any' do - it 'fails' do - pp = <<-EOS + pp41 = <<-EOS class { '::firewall': } firewall { '571 - test': proto => icmp, icmp => 'any', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/This behaviour should be achieved by omitting or undefining the ICMP parameter/) + EOS + it 'fails' do + apply_manifest(pp41, expect_failures: true) do |r| + expect(r.stderr).to match(%r{This behaviour should be achieved by omitting or undefining the ICMP parameter}) end end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p icmp -m comment --comment "570 - test" -m icmp --icmp-type 11/) + expect(r.stdout).not_to match(%r{-A INPUT -p icmp -m comment --comment "570 - test" -m icmp --icmp-type 11}) end end end @@ -956,11 +913,10 @@ describe 'firewall basics', docker: true do # iptables version 1.3.5 is not suppored by the ip6tables provider # iptables version 1.4.7 fails for multiple hl entries - if default['platform'] !~ /(el-5|el-6|sles-10|sles-11)/ + if default['platform'] !~ %r{(el-5|el-6|sles-10|sles-11)} describe 'hop_limit' do context '5' do - it 'applies' do - pp = <<-EOS + pp42 = <<-EOS class { '::firewall': } firewall { '571 - test': ensure => present, @@ -970,21 +926,20 @@ describe 'firewall basics', docker: true do hop_limit => '5', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp42, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 571 -m hl --hl-eq 5 -m comment --comment "571 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 571 -m hl --hl-eq 5 -m comment --comment "571 - test" -j ACCEPT}) end end end context 'invalid' do - it 'applies' do - pp = <<-EOS + pp43 = <<-EOS class { '::firewall': } firewall { '571 - test': ensure => present, @@ -994,16 +949,16 @@ describe 'firewall basics', docker: true do hop_limit => 'invalid', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Invalid value "invalid"./) + EOS + it 'applies' do + apply_manifest(pp43, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Invalid value "invalid".}) end end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m multiport --ports 571 -m comment --comment "571 - test" -m hl --hl-eq invalid -j ACCEPT/) + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m multiport --ports 571 -m comment --comment "571 - test" -m hl --hl-eq invalid -j ACCEPT}) end end end @@ -1011,8 +966,7 @@ describe 'firewall basics', docker: true do describe 'ishasmorefrags' do context 'true' do - it 'applies' do - pp = <<-EOS + pp44 = <<-EOS class { '::firewall': } firewall { '587 - test': ensure => present, @@ -1022,21 +976,20 @@ describe 'firewall basics', docker: true do ishasmorefrags => true, provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp44, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/A INPUT -p tcp -m frag --fragid 0 --fragmore -m multiport --ports 587 -m comment --comment "587 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{A INPUT -p tcp -m frag --fragid 0 --fragmore -m multiport --ports 587 -m comment --comment "587 - test" -j ACCEPT}) end end end context 'false' do - it 'applies' do - pp = <<-EOS + pp45 = <<-EOS class { '::firewall': } firewall { '588 - test': ensure => present, @@ -1046,14 +999,14 @@ describe 'firewall basics', docker: true do ishasmorefrags => false, provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp45, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 588 -m comment --comment "588 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 588 -m comment --comment "588 - test" -j ACCEPT}) end end end @@ -1061,8 +1014,7 @@ describe 'firewall basics', docker: true do describe 'islastfrag' do context 'true' do - it 'applies' do - pp = <<-EOS + pp46 = <<-EOS class { '::firewall': } firewall { '589 - test': ensure => present, @@ -1072,21 +1024,20 @@ describe 'firewall basics', docker: true do islastfrag => true, provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp46, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m frag --fragid 0 --fraglast -m multiport --ports 589 -m comment --comment "589 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m frag --fragid 0 --fraglast -m multiport --ports 589 -m comment --comment "589 - test" -j ACCEPT}) end end end context 'false' do - it 'applies' do - pp = <<-EOS + pp47 = <<-EOS class { '::firewall': } firewall { '590 - test': ensure => present, @@ -1096,14 +1047,14 @@ describe 'firewall basics', docker: true do islastfrag => false, provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp47, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 590 -m comment --comment "590 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 590 -m comment --comment "590 - test" -j ACCEPT}) end end end @@ -1111,8 +1062,7 @@ describe 'firewall basics', docker: true do describe 'isfirstfrag' do context 'true' do - it 'applies' do - pp = <<-EOS + pp48 = <<-EOS class { '::firewall': } firewall { '591 - test': ensure => present, @@ -1122,21 +1072,20 @@ describe 'firewall basics', docker: true do isfirstfrag => true, provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp48, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m frag --fragid 0 --fragfirst -m multiport --ports 591 -m comment --comment "591 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m frag --fragid 0 --fragfirst -m multiport --ports 591 -m comment --comment "591 - test" -j ACCEPT}) end end end context 'false' do - it 'applies' do - pp = <<-EOS + pp49 = <<-EOS class { '::firewall': } firewall { '592 - test': ensure => present, @@ -1146,14 +1095,14 @@ describe 'firewall basics', docker: true do isfirstfrag => false, provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp49, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 592 -m comment --comment "592 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 592 -m comment --comment "592 - test" -j ACCEPT}) end end end @@ -1161,8 +1110,7 @@ describe 'firewall basics', docker: true do describe 'tcp_flags' do context 'FIN,SYN ACK' do - it 'applies' do - pp = <<-EOS + pp50 = <<-EOS class { '::firewall': } firewall { '593 - test': proto => tcp, @@ -1170,14 +1118,14 @@ describe 'firewall basics', docker: true do tcp_flags => 'FIN,SYN ACK', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp50, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m tcp --tcp-flags FIN,SYN ACK -m comment --comment "593 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m tcp --tcp-flags FIN,SYN ACK -m comment --comment "593 - test" -j ACCEPT}) end end end @@ -1185,8 +1133,7 @@ describe 'firewall basics', docker: true do describe 'src_range' do context '2001:db8::1-2001:db8::ff' do - it 'applies' do - pp = <<-EOS + pp51 = <<-EOS class { '::firewall': } firewall { '601 - test': proto => tcp, @@ -1195,23 +1142,22 @@ describe 'firewall basics', docker: true do src_range => '2001:db8::1-2001:db8::ff', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp51, catch_failures: true) + apply_manifest(pp51, catch_changes: do_catch_changes) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m iprange --src-range 2001:db8::1-2001:db8::ff -m multiport --ports 601 -m comment --comment "601 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m iprange --src-range 2001:db8::1-2001:db8::ff -m multiport --ports 601 -m comment --comment "601 - test" -j ACCEPT}) end end end # Invalid IP context '2001::db8::1-2001:db8::ff' do - it 'applies' do - pp = <<-EOS + pp52 = <<-EOS class { '::firewall': } firewall { '601 - test': proto => tcp, @@ -1220,16 +1166,16 @@ describe 'firewall basics', docker: true do provider => 'ip6tables', src_range => '2001::db8::1-2001:db8::ff', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Invalid IP address "2001::db8::1" in range "2001::db8::1-2001:db8::ff"/) + EOS + it 'applies' do + apply_manifest(pp52, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Invalid IP address "2001::db8::1" in range "2001::db8::1-2001:db8::ff"}) end end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m iprange --src-range 2001::db8::1-2001:db8::ff -m multiport --ports 601 -m comment --comment "601 - test" -j ACCEPT/) + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m iprange --src-range 2001::db8::1-2001:db8::ff -m multiport --ports 601 -m comment --comment "601 - test" -j ACCEPT}) end end end @@ -1237,8 +1183,7 @@ describe 'firewall basics', docker: true do describe 'dst_range' do context '2001:db8::1-2001:db8::ff' do - it 'applies' do - pp = <<-EOS + pp53 = <<-EOS class { '::firewall': } firewall { '602 - test': proto => tcp, @@ -1247,23 +1192,22 @@ describe 'firewall basics', docker: true do dst_range => '2001:db8::1-2001:db8::ff', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp53, catch_failures: true) + apply_manifest(pp53, catch_changes: do_catch_changes) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m iprange --dst-range 2001:db8::1-2001:db8::ff -m multiport --ports 602 -m comment --comment "602 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m iprange --dst-range 2001:db8::1-2001:db8::ff -m multiport --ports 602 -m comment --comment "602 - test" -j ACCEPT}) end end end # Invalid IP context '2001::db8::1-2001:db8::ff' do - it 'applies' do - pp = <<-EOS + pp54 = <<-EOS class { '::firewall': } firewall { '602 - test': proto => tcp, @@ -1272,16 +1216,16 @@ describe 'firewall basics', docker: true do provider => 'ip6tables', dst_range => '2001::db8::1-2001:db8::ff', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Invalid IP address "2001::db8::1" in range "2001::db8::1-2001:db8::ff"/) + EOS + it 'applies' do + apply_manifest(pp54, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Invalid IP address "2001::db8::1" in range "2001::db8::1-2001:db8::ff"}) end end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m iprange --dst-range 2001::db8::1-2001:db8::ff -m multiport --ports 602 -m comment --comment "602 - test" -j ACCEPT/) + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m iprange --dst-range 2001::db8::1-2001:db8::ff -m multiport --ports 602 -m comment --comment "602 - test" -j ACCEPT}) end end end @@ -1289,8 +1233,7 @@ describe 'firewall basics', docker: true do describe 'mac_source' do context '0A:1B:3C:4D:5E:6F' do - it 'applies' do - pp = <<-EOS + pp55 = <<-EOS class { '::firewall': } firewall { '604 - test': ensure => present, @@ -1299,68 +1242,66 @@ describe 'firewall basics', docker: true do chain => 'INPUT', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp55, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -s 2001:db8::1\/(128|ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff) -p tcp -m mac --mac-source 0A:1B:3C:4D:5E:6F -m comment --comment "604 - test"/) + expect(r.stdout).to match(%r{-A INPUT -s 2001:db8::1\/(128|ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff) -p tcp -m mac --mac-source 0A:1B:3C:4D:5E:6F -m comment --comment "604 - test"}) end end end end # ip6tables has limited `-m socket` support - if default['platform'] !~ /el-5/ and default['platform'] !~ /ubuntu-10\.04/ and default['platform'] !~ /debian-6/ and default['platform'] !~ /sles/ + if default['platform'] !~ %r{el-5} && default['platform'] !~ %r{ubuntu-10\.04} && default['platform'] !~ %r{debian-6} && default['platform'] !~ %r{sles} describe 'socket' do context 'true' do + pp56 = <<-EOS + class { '::firewall': } + firewall { '605 - test': + ensure => present, + proto => tcp, + port => '605', + action => accept, + chain => 'INPUT', + socket => true, + provider => 'ip6tables', + } + EOS it 'applies' do - pp = <<-EOS - class { '::firewall': } - firewall { '605 - test': - ensure => present, - proto => tcp, - port => '605', - action => accept, - chain => 'INPUT', - socket => true, - provider => 'ip6tables', - } - EOS - - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp56, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 605 -m socket -m comment --comment "605 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 605 -m socket -m comment --comment "605 - test" -j ACCEPT}) end end end context 'false' do + pp57 = <<-EOS + class { '::firewall': } + firewall { '606 - test': + ensure => present, + proto => tcp, + port => '606', + action => accept, + chain => 'INPUT', + socket => false, + provider => 'ip6tables', + } + EOS it 'applies' do - pp = <<-EOS - class { '::firewall': } - firewall { '606 - test': - ensure => present, - proto => tcp, - port => '606', - action => accept, - chain => 'INPUT', - socket => false, - provider => 'ip6tables', - } - EOS - - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp57, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 606 -m comment --comment "606 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 606 -m comment --comment "606 - test" -j ACCEPT}) end end end @@ -1369,36 +1310,34 @@ describe 'firewall basics', docker: true do describe 'ipsec_policy' do context 'ipsec' do + pp58 = <<-EOS + class { '::firewall': } + firewall { '607 - test': + ensure => 'present', + action => 'reject', + chain => 'OUTPUT', + destination => '2001:db8::1/128', + ipsec_dir => 'out', + ipsec_policy => 'ipsec', + proto => 'all', + reject => 'icmp6-adm-prohibited', + table => 'filter', + provider => 'ip6tables', + } + EOS it 'applies' do - pp = <<-EOS - class { '::firewall': } - firewall { '607 - test': - ensure => 'present', - action => 'reject', - chain => 'OUTPUT', - destination => '2001:db8::1/128', - ipsec_dir => 'out', - ipsec_policy => 'ipsec', - proto => 'all', - reject => 'icmp6-adm-prohibited', - table => 'filter', - provider => 'ip6tables', - } - EOS - - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp58, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -d 2001:db8::1\/(128|ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff) -m policy --dir out --pol ipsec -m comment --comment "607 - test" -j REJECT --reject-with icmp6-adm-prohibited/) + expect(r.stdout).to match(%r{-A OUTPUT -d 2001:db8::1\/(128|ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff) -m policy --dir out --pol ipsec -m comment --comment "607 - test" -j REJECT --reject-with icmp6-adm-prohibited}) # rubocop:disable Metrics/LineLength : Cannot reduce line to required length end end end context 'none' do - it 'applies' do - pp = <<-EOS + pp59 = <<-EOS class { '::firewall': } firewall { '608 - test': ensure => 'present', @@ -1412,14 +1351,14 @@ describe 'firewall basics', docker: true do table => 'filter', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp59, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -d 2001:db8::1\/(128|ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff) -m policy --dir out --pol none -m comment --comment "608 - test" -j REJECT --reject-with icmp6-adm-prohibited/) + expect(r.stdout).to match(%r{-A OUTPUT -d 2001:db8::1\/(128|ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff) -m policy --dir out --pol none -m comment --comment "608 - test" -j REJECT --reject-with icmp6-adm-prohibited}) # rubocop:disable Metrics/LineLength : Cannot reduce line to required length end end end @@ -1427,8 +1366,7 @@ describe 'firewall basics', docker: true do describe 'ipsec_dir' do context 'out' do - it 'applies' do - pp = <<-EOS + pp60 = <<-EOS class { '::firewall': } firewall { '609 - test': ensure => 'present', @@ -1442,21 +1380,20 @@ describe 'firewall basics', docker: true do table => 'filter', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp60, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -d 2001:db8::1\/(128|ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff) -m policy --dir out --pol ipsec -m comment --comment "609 - test" -j REJECT --reject-with icmp6-adm-prohibited/) + expect(r.stdout).to match(%r{-A OUTPUT -d 2001:db8::1\/(128|ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff) -m policy --dir out --pol ipsec -m comment --comment "609 - test" -j REJECT --reject-with icmp6-adm-prohibited}) # rubocop:disable Metrics/LineLength : Cannot reduce line to required length end end end context 'in' do - it 'applies' do - pp = <<-EOS + pp61 = <<-EOS class { '::firewall': } firewall { '610 - test': ensure => 'present', @@ -1470,14 +1407,14 @@ describe 'firewall basics', docker: true do table => 'filter', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp61, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -d 2001:db8::1\/(128|ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff) -m policy --dir in --pol none -m comment --comment "610 - test" -j REJECT --reject-with icmp6-adm-prohibited/) + expect(r.stdout).to match(%r{-A INPUT -d 2001:db8::1\/(128|ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff) -m policy --dir in --pol none -m comment --comment "610 - test" -j REJECT --reject-with icmp6-adm-prohibited}) # rubocop:disable Metrics/LineLength : Cannot reduce line to required length end end end @@ -1485,8 +1422,7 @@ describe 'firewall basics', docker: true do describe 'set_mark' do context '0x3e8/0xffffffff' do - it 'applies' do - pp = <<-EOS + pp62 = <<-EOS class { '::firewall': } firewall { '611 - test': ensure => present, @@ -1498,26 +1434,25 @@ describe 'firewall basics', docker: true do set_mark => '0x3e8/0xffffffff', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp62, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save -t mangle') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m multiport --ports 611 -m comment --comment "611 - test" -j MARK --set-xmark 0x3e8\/0xffffffff/) + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m multiport --ports 611 -m comment --comment "611 - test" -j MARK --set-xmark 0x3e8\/0xffffffff}) end end end end - #ip6tables only supports ipset, addrtype, and mask on a limited set of platforms - if default['platform'] =~ /el-7/ or default['platform'] =~ /debian-7/ or default['platform'] =~ /ubuntu-14\.04/ - #ipset is really difficult to test, just testing on one platform - if default['platform'] =~ /ubuntu-14\.04/ + # ip6tables only supports ipset, addrtype, and mask on a limited set of platforms + if default['platform'] =~ %r{el-7} || default['platform'] =~ %r{debian-7} || default['platform'] =~ %r{ubuntu-14\.04} + # ipset is really difficult to test, just testing on one platform + if default['platform'] =~ %r{ubuntu-14\.04} describe 'ipset' do - it 'applies' do - pp = <<-EOS + pp63 = <<-EOS exec { 'hackery pt 1': command => 'service iptables-persistent flush', path => '/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin', @@ -1558,24 +1493,23 @@ describe 'firewall basics', docker: true do provider => 'ip6tables', require => Exec['add honeypot'], } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp63, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m set --match-set blacklist src,dst -m set ! --match-set honeypot dst -m comment --comment "612 - test" -j DROP/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m set --match-set blacklist src,dst -m set ! --match-set honeypot dst -m comment --comment "612 - test" -j DROP}) end end end end # mask isn't supported on deb7 - if default['platform'] !~ /debian-7/ + if default['platform'] !~ %r{debian-7} describe 'mask' do - it 'applies' do - pp = <<-EOS + pp64 = <<-EOS class { '::firewall': } firewall { '613 - test': recent => 'update', @@ -1587,87 +1521,84 @@ describe 'firewall basics', docker: true do mask => 'ffff::', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp64, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A FORWARD -p tcp -m recent --update --seconds 60 --name test --mask ffff:: --rsource -m comment --comment "613 - test" -j DROP/) + expect(r.stdout).to match(%r{-A FORWARD -p tcp -m recent --update --seconds 60 --name test --mask ffff:: --rsource -m comment --comment "613 - test" -j DROP}) end end end end - ['dst_type', 'src_type'].each do |type| - describe "#{type}" do + %w[dst_type src_type].each do |type| + describe type.to_s do context 'MULTICAST' do + pp65 = <<-EOS + class { '::firewall': } + firewall { '603 - test': + proto => tcp, + action => accept, + #{type} => 'MULTICAST', + provider => 'ip6tables', + } + EOS it 'applies' do - pp = <<-EOS - class { '::firewall': } - firewall { '603 - test': - proto => tcp, - action => accept, - #{type} => 'MULTICAST', - provider => 'ip6tables', - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + apply_manifest(pp65, catch_failures: true) + apply_manifest(pp65, catch_changes: do_catch_changes) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m addrtype\s.*\sMULTICAST -m comment --comment "603 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m addrtype\s.*\sMULTICAST -m comment --comment "603 - test" -j ACCEPT}) end end end context '! MULTICAST' do + pp66 = <<-EOS + class { '::firewall': } + firewall { '603 - test inversion': + proto => tcp, + action => accept, + #{type} => '! MULTICAST', + provider => 'ip6tables', + } + EOS it 'applies' do - pp = <<-EOS - class { '::firewall': } - firewall { '603 - test inversion': - proto => tcp, - action => accept, - #{type} => '! MULTICAST', - provider => 'ip6tables', - } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + apply_manifest(pp66, catch_failures: true) + apply_manifest(pp66, catch_changes: do_catch_changes) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m addrtype( !\s.*\sMULTICAST|\s.*\s! MULTICAST) -m comment --comment "603 - test inversion" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m addrtype( !\s.*\sMULTICAST|\s.*\s! MULTICAST) -m comment --comment "603 - test inversion" -j ACCEPT}) end end end context 'BROKEN' do + pp67 = <<-EOS + class { '::firewall': } + firewall { '603 - test': + proto => tcp, + action => accept, + #{type} => 'BROKEN', + provider => 'ip6tables', + } + EOS it 'fails' do - pp = <<-EOS - class { '::firewall': } - firewall { '603 - test': - proto => tcp, - action => accept, - #{type} => 'BROKEN', - provider => 'ip6tables', - } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Invalid value "BROKEN"./) + apply_manifest(pp67, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Invalid value "BROKEN".}) end end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m addrtype\s.*\sBROKEN -m comment --comment "603 - test" -j ACCEPT/) + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m addrtype\s.*\sBROKEN -m comment --comment "603 - test" -j ACCEPT}) end end end @@ -1679,8 +1610,7 @@ describe 'firewall basics', docker: true do describe 'limit' do context '500/sec' do - it 'applies' do - pp = <<-EOS + pp68 = <<-EOS class { '::firewall': } firewall { '572 - test': ensure => present, @@ -1689,14 +1619,14 @@ describe 'firewall basics', docker: true do action => accept, limit => '500/sec', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp68, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 572 -m limit --limit 500\/sec -m comment --comment "572 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 572 -m limit --limit 500\/sec -m comment --comment "572 - test" -j ACCEPT}) end end end @@ -1704,8 +1634,7 @@ describe 'firewall basics', docker: true do describe 'burst' do context '500' do - it 'applies' do - pp = <<-EOS + pp69 = <<-EOS class { '::firewall': } firewall { '573 - test': ensure => present, @@ -1715,21 +1644,20 @@ describe 'firewall basics', docker: true do limit => '500/sec', burst => '1500', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp69, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 573 -m limit --limit 500\/sec --limit-burst 1500 -m comment --comment "573 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 573 -m limit --limit 500\/sec --limit-burst 1500 -m comment --comment "573 - test" -j ACCEPT}) end end end context 'invalid' do - it 'applies' do - pp = <<-EOS + pp70 = <<-EOS class { '::firewall': } firewall { '571 - test': ensure => present, @@ -1739,16 +1667,16 @@ describe 'firewall basics', docker: true do limit => '500/sec', burst => '1500/sec', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Invalid value "1500\/sec"./) + EOS + it 'applies' do + apply_manifest(pp70, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Invalid value "1500\/sec".}) end end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m multiport --ports 573 -m comment --comment "573 - test" -m limit --limit 500\/sec --limit-burst 1500\/sec -j ACCEPT/) + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m multiport --ports 573 -m comment --comment "573 - test" -m limit --limit 500\/sec --limit-burst 1500\/sec -j ACCEPT}) end end end @@ -1756,8 +1684,7 @@ describe 'firewall basics', docker: true do describe 'uid' do context 'nobody' do - it 'applies' do - pp = <<-EOS + pp71 = <<-EOS class { '::firewall': } firewall { '574 - test': ensure => present, @@ -1767,14 +1694,14 @@ describe 'firewall basics', docker: true do action => accept, uid => 'nobody', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp71, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m owner --uid-owner (nobody|\d+) -m multiport --ports 574 -m comment --comment "574 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m owner --uid-owner (nobody|\d+) -m multiport --ports 574 -m comment --comment "574 - test" -j ACCEPT}) end end end @@ -1782,8 +1709,7 @@ describe 'firewall basics', docker: true do describe 'gid' do context 'root' do - it 'applies' do - pp = <<-EOS + pp72 = <<-EOS class { '::firewall': } firewall { '575 - test': ensure => present, @@ -1793,25 +1719,24 @@ describe 'firewall basics', docker: true do action => accept, gid => 'root', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp72, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m owner --gid-owner (root|\d+) -m multiport --ports 575 -m comment --comment "575 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m owner --gid-owner (root|\d+) -m multiport --ports 575 -m comment --comment "575 - test" -j ACCEPT}) end end end end - #iptables version 1.3.5 does not support masks on MARK rules - if default['platform'] !~ /el-5/ and default['platform'] !~ /sles-10/ + # iptables version 1.3.5 does not support masks on MARK rules + if default['platform'] !~ %r{el-5} && default['platform'] !~ %r{sles-10} describe 'set_mark' do context '0x3e8/0xffffffff' do - it 'applies' do - pp = <<-EOS + pp73 = <<-EOS class { '::firewall': } firewall { '580 - test': ensure => present, @@ -1822,14 +1747,14 @@ describe 'firewall basics', docker: true do table => 'mangle', set_mark => '0x3e8/0xffffffff', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp73, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t mangle') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m multiport --ports 580 -m comment --comment "580 - test" -j MARK --set-xmark 0x3e8\/0xffffffff/) + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m multiport --ports 580 -m comment --comment "580 - test" -j MARK --set-xmark 0x3e8\/0xffffffff}) end end end @@ -1838,8 +1763,7 @@ describe 'firewall basics', docker: true do describe 'pkttype' do context 'multicast' do - it 'applies' do - pp = <<-EOS + pp74 = <<-EOS class { '::firewall': } firewall { '581 - test': ensure => present, @@ -1848,21 +1772,20 @@ describe 'firewall basics', docker: true do action => accept, pkttype => 'multicast', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp74, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 581 -m pkttype --pkt-type multicast -m comment --comment "581 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 581 -m pkttype --pkt-type multicast -m comment --comment "581 - test" -j ACCEPT}) end end end context 'test' do - it 'applies' do - pp = <<-EOS + pp75 = <<-EOS class { '::firewall': } firewall { '582 - test': ensure => present, @@ -1871,16 +1794,16 @@ describe 'firewall basics', docker: true do action => accept, pkttype => 'test', } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/Invalid value "test"./) + EOS + it 'applies' do + apply_manifest(pp75, expect_failures: true) do |r| + expect(r.stderr).to match(%r{Invalid value "test".}) end end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m multiport --ports 582 -m pkttype --pkt-type multicast -m comment --comment "582 - test" -j ACCEPT/) + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m multiport --ports 582 -m pkttype --pkt-type multicast -m comment --comment "582 - test" -j ACCEPT}) end end end @@ -1888,8 +1811,7 @@ describe 'firewall basics', docker: true do describe 'isfragment' do context 'true' do - it 'applies' do - pp = <<-EOS + pp76 = <<-EOS class { '::firewall': } firewall { '583 - test': ensure => present, @@ -1898,21 +1820,20 @@ describe 'firewall basics', docker: true do action => accept, isfragment => true, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp76, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -f -m multiport --ports 583 -m comment --comment "583 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -f -m multiport --ports 583 -m comment --comment "583 - test" -j ACCEPT}) end end end context 'false' do - it 'applies' do - pp = <<-EOS + pp77 = <<-EOS class { '::firewall': } firewall { '584 - test': ensure => present, @@ -1921,24 +1842,23 @@ describe 'firewall basics', docker: true do action => accept, isfragment => false, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp77, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m multiport --ports 584 -m comment --comment "584 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m multiport --ports 584 -m comment --comment "584 - test" -j ACCEPT}) end end end end # RHEL5/SLES does not support -m socket - describe 'socket', :unless => (default['platform'] =~ /el-5/ or fact('operatingsystem') == 'SLES') do + describe 'socket', unless: (default['platform'] =~ %r{el-5} || fact('operatingsystem') == 'SLES') do context 'true' do - it 'applies' do - pp = <<-EOS + pp78 = <<-EOS class { '::firewall': } firewall { '585 - test': ensure => present, @@ -1949,21 +1869,20 @@ describe 'firewall basics', docker: true do table => 'nat', socket => true, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp78, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t nat') do |r| - expect(r.stdout).to match(/-A PREROUTING -p tcp -m multiport --ports 585 -m socket -m comment --comment "585 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A PREROUTING -p tcp -m multiport --ports 585 -m socket -m comment --comment "585 - test" -j ACCEPT}) end end end context 'false' do - it 'applies' do - pp = <<-EOS + pp79 = <<-EOS class { '::firewall': } firewall { '586 - test': ensure => present, @@ -1974,14 +1893,14 @@ describe 'firewall basics', docker: true do table => 'nat', socket => false, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp79, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t nat') do |r| - expect(r.stdout).to match(/-A PREROUTING -p tcp -m multiport --ports 586 -m comment --comment "586 - test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A PREROUTING -p tcp -m multiport --ports 586 -m comment --comment "586 - test" -j ACCEPT}) end end end @@ -1989,8 +1908,7 @@ describe 'firewall basics', docker: true do describe 'ipsec_policy' do context 'ipsec' do - it 'applies' do - pp = <<-EOS + pp80 = <<-EOS class { '::firewall': } firewall { '593 - test': ensure => 'present', @@ -2003,21 +1921,20 @@ describe 'firewall basics', docker: true do reject => 'icmp-net-unreachable', table => 'filter', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp80, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -d 20.0.0.0\/(8|255\.0\.0\.0) -m policy --dir out --pol ipsec -m comment --comment "593 - test" -j REJECT --reject-with icmp-net-unreachable/) + expect(r.stdout).to match(%r{-A OUTPUT -d 20.0.0.0\/(8|255\.0\.0\.0) -m policy --dir out --pol ipsec -m comment --comment "593 - test" -j REJECT --reject-with icmp-net-unreachable}) end end end context 'none' do - it 'applies' do - pp = <<-EOS + pp81 = <<-EOS class { '::firewall': } firewall { '594 - test': ensure => 'present', @@ -2030,14 +1947,14 @@ describe 'firewall basics', docker: true do reject => 'icmp-net-unreachable', table => 'filter', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp81, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -d 20.0.0.0\/(8|255\.0\.0\.0) -m policy --dir out --pol none -m comment --comment "594 - test" -j REJECT --reject-with icmp-net-unreachable/) + expect(r.stdout).to match(%r{-A OUTPUT -d 20.0.0.0\/(8|255\.0\.0\.0) -m policy --dir out --pol none -m comment --comment "594 - test" -j REJECT --reject-with icmp-net-unreachable}) end end end @@ -2045,8 +1962,7 @@ describe 'firewall basics', docker: true do describe 'ipsec_dir' do context 'out' do - it 'applies' do - pp = <<-EOS + pp82 = <<-EOS class { '::firewall': } firewall { '595 - test': ensure => 'present', @@ -2059,21 +1975,20 @@ describe 'firewall basics', docker: true do reject => 'icmp-net-unreachable', table => 'filter', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp82, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -d 20.0.0.0\/(8|255\.0\.0\.0) -m policy --dir out --pol ipsec -m comment --comment "595 - test" -j REJECT --reject-with icmp-net-unreachable/) + expect(r.stdout).to match(%r{-A OUTPUT -d 20.0.0.0\/(8|255\.0\.0\.0) -m policy --dir out --pol ipsec -m comment --comment "595 - test" -j REJECT --reject-with icmp-net-unreachable}) end end end context 'in' do - it 'applies' do - pp = <<-EOS + pp83 = <<-EOS class { '::firewall': } firewall { '596 - test': ensure => 'present', @@ -2086,14 +2001,14 @@ describe 'firewall basics', docker: true do reject => 'icmp-net-unreachable', table => 'filter', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp83, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -d 20.0.0.0\/(8|255\.0\.0\.0) -m policy --dir in --pol none -m comment --comment "596 - test" -j REJECT --reject-with icmp-net-unreachable/) + expect(r.stdout).to match(%r{-A INPUT -d 20.0.0.0\/(8|255\.0\.0\.0) -m policy --dir in --pol none -m comment --comment "596 - test" -j REJECT --reject-with icmp-net-unreachable}) end end end @@ -2101,8 +2016,7 @@ describe 'firewall basics', docker: true do describe 'recent' do context 'set' do - it 'applies' do - pp = <<-EOS + pp84 = <<-EOS class { '::firewall': } firewall { '597 - test': ensure => 'present', @@ -2114,22 +2028,21 @@ describe 'firewall basics', docker: true do rdest => true, rname => 'list1', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp84, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| # Mask added as of Ubuntu 14.04. - expect(r.stdout).to match(/-A INPUT -d 30.0.0.0\/(8|255\.0\.0\.0) -m recent --set --name list1 (--mask 255.255.255.255 )?--rdest -m comment --comment "597 - test"/) + expect(r.stdout).to match(%r{-A INPUT -d 30.0.0.0\/(8|255\.0\.0\.0) -m recent --set --name list1 (--mask 255.255.255.255 )?--rdest -m comment --comment "597 - test"}) end end end context 'rcheck' do - it 'applies' do - pp = <<-EOS + pp85 = <<-EOS class { '::firewall': } firewall { '598 - test': ensure => 'present', @@ -2144,21 +2057,20 @@ describe 'firewall basics', docker: true do rhitcount => 5, rttl => true, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp85, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -d 30.0.0.0\/(8|255\.0\.0\.0) -m recent --rcheck --seconds 60 --hitcount 5 --rttl --name list1 (--mask 255.255.255.255 )?--rsource -m comment --comment "598 - test"/) + expect(r.stdout).to match(%r{-A INPUT -d 30.0.0.0\/(8|255\.0\.0\.0) -m recent --rcheck --seconds 60 --hitcount 5 --rttl --name list1 (--mask 255.255.255.255 )?--rsource -m comment --comment "598 - test"}) # rubocop:disable Metrics/LineLength : Cannot reduce line to required length end end end context 'update' do - it 'applies' do - pp = <<-EOS + pp86 = <<-EOS class { '::firewall': } firewall { '599 - test': ensure => 'present', @@ -2168,21 +2080,20 @@ describe 'firewall basics', docker: true do table => 'filter', recent => 'update', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp86, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -d 30.0.0.0\/(8|255\.0\.0\.0) -m recent --update --name DEFAULT (--mask 255.255.255.255 )?--rsource -m comment --comment "599 - test"/) + expect(r.stdout).to match(%r{-A INPUT -d 30.0.0.0\/(8|255\.0\.0\.0) -m recent --update --name DEFAULT (--mask 255.255.255.255 )?--rsource -m comment --comment "599 - test"}) end end end context 'remove' do - it 'applies' do - pp = <<-EOS + pp87 = <<-EOS class { '::firewall': } firewall { '600 - test': ensure => 'present', @@ -2192,14 +2103,14 @@ describe 'firewall basics', docker: true do table => 'filter', recent => 'remove', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp87, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -d 30.0.0.0\/(8|255\.0\.0\.0) -m recent --remove --name DEFAULT (--mask 255.255.255.255 )?--rsource -m comment --comment "600 - test"/) + expect(r.stdout).to match(%r{-A INPUT -d 30.0.0.0\/(8|255\.0\.0\.0) -m recent --remove --name DEFAULT (--mask 255.255.255.255 )?--rsource -m comment --comment "600 - test"}) end end end @@ -2207,8 +2118,7 @@ describe 'firewall basics', docker: true do describe 'mac_source' do context '0A:1B:3C:4D:5E:6F' do - it 'applies' do - pp = <<-EOS + pp88 = <<-EOS class { '::firewall': } firewall { '610 - test': ensure => present, @@ -2216,20 +2126,21 @@ describe 'firewall basics', docker: true do mac_source => '0A:1B:3C:4D:5E:6F', chain => 'INPUT', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp88, catch_failures: true) end - - it 'should contain the rule' do + # rubocop:disable RSpec/ExampleLength : Cannot reduce lines to required size + it 'contains the rule' do # rubocop:disable RSpec/MultipleExpectations : Second expectation required shell('iptables-save') do |r| - if (fact('osfamily') == 'RedHat' and fact('operatingsystemmajrelease') == '5') or (default['platform'] =~ /sles-10/) - expect(r.stdout).to match(/-A INPUT -s 10.1.5.28 -p tcp -m mac --mac-source 0A:1B:3C:4D:5E:6F -m comment --comment "610 - test"/) + if (fact('osfamily') == 'RedHat' && fact('operatingsystemmajrelease') == '5') || (default['platform'] =~ %r{sles-10}) + expect(r.stdout).to match(%r{-A INPUT -s 10.1.5.28 -p tcp -m mac --mac-source 0A:1B:3C:4D:5E:6F -m comment --comment "610 - test"}) else - expect(r.stdout).to match(/-A INPUT -s 10.1.5.28\/(32|255\.255\.255\.255) -p tcp -m mac --mac-source 0A:1B:3C:4D:5E:6F -m comment --comment "610 - test"/) + expect(r.stdout).to match(%r{-A INPUT -s 10.1.5.28\/(32|255\.255\.255\.255) -p tcp -m mac --mac-source 0A:1B:3C:4D:5E:6F -m comment --comment "610 - test"}) end end end + # rubocop:enable RSpec/ExampleLength : Cannot reduce lines to required size end end @@ -2242,8 +2153,7 @@ describe 'firewall basics', docker: true do describe 'to' do context 'Destination netmap 192.168.1.1' do - it 'applies' do - pp = <<-EOS + pp89 = <<-EOS class { '::firewall': } firewall { '569 - test': proto => tcp, @@ -2253,28 +2163,27 @@ describe 'firewall basics', docker: true do source => '200.200.200.200', to => '192.168.1.1', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp89, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t nat') do |r| - expect(r.stdout).to match(/-A PREROUTING -s 200.200.200.200(\/32)? -p tcp -m comment --comment "569 - test" -j NETMAP --to 192.168.1.1/) + expect(r.stdout).to match(%r{-A PREROUTING -s 200.200.200.200(\/32)? -p tcp -m comment --comment "569 - test" -j NETMAP --to 192.168.1.1}) end end end - describe 'reset' do - it 'deletes all rules' do - shell('ip6tables --flush') - shell('iptables --flush; iptables -t nat --flush; iptables -t mangle --flush') - end - end + describe 'reset' do + it 'deletes all rules' do + shell('ip6tables --flush') + shell('iptables --flush; iptables -t nat --flush; iptables -t mangle --flush') + end + end context 'Source netmap 192.168.1.1' do - it 'applies' do - pp = <<-EOS + pp90 = <<-EOS class { '::firewall': } firewall { '569 - test': proto => tcp, @@ -2284,80 +2193,76 @@ describe 'firewall basics', docker: true do destination => '200.200.200.200', to => '192.168.1.1', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp90, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t nat') do |r| - expect(r.stdout).to match(/-A POSTROUTING -d 200.200.200.200(\/32)? -p tcp -m comment --comment "569 - test" -j NETMAP --to 192.168.1.1/) + expect(r.stdout).to match(%r{-A POSTROUTING -d 200.200.200.200(\/32)? -p tcp -m comment --comment "569 - test" -j NETMAP --to 192.168.1.1}) end end end end context 'log_prefix containing -A' do - it 'adds the rule' do - pp = <<-EOS + pp91 = <<-EOS class { '::firewall': } firewall { '700 - test': jump => 'LOG', log_prefix => 'FW-A-INPUT: ', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'adds the rule' do + apply_manifest(pp91, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m comment --comment "700 - test" -j LOG --log-prefix "FW-A-INPUT: "/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m comment --comment "700 - test" -j LOG --log-prefix "FW-A-INPUT: "}) end end - it 'removes the rule' do - pp = <<-EOS + pp92 = <<-EOS class { '::firewall': } firewall { '700 - test': ensure => absent, jump => 'LOG', log_prefix => 'FW-A-INPUT: ', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'removes the rule' do + apply_manifest(pp92, catch_failures: true) end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m comment --comment "700 - test" -j LOG --log-prefix "FW-A-INPUT: "/) + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m comment --comment "700 - test" -j LOG --log-prefix "FW-A-INPUT: "}) end end end context 'log_uid is true' do - it 'adds the rule' do - pp = <<-EOS + pp93 = <<-EOS class { '::firewall': } firewall { '700 - test log_uid': chain => 'OUTPUT', jump => 'LOG', log_uid => true, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'adds the rule' do + apply_manifest(pp93, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m comment --comment "700 - test log_uid" -j LOG --log-uid/) + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m comment --comment "700 - test log_uid" -j LOG --log-uid}) end end - it 'removes the rule' do - pp = <<-EOS + pp94 = <<-EOS class { '::firewall': } firewall { '700 - test log_uid': chain => 'OUTPUT', @@ -2365,56 +2270,52 @@ describe 'firewall basics', docker: true do log_uid => false, ensure => absent, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'removes the rule' do + apply_manifest(pp94, catch_failures: true) end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A OUTPUT -p tcp -m comment --comment "700 - test log_uid" -j --log-uid/) + expect(r.stdout).not_to match(%r{-A OUTPUT -p tcp -m comment --comment "700 - test log_uid" -j --log-uid}) end end end context 'comment containing "-A "' do - it 'adds the rule' do - pp = <<-EOS + pp95 = <<-EOS class { '::firewall': } firewall { '700 - blah-A Test Rule': jump => 'LOG', log_prefix => 'FW-A-INPUT: ', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'adds the rule' do + apply_manifest(pp95, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m comment --comment "700 - blah-A Test Rule" -j LOG --log-prefix "FW-A-INPUT: "/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m comment --comment "700 - blah-A Test Rule" -j LOG --log-prefix "FW-A-INPUT: "}) end end - it 'removes the rule' do - pp = <<-EOS + pp96 = <<-EOS class { '::firewall': } firewall { '700 - blah-A Test Rule': ensure => absent, jump => 'LOG', log_prefix => 'FW-A-INPUT: ', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'removes the rule' do + apply_manifest(pp96, catch_failures: true) end - it 'should not contain the rule' do + it 'does not contain the rule' do shell('iptables-save') do |r| - expect(r.stdout).to_not match(/-A INPUT -p tcp -m comment --comment "700 - blah-A Test Rule" -j LOG --log-prefix "FW-A-INPUT: "/) + expect(r.stdout).not_to match(%r{-A INPUT -p tcp -m comment --comment "700 - blah-A Test Rule" -j LOG --log-prefix "FW-A-INPUT: "}) end end end - - end diff --git a/spec/acceptance/firewall_tee_spec.rb b/spec/acceptance/firewall_tee_spec.rb index da07a28..507fa1d 100644 --- a/spec/acceptance/firewall_tee_spec.rb +++ b/spec/acceptance/firewall_tee_spec.rb @@ -6,11 +6,10 @@ describe 'firewall tee' do ip6tables_flush_all_tables end - if default['platform'] =~ /ubuntu-1404/ or default['platform'] =~ /ubuntu-1204/ or default['platform'] =~ /debian-7/ or default['platform'] =~ /debian-8/ or default['platform'] =~ /el-7/ + if default['platform'] =~ %r{ubuntu-1404} || default['platform'] =~ %r{ubuntu-1204} || default['platform'] =~ %r{debian-7} || default['platform'] =~ %r{debian-8} || default['platform'] =~ %r{el-7} describe 'tee_gateway' do context '10.0.0.2' do - it 'applies' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '810 - tee_gateway': @@ -20,14 +19,14 @@ describe 'firewall tee' do gateway => '10.0.0.2', proto => all, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save -t mangle') do |r| - expect(r.stdout).to match(/-A PREROUTING -m comment --comment "810 - tee_gateway" -j TEE --gateway 10.0.0.2/) + expect(r.stdout).to match(%r{-A PREROUTING -m comment --comment "810 - tee_gateway" -j TEE --gateway 10.0.0.2}) end end end @@ -35,8 +34,7 @@ describe 'firewall tee' do describe 'tee_gateway6' do context '2001:db8::1' do - it 'applies' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '811 - tee_gateway6': @@ -47,18 +45,17 @@ describe 'firewall tee' do proto => all, provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp2, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save -t mangle') do |r| - expect(r.stdout).to match(/-A PREROUTING -m comment --comment "811 - tee_gateway6" -j TEE --gateway 2001:db8::1/) + expect(r.stdout).to match(%r{-A PREROUTING -m comment --comment "811 - tee_gateway6" -j TEE --gateway 2001:db8::1}) end end end end end - end diff --git a/spec/acceptance/firewall_time_spec.rb b/spec/acceptance/firewall_time_spec.rb index 5b2ed37..1cb0482 100644 --- a/spec/acceptance/firewall_time_spec.rb +++ b/spec/acceptance/firewall_time_spec.rb @@ -6,11 +6,10 @@ describe 'firewall time' do ip6tables_flush_all_tables end - if default['platform'] =~ /ubuntu-1404/ or default['platform'] =~ /debian-7/ or default['platform'] =~ /debian-8/ or default['platform'] =~ /el-7/ - describe "time tests ipv4" do + if default['platform'] =~ %r{ubuntu-1404} || default['platform'] =~ %r{debian-7} || default['platform'] =~ %r{debian-8} || default['platform'] =~ %r{el-7} + describe 'time tests ipv4' do context 'set all time parameters' do - it 'applies' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '805 - test': proto => tcp, @@ -25,24 +24,23 @@ describe 'firewall time' do week_days => 'Tue', kernel_timezone => true, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) + apply_manifest(pp1, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m multiport --dports 8080 -m time --timestart 06:00:00 --timestop 17:00:00 --monthdays 7 --weekdays Tue --datestart 2016-01-19T04:17:07 --datestop 2038-01-19T04:17:07 --kerneltz -m comment --comment "805 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m multiport --dports 8080 -m time --timestart 06:00:00 --timestop 17:00:00 --monthdays 7 --weekdays Tue --datestart 2016-01-19T04:17:07 --datestop 2038-01-19T04:17:07 --kerneltz -m comment --comment "805 - test" -j ACCEPT}) # rubocop:disable Metrics/LineLength : Cannot reduce line length to the required size + end end end end - describe "time tests ipv6" do + describe 'time tests ipv6' do context 'set all time parameters' do - it 'applies' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '805 - test': proto => tcp, @@ -58,16 +56,16 @@ describe 'firewall time' do kernel_timezone => true, provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp2, catch_failures: true) + apply_manifest(pp2, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -p tcp -m multiport --dports 8080 -m time --timestart 06:00:00 --timestop 17:00:00 --monthdays 7 --weekdays Tue --datestart 2016-01-19T04:17:07 --datestop 2038-01-19T04:17:07 --kerneltz -m comment --comment "805 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('ip6tables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -p tcp -m multiport --dports 8080 -m time --timestart 06:00:00 --timestop 17:00:00 --monthdays 7 --weekdays Tue --datestart 2016-01-19T04:17:07 --datestop 2038-01-19T04:17:07 --kerneltz -m comment --comment "805 - test" -j ACCEPT}) # rubocop:disable Metrics/LineLength : Cannot reduce line length to the required size + end end end end diff --git a/spec/acceptance/firewall_uid_spec.rb b/spec/acceptance/firewall_uid_spec.rb index e4df7f8..5d4ff45 100644 --- a/spec/acceptance/firewall_uid_spec.rb +++ b/spec/acceptance/firewall_uid_spec.rb @@ -6,10 +6,9 @@ describe 'firewall uid' do ip6tables_flush_all_tables end - describe "uid tests" do + describe 'uid tests' do context 'uid set to root' do - it 'applies' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '801 - test': chain => 'OUTPUT', @@ -17,22 +16,21 @@ describe 'firewall uid' do uid => 'root', proto => 'all', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) + apply_manifest(pp1, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -m owner --uid-owner (0|root) -m comment --comment "801 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -m owner --uid-owner (0|root) -m comment --comment "801 - test" -j ACCEPT}) + end end end context 'uid set to !root' do - it 'applies' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '802 - test': chain => 'OUTPUT', @@ -40,22 +38,21 @@ describe 'firewall uid' do uid => '!root', proto => 'all', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp2, catch_failures: true) + apply_manifest(pp2, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -m owner ! --uid-owner (0|root) -m comment --comment "802 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -m owner ! --uid-owner (0|root) -m comment --comment "802 - test" -j ACCEPT}) + end end end context 'uid set to 0' do - it 'applies' do - pp = <<-EOS + pp3 = <<-EOS class { '::firewall': } firewall { '803 - test': chain => 'OUTPUT', @@ -63,22 +60,21 @@ describe 'firewall uid' do uid => '0', proto => 'all', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp3, catch_failures: true) + apply_manifest(pp3, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -m owner --uid-owner (0|root) -m comment --comment "803 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -m owner --uid-owner (0|root) -m comment --comment "803 - test" -j ACCEPT}) + end end end context 'uid set to !0' do - it 'applies' do - pp = <<-EOS + pp4 = <<-EOS class { '::firewall': } firewall { '804 - test': chain => 'OUTPUT', @@ -86,19 +82,17 @@ describe 'firewall uid' do uid => '!0', proto => 'all', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp4, catch_failures: true) + apply_manifest(pp4, catch_changes: do_catch_changes) end - it 'should contain the rule' do - shell('iptables-save') do |r| - expect(r.stdout).to match(/-A OUTPUT -m owner ! --uid-owner (0|root) -m comment --comment "804 - test" -j ACCEPT/) - end + it 'contains the rule' do + shell('iptables-save') do |r| + expect(r.stdout).to match(%r{-A OUTPUT -m owner ! --uid-owner (0|root) -m comment --comment "804 - test" -j ACCEPT}) + end end end - end - end diff --git a/spec/acceptance/firewallchain_spec.rb b/spec/acceptance/firewallchain_spec.rb index ffc4e22..4b618c0 100644 --- a/spec/acceptance/firewallchain_spec.rb +++ b/spec/acceptance/firewallchain_spec.rb @@ -8,48 +8,47 @@ describe 'puppet resource firewallchain command' do describe 'ensure' do context 'present' do - it 'applies cleanly' do - pp = <<-EOS + pp1 = <<-EOS firewallchain { 'MY_CHAIN:filter:IPv4': ensure => present, } - EOS + EOS + it 'applies cleanly' do # Run it twice and test for idempotency - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + apply_manifest(pp1, catch_failures: true) + apply_manifest(pp1, catch_changes: do_catch_changes) end it 'finds the chain' do shell('iptables-save') do |r| - expect(r.stdout).to match(/MY_CHAIN/) + expect(r.stdout).to match(%r{MY_CHAIN}) end end end context 'absent' do - it 'applies cleanly' do - pp = <<-EOS + pp2 = <<-EOS firewallchain { 'MY_CHAIN:filter:IPv4': ensure => absent, } - EOS + EOS + it 'applies cleanly' do # Run it twice and test for idempotency - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + apply_manifest(pp2, catch_failures: true) + apply_manifest(pp2, catch_changes: do_catch_changes) end it 'fails to find the chain' do shell('iptables-save') do |r| - expect(r.stdout).to_not match(/MY_CHAIN/) + expect(r.stdout).not_to match(%r{MY_CHAIN}) end end end end # XXX purge => false is not yet implemented - #context 'adding a firewall rule to a chain:' do - # it 'applies cleanly' do - # pp = <<-EOS + # context 'adding a firewall rule to a chain:' do + # pp3 = <<-EOS # firewallchain { 'MY_CHAIN:filter:IPv4': # ensure => present, # } @@ -60,15 +59,15 @@ describe 'puppet resource firewallchain command' do # dport => 5000, # } # EOS + # it 'applies cleanly' do # # Run it twice and test for idempotency - # apply_manifest(pp, :catch_failures => true) - # apply_manifest(pp, :catch_changes => do_catch_changes) + # apply_manifest(pp3, :catch_failures => true) + # apply_manifest(pp3, :catch_changes => do_catch_changes) # end - #end + # end - #context 'not purge firewallchain chains:' do - # it 'does not purge the rule' do - # pp = <<-EOS + # context 'not purge firewallchain chains:' do + # pp4 = <<-EOS # firewallchain { 'MY_CHAIN:filter:IPv4': # ensure => present, # purge => false, @@ -78,16 +77,16 @@ describe 'puppet resource firewallchain command' do # purge => true, # } # EOS + # it 'does not purge the rule' do # # Run it twice and test for idempotency - # apply_manifest(pp, :catch_failures => true) do |r| + # apply_manifest(pp4, :catch_failures => true) do |r| # expect(r.stdout).to_not match(/removed/) # expect(r.stderr).to eq('') # end - # apply_manifest(pp, :catch_changes => do_catch_changes) + # apply_manifest(pp4, :catch_changes => do_catch_changes) # end - # it 'still has the rule' do - # pp = <<-EOS + # pp5 = <<-EOS # firewall { '100 my rule': # chain => 'MY_CHAIN', # action => 'accept', @@ -95,10 +94,11 @@ describe 'puppet resource firewallchain command' do # dport => 5000, # } # EOS + # it 'still has the rule' do # # Run it twice and test for idempotency - # apply_manifest(pp, :catch_changes => do_catch_changes) + # apply_manifest(pp5, :catch_changes => do_catch_changes) # end - #end + # end describe 'policy' do after :all do @@ -106,20 +106,20 @@ describe 'puppet resource firewallchain command' do end context 'DROP' do - it 'applies cleanly' do - pp = <<-EOS + pp6 = <<-EOS firewallchain { 'FORWARD:filter:IPv4': policy => 'drop', } - EOS + EOS + it 'applies cleanly' do # Run it twice and test for idempotency - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + apply_manifest(pp6, catch_failures: true) + apply_manifest(pp6, catch_changes: do_catch_changes) end it 'finds the chain' do shell('iptables-save') do |r| - expect(r.stdout).to match(/FORWARD DROP/) + expect(r.stdout).to match(%r{FORWARD DROP}) end end end diff --git a/spec/acceptance/hashlimit_spec.rb b/spec/acceptance/hashlimit_spec.rb index 89b1ff0..97c2187 100644 --- a/spec/acceptance/hashlimit_spec.rb +++ b/spec/acceptance/hashlimit_spec.rb @@ -9,8 +9,7 @@ describe 'hashlimit property', if: fact('operatingsystemmajrelease') != '5' && ( describe 'hashlimit_tests' do context 'hashlimit_above' do - it 'applies' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '800 - hashlimit_above test': chain => 'INPUT', @@ -21,28 +20,25 @@ describe 'hashlimit property', if: fact('operatingsystemmajrelease') != '5' && ( hashlimit_mode => 'srcip,dstip', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) + apply_manifest(pp1, catch_changes: do_catch_changes) end - it 'should contain the rule' do + regex_array = [%r{-A INPUT}, %r{-p tcp}, %r{--hashlimit-above 526\/sec}, %r{--hashlimit-mode srcip,dstip}, + %r{--hashlimit-name above}, %r{--hashlimit-htable-gcinterval 10}, %r{-j ACCEPT}] + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT/) - expect(r.stdout).to match(/-p tcp/) - expect(r.stdout).to match(/--hashlimit-above 526\/sec/) - expect(r.stdout).to match(/--hashlimit-mode srcip,dstip/) - expect(r.stdout).to match(/--hashlimit-name above/) - expect(r.stdout).to match(/--hashlimit-htable-gcinterval 10/) - expect(r.stdout).to match(/-j ACCEPT/) + regex_array.each do |regex| + expect(r.stdout).to match(regex) + end end end end context 'hashlimit_above_ip6' do - it 'applies' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '801 - hashlimit_above test ipv6': chain => 'INPUT', @@ -54,28 +50,25 @@ describe 'hashlimit property', if: fact('operatingsystemmajrelease') != '5' && ( hashlimit_mode => 'srcip,dstip', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp2, catch_failures: true) + apply_manifest(pp2, catch_changes: do_catch_changes) end - it 'should contain the rule' do + regex_array = [%r{-A INPUT}, %r{-p tcp}, %r{--hashlimit-above 526\/sec}, %r{--hashlimit-mode srcip,dstip}, + %r{--hashlimit-name above-ip6}, %r{--hashlimit-htable-gcinterval 10}, %r{-j ACCEPT}] + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT/) - expect(r.stdout).to match(/-p tcp/) - expect(r.stdout).to match(/--hashlimit-above 526\/sec/) - expect(r.stdout).to match(/--hashlimit-mode srcip,dstip/) - expect(r.stdout).to match(/--hashlimit-name above-ip6/) - expect(r.stdout).to match(/--hashlimit-htable-gcinterval 10/) - expect(r.stdout).to match(/-j ACCEPT/) + regex_array.each do |regex| + expect(r.stdout).to match(regex) + end end end end context 'hashlimit_upto' do - it 'applies' do - pp = <<-EOS + pp3 = <<-EOS class { '::firewall': } firewall { '802 - hashlimit_upto test': chain => 'INPUT', @@ -87,22 +80,21 @@ describe 'hashlimit property', if: fact('operatingsystemmajrelease') != '5' && ( hashlimit_htable_expire => '36000000', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp3, catch_failures: true) + apply_manifest(pp3, catch_changes: do_catch_changes) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m hashlimit --hashlimit-upto 16\/sec --hashlimit-burst 640 --hashlimit-name upto --hashlimit-htable-size 1310000 --hashlimit-htable-max 320000 --hashlimit-htable-expire 36000000 -m comment --comment "802 - hashlimit_upto test" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m hashlimit --hashlimit-upto 16\/sec --hashlimit-burst 640 --hashlimit-name upto --hashlimit-htable-size 1310000 --hashlimit-htable-max 320000 --hashlimit-htable-expire 36000000 -m comment --comment "802 - hashlimit_upto test" -j ACCEPT}) # rubocop:disable Metrics/LineLength : Cannot reduce line to required length end end end context 'hashlimit_upto_ip6' do - it 'applies' do - pp = <<-EOS + pp4 = <<-EOS class { '::firewall': } firewall { '803 - hashlimit_upto test ip6': chain => 'INPUT', @@ -115,19 +107,17 @@ describe 'hashlimit property', if: fact('operatingsystemmajrelease') != '5' && ( hashlimit_htable_expire => '36000000', action => accept, } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp4, catch_failures: true) + apply_manifest(pp4, catch_changes: do_catch_changes) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -p tcp -m hashlimit --hashlimit-upto 16\/sec --hashlimit-burst 640 --hashlimit-name upto-ip6 --hashlimit-htable-size 1310000 --hashlimit-htable-max 320000 --hashlimit-htable-expire 36000000 -m comment --comment "803 - hashlimit_upto test ip6" -j ACCEPT/) + expect(r.stdout).to match(%r{-A INPUT -p tcp -m hashlimit --hashlimit-upto 16\/sec --hashlimit-burst 640 --hashlimit-name upto-ip6 --hashlimit-htable-size 1310000 --hashlimit-htable-max 320000 --hashlimit-htable-expire 36000000 -m comment --comment "803 - hashlimit_upto test ip6" -j ACCEPT}) # rubocop:disable Metrics/LineLength : Cannot reduce line to required length end end end - end - end diff --git a/spec/acceptance/invert_spec.rb b/spec/acceptance/invert_spec.rb index 87bffd8..9469139 100644 --- a/spec/acceptance/invert_spec.rb +++ b/spec/acceptance/invert_spec.rb @@ -6,9 +6,8 @@ describe 'firewall inverting' do ip6tables_flush_all_tables end - context "inverting rules" do - it 'applies' do - pp = <<-EOS + context 'inverting rules' do + pp1 = <<-EOS class { '::firewall': } firewall { '601 disallow esp protocol': action => 'accept', @@ -23,25 +22,25 @@ describe 'firewall inverting' do source => '! 10.0.0.0/8', tcp_flags => '! FIN,SYN,RST,ACK SYN', } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) + apply_manifest(pp1, catch_changes: do_catch_changes) end - it 'should contain the rules' do + regex_array = [%r{-A INPUT (-s !|! -s) (10\.0\.0\.0\/8|10\.0\.0\.0\/255\.0\.0\.0).*}, %r{-A INPUT.*(--sports !|! --sports) 80,443.*}, + %r{-A INPUT.*-m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN.*}, %r{-A INPUT.*-j DROP}, + %r{-A INPUT (! -p|-p !) esp -m comment --comment "601 disallow esp protocol" -j ACCEPT}] + it 'contains the rules' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT (-s !|! -s) (10\.0\.0\.0\/8|10\.0\.0\.0\/255\.0\.0\.0).*/) - expect(r.stdout).to match(/-A INPUT.*(--sports !|! --sports) 80,443.*/) - expect(r.stdout).to match(/-A INPUT.*-m tcp ! --tcp-flags FIN,SYN,RST,ACK SYN.*/) - expect(r.stdout).to match(/-A INPUT.*-j DROP/) - expect(r.stdout).to match(/-A INPUT (! -p|-p !) esp -m comment --comment "601 disallow esp protocol" -j ACCEPT/) + regex_array.each do |regex| + expect(r.stdout).to match(regex) + end end end end - context "inverting partial array rules" do - it 'raises a failure' do - pp = <<-EOS + context 'inverting partial array rules' do + pp2 = <<-EOS class { '::firewall': } firewall { '603 drop 80,443 traffic': chain => 'INPUT', @@ -49,10 +48,10 @@ describe 'firewall inverting' do proto => 'tcp', sport => ['! http', '443'], } - EOS - - apply_manifest(pp, :expect_failures => true) do |r| - expect(r.stderr).to match(/is not prefixed/) + EOS + it 'raises a failure' do + apply_manifest(pp2, expect_failures: true) do |r| + expect(r.stderr).to match(%r{is not prefixed}) end end end diff --git a/spec/acceptance/ip6_fragment_spec.rb b/spec/acceptance/ip6_fragment_spec.rb index ed2256f..19642e0 100644 --- a/spec/acceptance/ip6_fragment_spec.rb +++ b/spec/acceptance/ip6_fragment_spec.rb @@ -1,22 +1,22 @@ require 'spec_helper_acceptance' -if default['platform'] =~ /el-5/ or default['platform'] =~ /sles-10/ +if default['platform'] =~ %r{el-5} || default['platform'] =~ %r{sles-10} describe "firewall ip6tables doesn't work on 1.3.5 because --comment is missing" do before :all do iptables_flush_all_tables ip6tables_flush_all_tables end - it "can't use ip6tables" do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '599 - test': ensure => present, proto => 'tcp', provider => 'ip6tables', } - EOS - expect(apply_manifest(pp, :expect_failures => true).stderr).to match(/ip6tables provider is not supported/) + EOS + it "can't use ip6tables" do + expect(apply_manifest(pp1, expect_failures: true).stderr).to match(%r{ip6tables provider is not supported}) end end else @@ -26,9 +26,8 @@ else ip6tables_flush_all_tables end - shared_examples "is idempotent" do |values, line_match| - it "changes the values to #{values}" do - pp = <<-EOS + shared_examples 'is idempotent' do |values, line_match| + pp2 = <<-EOS class { '::firewall': } firewall { '599 - test': ensure => present, @@ -36,19 +35,18 @@ else provider => 'ip6tables', #{values} } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it "changes the values to #{values}" do + apply_manifest(pp2, catch_failures: true) + apply_manifest(pp2, catch_changes: do_catch_changes) shell('ip6tables-save') do |r| - expect(r.stdout).to match(/#{line_match}/) + expect(r.stdout).to match(%r{#{line_match}}) end end end shared_examples "doesn't change" do |values, line_match| - it "doesn't change the values to #{values}" do - pp = <<-EOS + pp3 = <<-EOS class { '::firewall': } firewall { '599 - test': ensure => present, @@ -56,12 +54,12 @@ else provider => 'ip6tables', #{values} } - EOS - - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it "doesn't change the values to #{values}" do + apply_manifest(pp3, catch_changes: do_catch_changes) shell('ip6tables-save') do |r| - expect(r.stdout).to match(/#{line_match}/) + expect(r.stdout).to match(%r{#{line_match}}) end end end @@ -71,19 +69,20 @@ else before :all do ip6tables_flush_all_tables end - it_behaves_like 'is idempotent', '', /-A INPUT -p tcp -m comment --comment "599 - test"/ + it_behaves_like 'is idempotent', '', %r{-A INPUT -p tcp -m comment --comment "599 - test"} end context 'when set to true' do before :all do ip6tables_flush_all_tables end - it_behaves_like "is idempotent", 'ishasmorefrags => true, islastfrag => true, isfirstfrag => true', /-A INPUT -p tcp -m frag --fragid 0 --fragmore -m frag --fragid 0 --fraglast -m frag --fragid 0 --fragfirst -m comment --comment "599 - test"/ + it_behaves_like 'is idempotent', 'ishasmorefrags => true, islastfrag => true, isfirstfrag => true', + %r{-A INPUT -p tcp -m frag --fragid 0 --fragmore -m frag --fragid 0 --fraglast -m frag --fragid 0 --fragfirst -m comment --comment "599 - test"} end context 'when set to false' do before :all do ip6tables_flush_all_tables end - it_behaves_like "is idempotent", 'ishasmorefrags => false, islastfrag => false, isfirstfrag => false', /-A INPUT -p tcp -m comment --comment "599 - test"/ + it_behaves_like 'is idempotent', 'ishasmorefrags => false, islastfrag => false, isfirstfrag => false', %r{-A INPUT -p tcp -m comment --comment "599 - test"} end end describe 'editing a rule' do @@ -93,10 +92,11 @@ else shell('ip6tables -A INPUT -p tcp -m comment --comment "599 - test"') end context 'and current value is false' do - it_behaves_like "doesn't change", 'ishasmorefrags => false, islastfrag => false, isfirstfrag => false', /-A INPUT -p tcp -m comment --comment "599 - test"/ + it_behaves_like "doesn't change", 'ishasmorefrags => false, islastfrag => false, isfirstfrag => false', %r{-A INPUT -p tcp -m comment --comment "599 - test"} end context 'and current value is true' do - it_behaves_like "is idempotent", 'ishasmorefrags => true, islastfrag => true, isfirstfrag => true', /-A INPUT -p tcp -m frag --fragid 0 --fragmore -m frag --fragid 0 --fraglast -m frag --fragid 0 --fragfirst -m comment --comment "599 - test"/ + it_behaves_like 'is idempotent', 'ishasmorefrags => true, islastfrag => true, isfirstfrag => true', + %r{-A INPUT -p tcp -m frag --fragid 0 --fragmore -m frag --fragid 0 --fraglast -m frag --fragid 0 --fragfirst -m comment --comment "599 - test"} end end context 'when set to true' do @@ -105,10 +105,11 @@ else shell('ip6tables -A INPUT -p tcp -m frag --fragid 0 --fragmore -m frag --fragid 0 --fraglast -m frag --fragid 0 --fragfirst -m comment --comment "599 - test"') end context 'and current value is false' do - it_behaves_like "is idempotent", 'ishasmorefrags => false, islastfrag => false, isfirstfrag => false', /-A INPUT -p tcp -m comment --comment "599 - test"/ + it_behaves_like 'is idempotent', 'ishasmorefrags => false, islastfrag => false, isfirstfrag => false', %r{-A INPUT -p tcp -m comment --comment "599 - test"} end context 'and current value is true' do - it_behaves_like "doesn't change", 'ishasmorefrags => true, islastfrag => true, isfirstfrag => true', /-A INPUT -p tcp -m frag --fragid 0 --fragmore -m frag --fragid 0 --fraglast -m frag --fragid 0 --fragfirst -m comment --comment "599 - test"/ + it_behaves_like "doesn't change", 'ishasmorefrags => true, islastfrag => true, isfirstfrag => true', + %r{-A INPUT -p tcp -m frag --fragid 0 --fragmore -m frag --fragid 0 --fraglast -m frag --fragid 0 --fragfirst -m comment --comment "599 - test"} end end end diff --git a/spec/acceptance/isfragment_spec.rb b/spec/acceptance/isfragment_spec.rb index 8e879b2..38afcdc 100644 --- a/spec/acceptance/isfragment_spec.rb +++ b/spec/acceptance/isfragment_spec.rb @@ -6,40 +6,39 @@ describe 'firewall isfragment property' do ip6tables_flush_all_tables end - shared_examples "is idempotent" do |value, line_match| - it "changes the value to #{value}" do - pp = <<-EOS + shared_examples 'is idempotent' do |value, line_match| + pp1 = <<-EOS class { '::firewall': } firewall { '597 - test': ensure => present, proto => 'tcp', #{value} } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it "changes the value to #{value}" do + apply_manifest(pp1, catch_failures: true) + apply_manifest(pp1, catch_changes: do_catch_changes) shell('iptables-save') do |r| - expect(r.stdout).to match(/#{line_match}/) + expect(r.stdout).to match(%r{#{line_match}}) end end end + shared_examples "doesn't change" do |value, line_match| - it "doesn't change the value to #{value}" do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '597 - test': ensure => present, proto => 'tcp', #{value} } - EOS - - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it "doesn't change the value to #{value}" do + apply_manifest(pp2, catch_changes: do_catch_changes) shell('iptables-save') do |r| - expect(r.stdout).to match(/#{line_match}/) + expect(r.stdout).to match(%r{#{line_match}}) end end end @@ -49,45 +48,51 @@ describe 'firewall isfragment property' do before :all do iptables_flush_all_tables end - it_behaves_like 'is idempotent', '', /-A INPUT -p tcp -m comment --comment "597 - test"/ + it_behaves_like 'is idempotent', '', %r{-A INPUT -p tcp -m comment --comment "597 - test"} end context 'when set to true' do before :all do iptables_flush_all_tables end - it_behaves_like 'is idempotent', 'isfragment => true,', /-A INPUT -p tcp -f -m comment --comment "597 - test"/ + it_behaves_like 'is idempotent', 'isfragment => true,', %r{-A INPUT -p tcp -f -m comment --comment "597 - test"} end context 'when set to false' do before :all do iptables_flush_all_tables end - it_behaves_like "is idempotent", 'isfragment => false,', /-A INPUT -p tcp -m comment --comment "597 - test"/ + it_behaves_like 'is idempotent', 'isfragment => false,', %r{-A INPUT -p tcp -m comment --comment "597 - test"} end end - describe 'editing a rule' do + + describe 'editing a rule and current value is false' do context 'when unset or false' do before :each do iptables_flush_all_tables shell('iptables -A INPUT -p tcp -m comment --comment "597 - test"') end - context 'and current value is false' do - it_behaves_like "doesn't change", 'isfragment => false,', /-A INPUT -p tcp -m comment --comment "597 - test"/ - end - context 'and current value is true' do - it_behaves_like "is idempotent", 'isfragment => true,', /-A INPUT -p tcp -f -m comment --comment "597 - test"/ + it_behaves_like "doesn't change", 'isfragment => false,', %r{-A INPUT -p tcp -m comment --comment "597 - test"} + end + context 'when unset or false and current value is true' do + before :each do + iptables_flush_all_tables + shell('iptables -A INPUT -p tcp -m comment --comment "597 - test"') end + it_behaves_like 'is idempotent', 'isfragment => true,', %r{-A INPUT -p tcp -f -m comment --comment "597 - test"} end - context 'when set to true' do + + context 'when set to true and current value is false' do before :each do iptables_flush_all_tables shell('iptables -A INPUT -p tcp -f -m comment --comment "597 - test"') end - context 'and current value is false' do - it_behaves_like "is idempotent", 'isfragment => false,', /-A INPUT -p tcp -m comment --comment "597 - test"/ - end - context 'and current value is true' do - it_behaves_like "doesn't change", 'isfragment => true,', /-A INPUT -p tcp -f -m comment --comment "597 - test"/ + it_behaves_like 'is idempotent', 'isfragment => false,', %r{-A INPUT -p tcp -m comment --comment "597 - test"} + end + context 'when set to trueand current value is true' do + before :each do + iptables_flush_all_tables + shell('iptables -A INPUT -p tcp -f -m comment --comment "597 - test"') end + it_behaves_like "doesn't change", 'isfragment => true,', %r{-A INPUT -p tcp -f -m comment --comment "597 - test"} end end end diff --git a/spec/acceptance/match_mark_spec.rb b/spec/acceptance/match_mark_spec.rb index 22abfea..6cf38ec 100644 --- a/spec/acceptance/match_mark_spec.rb +++ b/spec/acceptance/match_mark_spec.rb @@ -6,25 +6,24 @@ describe 'firewall match marks' do ip6tables_flush_all_tables end - if default['platform'] !~ /el-5/ and default['platform'] !~ /sles-10/ + if default['platform'] !~ %r{el-5} && default['platform'] !~ %r{sles-10} describe 'match_mark' do context '0x1' do - it 'applies' do - pp = <<-EOS + pp1 = <<-EOS class { '::firewall': } firewall { '503 match_mark - test': proto => 'all', match_mark => '0x1', action => reject, } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp1, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/-A INPUT -m mark --mark 0x1 -m comment --comment "503 match_mark - test" -j REJECT --reject-with icmp-port-unreachable/) + expect(r.stdout).to match(%r{-A INPUT -m mark --mark 0x1 -m comment --comment "503 match_mark - test" -j REJECT --reject-with icmp-port-unreachable}) end end end @@ -32,8 +31,7 @@ describe 'firewall match marks' do describe 'match_mark_ip6' do context '0x1' do - it 'applies' do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '503 match_mark ip6tables - test': proto => 'all', @@ -41,14 +39,14 @@ describe 'firewall match marks' do action => reject, provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'applies' do + apply_manifest(pp2, catch_failures: true) end - it 'should contain the rule' do + it 'contains the rule' do shell('ip6tables-save') do |r| - expect(r.stdout).to match(/-A INPUT -m mark --mark 0x1 -m comment --comment "503 match_mark ip6tables - test" -j REJECT --reject-with icmp6-port-unreachable/) + expect(r.stdout).to match(%r{-A INPUT -m mark --mark 0x1 -m comment --comment "503 match_mark ip6tables - test" -j REJECT --reject-with icmp6-port-unreachable}) end end end diff --git a/spec/acceptance/nflog_spec.rb b/spec/acceptance/nflog_spec.rb index 45a2bbb..1ec0589 100644 --- a/spec/acceptance/nflog_spec.rb +++ b/spec/acceptance/nflog_spec.rb @@ -1,109 +1,88 @@ require 'spec_helper_acceptance' -describe 'nflog on older OSes', :if => fact('iptables_version') < '1.3.7' do - let(:pp) { <<-EOS - class {'::firewall': } - firewall { '503 - test': - jump => 'NFLOG', - proto => 'all', - nflog_group => 3, - } - EOS - } - it 'should throw an error' do - apply_manifest(pp, :acceptable_error_codes => [0]) +describe 'nflog on older OSes', if: fact('iptables_version') < '1.3.7' do # rubocop:disable RSpec/MultipleDescribes : Describes are clearly seperate + pp1 = <<-EOS + class {'::firewall': } + firewall { '503 - test': + jump => 'NFLOG', + proto => 'all', + nflog_group => 3, + } + EOS + it 'throws an error' do + apply_manifest(pp1, acceptable_error_codes: [0]) end end -describe 'nflog', :unless => fact('iptables_version') < '1.3.7' do +describe 'nflog', unless: fact('iptables_version') < '1.3.7' do describe 'nflog_group' do - let(:group) { 3 } it 'applies' do - pp = <<-EOS + pp2 = <<-EOS class {'::firewall': } - firewall { '503 - test': - jump => 'NFLOG', - proto => 'all', - nflog_group => #{group}, - } + firewall { '503 - test': jump => 'NFLOG', proto => 'all', nflog_group => #{group}} EOS - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp2, catch_failures: true) end it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/NFLOG --nflog-group #{group}/) + expect(r.stdout).to match(%r{NFLOG --nflog-group #{group}}) end end end describe 'nflog_prefix' do - - let(:prefix) { "TEST PREFIX" } + let(:prefix) { 'TEST PREFIX' } it 'applies' do - pp = <<-EOS + pp3 = <<-EOS class {'::firewall': } - firewall { '503 - test': - jump => 'NFLOG', - proto => 'all', - nflog_prefix => '#{prefix}', - } - EOS - apply_manifest(pp, :catch_failures => true) + firewall { '503 - test': jump => 'NFLOG', proto => 'all', nflog_prefix => '#{prefix}'} + EOS + apply_manifest(pp3, catch_failures: true) end it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/NFLOG --nflog-prefix +"#{prefix}"/) + expect(r.stdout).to match(%r{NFLOG --nflog-prefix +"#{prefix}"}) end end end describe 'nflog_range' do - let(:range) { 16 } it 'applies' do - pp = <<-EOS + pp4 = <<-EOS class {'::firewall': } - firewall { '503 - test': - jump => 'NFLOG', - proto => 'all', - nflog_range => #{range}, - } + firewall { '503 - test': jump => 'NFLOG', proto => 'all', nflog_range => #{range}} EOS - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp4, catch_failures: true) end it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/NFLOG --nflog-range #{range}/) + expect(r.stdout).to match(%r{NFLOG --nflog-range #{range}}) end end end describe 'nflog_threshold' do - let(:threshold) { 2 } it 'applies' do - pp = <<-EOS + pp5 = <<-EOS class {'::firewall': } - firewall { '503 - test': - jump => 'NFLOG', - proto => 'all', - nflog_threshold => #{threshold}, - } + firewall { '503 - test': jump => 'NFLOG', proto => 'all', nflog_threshold => #{threshold}} EOS - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp5, catch_failures: true) end it 'contains the rule' do shell('iptables-save') do |r| - expect(r.stdout).to match(/NFLOG --nflog-threshold #{threshold}/) + expect(r.stdout).to match(%r{NFLOG --nflog-threshold #{threshold}}) end end end @@ -113,23 +92,17 @@ describe 'nflog', :unless => fact('iptables_version') < '1.3.7' do let(:group) { 3 } it 'applies' do - pp = <<-EOS + pp6 = <<-EOS class {'::firewall': } - firewall { '503 - test': - jump => 'NFLOG', - proto => 'all', - nflog_threshold => #{threshold}, - nflog_group => #{group} - } + firewall { '503 - test': jump => 'NFLOG', proto => 'all', nflog_threshold => #{threshold}, nflog_group => #{group}} EOS - apply_manifest(pp, :catch_failures => true) + apply_manifest(pp6, catch_failures: true) end it 'contains the rules' do shell('iptables-save') do |r| - expect(r.stdout).to match(/NFLOG --nflog-group #{group} --nflog-threshold #{threshold}/) + expect(r.stdout).to match(%r{NFLOG --nflog-group #{group} --nflog-threshold #{threshold}}) end end - end end diff --git a/spec/acceptance/params_spec.rb b/spec/acceptance/params_spec.rb index cac685a..12dffbb 100644 --- a/spec/acceptance/params_spec.rb +++ b/spec/acceptance/params_spec.rb @@ -6,10 +6,7 @@ describe 'param based tests' do ip6tables_flush_all_tables end - it 'test various params', :unless => (default['platform'].match(/el-5/) || fact('operatingsystem') == 'SLES') do - iptables_flush_all_tables - - ppm = <<-EOS + ppm1 = <<-EOS firewall { '100 test': table => 'raw', socket => 'true', @@ -17,30 +14,33 @@ describe 'param based tests' do jump => 'LOG', log_level => 'debug', } - EOS + EOS + values = [2, 0] + it 'test various params', unless: (default['platform'].match(%r{el-5}) || fact('operatingsystem') == 'SLES') do + iptables_flush_all_tables - expect(apply_manifest(ppm, :catch_failures => true).exit_code).to eq(2) - expect(apply_manifest(ppm, :catch_failures => true).exit_code).to be_zero + values.each do |value| + expect(apply_manifest(ppm1, catch_failures: true).exit_code).to eq(value) + end end - it 'test log rule' do - iptables_flush_all_tables - - ppm = <<-EOS + ppm2 = <<-EOS firewall { '998 log all': proto => 'all', jump => 'LOG', log_level => 'debug', } - EOS - expect(apply_manifest(ppm, :catch_failures => true).exit_code).to eq(2) - expect(apply_manifest(ppm, :catch_failures => true).exit_code).to be_zero - end - - it 'test log rule - changing names' do + EOS + values = [2, 0] + it 'test log rule' do iptables_flush_all_tables - ppm1 = <<-EOS + values.each do |value| + expect(apply_manifest(ppm2, catch_failures: true).exit_code).to eq(value) + end + end + + ppm3 = <<-EOS firewall { '004 log all INVALID packets': chain => 'INPUT', proto => 'all', @@ -49,9 +49,8 @@ describe 'param based tests' do log_level => '3', log_prefix => 'IPTABLES dropped invalid: ', } - EOS - - ppm2 = <<-EOS + EOS + ppm4 = <<-EOS firewall { '003 log all INVALID packets': chain => 'INPUT', proto => 'all', @@ -60,49 +59,44 @@ describe 'param based tests' do log_level => '3', log_prefix => 'IPTABLES dropped invalid: ', } - EOS - - expect(apply_manifest(ppm1, :catch_failures => true).exit_code).to eq(2) - - ppm = <<-EOS + "\n" + ppm2 + EOS + ppm5 = <<-EOS + "\n" + ppm4 resources { 'firewall': purge => true, } - EOS - expect(apply_manifest(ppm, :catch_failures => true).exit_code).to eq(2) - end - - it 'test chain - changing names' do + EOS + it 'test log rule - changing names' do # rubocop:disable RSpec/MultipleExpectations iptables_flush_all_tables - ppm1 = <<-EOS + expect(apply_manifest(ppm3, catch_failures: true).exit_code).to eq(2) + expect(apply_manifest(ppm5, catch_failures: true).exit_code).to eq(2) + end + + ppm6 = <<-EOS firewall { '004 with a chain': chain => 'INPUT', proto => 'all', } - EOS - - ppm2 = <<-EOS + EOS + ppm7 = <<-EOS firewall { '004 with a chain': chain => 'OUTPUT', proto => 'all', } - EOS - - apply_manifest(ppm1, :expect_changes => true) - - ppm = <<-EOS + "\n" + ppm2 + EOS + _ppm8 = <<-EOS + "\n" + ppm7 resources { 'firewall': purge => true, } - EOS - expect(apply_manifest(ppm2, :expect_failures => true).stderr).to match(/is not supported/) - end - - it 'test log rule - idempotent' do + EOS + it 'test chain - changing names' do iptables_flush_all_tables - ppm1 = <<-EOS + apply_manifest(ppm6, expect_changes: true) + expect(apply_manifest(ppm7, expect_failures: true).stderr).to match(%r{is not supported}) + end + + ppm9 = <<-EOS firewall { '004 log all INVALID packets': chain => 'INPUT', proto => 'all', @@ -111,42 +105,47 @@ describe 'param based tests' do log_level => '3', log_prefix => 'IPTABLES dropped invalid: ', } - EOS + EOS + values = [2, 0] + it 'test log rule - idempotent' do + iptables_flush_all_tables - expect(apply_manifest(ppm1, :catch_failures => true).exit_code).to eq(2) - expect(apply_manifest(ppm1, :catch_failures => true).exit_code).to be_zero + values.each do |value| + expect(apply_manifest(ppm9, catch_failures: true).exit_code).to eq(value) + end end - it 'test src_range rule' do - iptables_flush_all_tables - - ppm = <<-EOS + ppm10 = <<-EOS firewall { '997 block src ip range': chain => 'INPUT', proto => 'all', action => 'drop', src_range => '10.0.0.1-10.0.0.10', } - EOS + EOS + values = [2, 0] + it 'test src_range rule' do + iptables_flush_all_tables - expect(apply_manifest(ppm, :catch_failures => true).exit_code).to eq(2) - expect(apply_manifest(ppm, :catch_failures => true).exit_code).to be_zero + values.each do |value| + expect(apply_manifest(ppm10, catch_failures: true).exit_code).to eq(value) + end end - it 'test dst_range rule' do - iptables_flush_all_tables - - ppm = <<-EOS + ppm11 = <<-EOS firewall { '998 block dst ip range': chain => 'INPUT', proto => 'all', action => 'drop', dst_range => '10.0.0.2-10.0.0.20', } - EOS + EOS + values = [2, 0] + it 'test dst_range rule' do + iptables_flush_all_tables - expect(apply_manifest(ppm, :catch_failures => true).exit_code).to eq(2) - expect(apply_manifest(ppm, :catch_failures => true).exit_code).to be_zero + values.each do |value| + expect(apply_manifest(ppm11, catch_failures: true).exit_code).to eq(value) + end end - end diff --git a/spec/acceptance/purge_spec.rb b/spec/acceptance/purge_spec.rb index 4e052ba..47a03ca 100644 --- a/spec/acceptance/purge_spec.rb +++ b/spec/acceptance/purge_spec.rb @@ -14,22 +14,20 @@ describe 'purge tests' do shell('iptables -A INPUT -s 1.2.1.2') end - it 'make sure duplicate existing rules get purged' do - - pp = <<-EOS + pp1 = <<-EOS class { 'firewall': } resources { 'firewall': purge => true, } - EOS - - apply_manifest(pp, :expect_changes => true) + EOS + it 'make sure duplicate existing rules get purged' do + apply_manifest(pp1, expect_changes: true) end - it 'saves' do + it 'saves' do # rubocop:disable RSpec/MultipleExpectations shell('iptables-save') do |r| - expect(r.stdout).to_not match(/1\.2\.1\.2/) - expect(r.stderr).to eq("") + expect(r.stdout).not_to match(%r{1\.2\.1\.2}) + expect(r.stderr).to eq('') end end end @@ -46,25 +44,25 @@ describe 'purge tests' do shell('iptables -A OUTPUT -s 1.2.1.2 -m comment --comment "010 output-1.2.1.2"') end - it 'purges only the specified chain' do - pp = <<-EOS + pp2 = <<-EOS class { 'firewall': } firewallchain { 'INPUT:filter:IPv4': purge => true, } - EOS - - apply_manifest(pp, :expect_changes => true) + EOS + # rubocop:disable RSpec/ExampleLength + it 'purges only the specified chain' do # rubocop:disable RSpec/MultipleExpectations + apply_manifest(pp2, expect_changes: true) shell('iptables-save') do |r| - expect(r.stdout).to match(/010 output-1\.2\.1\.2/) - expect(r.stdout).to_not match(/1\.2\.1\.1/) - expect(r.stderr).to eq("") + expect(r.stdout).to match(%r{010 output-1\.2\.1\.2}) + expect(r.stdout).not_to match(%r{1\.2\.1\.1}) + expect(r.stderr).to eq('') end end + # rubocop:enable RSpec/ExampleLength - it 'ignores managed rules' do - pp = <<-EOS + pp3 = <<-EOS class { 'firewall': } firewallchain { 'OUTPUT:filter:IPv4': purge => true, @@ -74,13 +72,12 @@ describe 'purge tests' do proto => 'all', source => '1.2.1.2', } - EOS - - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'ignores managed rules' do + apply_manifest(pp3, catch_changes: do_catch_changes) end - it 'ignores specified rules' do - pp = <<-EOS + pp4 = <<-EOS class { 'firewall': } firewallchain { 'INPUT:filter:IPv4': purge => true, @@ -88,13 +85,12 @@ describe 'purge tests' do '-s 1\.2\.1\.1', ], } - EOS - - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'ignores specified rules' do + apply_manifest(pp4, catch_changes: do_catch_changes) end - it 'adds managed rules with ignored rules' do - pp = <<-EOS + pp5 = <<-EOS class { 'firewall': } firewallchain { 'INPUT:filter:IPv4': purge => true, @@ -122,15 +118,15 @@ describe 'purge tests' do proto => 'all', source => '1.2.1.3', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'adds managed rules with ignored rules' do + apply_manifest(pp5, catch_failures: true) - expect(shell('iptables-save').stdout).to match(/-A INPUT -s 1\.2\.1\.1(\/32)? -p tcp\s?\n-A INPUT -s 1\.2\.1\.1(\/32)? -p udp/) + expect(shell('iptables-save').stdout).to match(%r{-A INPUT -s 1\.2\.1\.1(\/32)? -p tcp\s?\n-A INPUT -s 1\.2\.1\.1(\/32)? -p udp}) end end - if default['platform'] !~ /el-5/ and default['platform'] !~ /sles-10/ + if default['platform'] !~ %r{el-5} && default['platform'] !~ %r{sles-10} context 'ipv6 chain purge' do after(:all) do ip6tables_flush_all_tables @@ -143,25 +139,25 @@ describe 'purge tests' do shell('ip6tables -A OUTPUT -s 1::50 -m comment --comment "010 output-1::50"') end - it 'purges only the specified chain' do - pp = <<-EOS + pp6 = <<-EOS class { 'firewall': } firewallchain { 'INPUT:filter:IPv6': purge => true, } - EOS - - apply_manifest(pp, :expect_changes => true) + EOS + # rubocop:disable RSpec/ExampleLength + it 'purges only the specified chain' do # rubocop:disable RSpec/MultipleExpectations + apply_manifest(pp6, expect_changes: true) shell('ip6tables-save') do |r| - expect(r.stdout).to match(/010 output-1::50/) - expect(r.stdout).to_not match(/1::42/) - expect(r.stderr).to eq("") + expect(r.stdout).to match(%r{010 output-1::50}) + expect(r.stdout).not_to match(%r{1::42}) + expect(r.stderr).to eq('') end end + # rubocop:enable RSpec/ExampleLength - it 'ignores managed rules' do - pp = <<-EOS + pp7 = <<-EOS class { 'firewall': } firewallchain { 'OUTPUT:filter:IPv6': purge => true, @@ -172,13 +168,12 @@ describe 'purge tests' do source => '1::50', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'ignores managed rules' do + apply_manifest(pp7, catch_changes: do_catch_changes) end - it 'ignores specified rules' do - pp = <<-EOS + pp8 = <<-EOS class { 'firewall': } firewallchain { 'INPUT:filter:IPv6': purge => true, @@ -186,13 +181,12 @@ describe 'purge tests' do '-s 1::42', ], } - EOS - - apply_manifest(pp, :catch_changes => do_catch_changes) + EOS + it 'ignores specified rules' do + apply_manifest(pp8, catch_changes: do_catch_changes) end - it 'adds managed rules with ignored rules' do - pp = <<-EOS + pp9 = <<-EOS class { 'firewall': } firewallchain { 'INPUT:filter:IPv6': purge => true, @@ -224,11 +218,11 @@ describe 'purge tests' do source => '1::43', provider => 'ip6tables', } - EOS - - apply_manifest(pp, :catch_failures => true) + EOS + it 'adds managed rules with ignored rules' do + apply_manifest(pp9, catch_failures: true) - expect(shell('ip6tables-save').stdout).to match(/-A INPUT -s 1::42(\/128)? -p tcp\s?\n-A INPUT -s 1::42(\/128)? -p udp/) + expect(shell('ip6tables-save').stdout).to match(%r{-A INPUT -s 1::42(\/128)? -p tcp\s?\n-A INPUT -s 1::42(\/128)? -p udp}) end end end diff --git a/spec/acceptance/resource_cmd_spec.rb b/spec/acceptance/resource_cmd_spec.rb index 39845fb..df78250 100644 --- a/spec/acceptance/resource_cmd_spec.rb +++ b/spec/acceptance/resource_cmd_spec.rb @@ -96,12 +96,12 @@ describe 'puppet resource firewall command' do end end - if default['platform'] !~ /sles-10/ + if default['platform'] !~ %r{sles-10} context 'accepts rules utilizing the statistic module' do before :all do iptables_flush_all_tables # This command doesn't work with all versions/oses, so let it fail - shell('iptables -t nat -A POSTROUTING -d 1.2.3.4/32 -o eth0 -m statistic --mode nth --every 2 -j SNAT --to-source 2.3.4.5', :acceptable_exit_codes => [0,1,2] ) + shell('iptables -t nat -A POSTROUTING -d 1.2.3.4/32 -o eth0 -m statistic --mode nth --every 2 -j SNAT --to-source 2.3.4.5', acceptable_exit_codes: [0, 1, 2]) shell('iptables -t nat -A POSTROUTING -d 1.2.3.4/32 -o eth0 -m statistic --mode nth --every 1 --packet 0 -j SNAT --to-source 2.3.4.6') shell('iptables -t nat -A POSTROUTING -d 1.2.3.4/32 -o eth0 -m statistic --mode random --probability 0.99 -j SNAT --to-source 2.3.4.7') end @@ -167,7 +167,8 @@ describe 'puppet resource firewall command' do # version of iptables that ships with el5 doesn't work with the # ip6tables provider - if default['platform'] !~ /el-5/ and default['platform'] !~ /sles-10/ + # TODO: Test below fails if this file is run seperately. i.e. bundle exec rspec spec/acceptance/resource_cmd_spec.rb + if default['platform'] !~ %r{el-5} && default['platform'] !~ %r{sles-10} context 'dport/sport with ip6tables' do before :all do if fact('osfamily') == 'Debian' diff --git a/spec/acceptance/rules_spec.rb b/spec/acceptance/rules_spec.rb index 7c2aebb..d0c9e11 100644 --- a/spec/acceptance/rules_spec.rb +++ b/spec/acceptance/rules_spec.rb @@ -1,277 +1,274 @@ require 'spec_helper_acceptance' -describe 'complex ruleset 1' do - before :all do - iptables_flush_all_tables - ip6tables_flush_all_tables - end +describe 'rules spec' do + describe 'complex ruleset 1' do + before :all do + iptables_flush_all_tables + ip6tables_flush_all_tables + end - after :all do - shell('iptables -t filter -P INPUT ACCEPT') - shell('iptables -t filter -P FORWARD ACCEPT') - shell('iptables -t filter -P OUTPUT ACCEPT') - shell('iptables -t filter --flush') - end + after :all do + shell('iptables -t filter -P INPUT ACCEPT') + shell('iptables -t filter -P FORWARD ACCEPT') + shell('iptables -t filter -P OUTPUT ACCEPT') + shell('iptables -t filter --flush') + end - it 'applies cleanly' do - pp = <<-EOS - firewall { '090 forward allow local': - chain => 'FORWARD', - proto => 'all', - source => '10.0.0.0/8', - destination => '10.0.0.0/8', - action => 'accept', - } - firewall { '100 forward standard allow tcp': - chain => 'FORWARD', - source => '10.0.0.0/8', - destination => '!10.0.0.0/8', - proto => 'tcp', - state => 'NEW', - port => [80,443,21,20,22,53,123,43,873,25,465], - action => 'accept', - } - firewall { '100 forward standard allow udp': - chain => 'FORWARD', - source => '10.0.0.0/8', - destination => '!10.0.0.0/8', - proto => 'udp', - port => [53,123], - action => 'accept', - } - firewall { '100 forward standard allow icmp': - chain => 'FORWARD', - source => '10.0.0.0/8', - destination => '!10.0.0.0/8', - proto => 'icmp', - action => 'accept', - } + pp1 = <<-EOS + firewall { '090 forward allow local': + chain => 'FORWARD', + proto => 'all', + source => '10.0.0.0/8', + destination => '10.0.0.0/8', + action => 'accept', + } + firewall { '100 forward standard allow tcp': + chain => 'FORWARD', + source => '10.0.0.0/8', + destination => '!10.0.0.0/8', + proto => 'tcp', + state => 'NEW', + port => [80,443,21,20,22,53,123,43,873,25,465], + action => 'accept', + } + firewall { '100 forward standard allow udp': + chain => 'FORWARD', + source => '10.0.0.0/8', + destination => '!10.0.0.0/8', + proto => 'udp', + port => [53,123], + action => 'accept', + } + firewall { '100 forward standard allow icmp': + chain => 'FORWARD', + source => '10.0.0.0/8', + destination => '!10.0.0.0/8', + proto => 'icmp', + action => 'accept', + } - firewall { '090 ignore ipsec': - table => 'nat', - chain => 'POSTROUTING', - outiface => 'eth0', - ipsec_policy => 'ipsec', - ipsec_dir => 'out', - action => 'accept', - } - firewall { '093 ignore 10.0.0.0/8': - table => 'nat', - chain => 'POSTROUTING', - outiface => 'eth0', - destination => '10.0.0.0/8', - action => 'accept', - } - firewall { '093 ignore 172.16.0.0/12': - table => 'nat', - chain => 'POSTROUTING', - outiface => 'eth0', - destination => '172.16.0.0/12', - action => 'accept', - } - firewall { '093 ignore 192.168.0.0/16': - table => 'nat', - chain => 'POSTROUTING', - outiface => 'eth0', - destination => '192.168.0.0/16', - action => 'accept', - } - firewall { '100 masq outbound': - table => 'nat', - chain => 'POSTROUTING', - outiface => 'eth0', - jump => 'MASQUERADE', - } - firewall { '101 redirect port 1': - table => 'nat', - chain => 'PREROUTING', - iniface => 'eth0', - proto => 'tcp', - dport => '1', - toports => '22', - jump => 'REDIRECT', - } + firewall { '090 ignore ipsec': + table => 'nat', + chain => 'POSTROUTING', + outiface => 'eth0', + ipsec_policy => 'ipsec', + ipsec_dir => 'out', + action => 'accept', + } + firewall { '093 ignore 10.0.0.0/8': + table => 'nat', + chain => 'POSTROUTING', + outiface => 'eth0', + destination => '10.0.0.0/8', + action => 'accept', + } + firewall { '093 ignore 172.16.0.0/12': + table => 'nat', + chain => 'POSTROUTING', + outiface => 'eth0', + destination => '172.16.0.0/12', + action => 'accept', + } + firewall { '093 ignore 192.168.0.0/16': + table => 'nat', + chain => 'POSTROUTING', + outiface => 'eth0', + destination => '192.168.0.0/16', + action => 'accept', + } + firewall { '100 masq outbound': + table => 'nat', + chain => 'POSTROUTING', + outiface => 'eth0', + jump => 'MASQUERADE', + } + firewall { '101 redirect port 1': + table => 'nat', + chain => 'PREROUTING', + iniface => 'eth0', + proto => 'tcp', + dport => '1', + toports => '22', + jump => 'REDIRECT', + } EOS - - # Run it twice and test for idempotency - apply_manifest(pp, :catch_failures => true) - expect(apply_manifest(pp, :catch_failures => true).exit_code).to be_zero - end - - it 'contains appropriate rules' do - shell('iptables-save') do |r| - [ - /INPUT ACCEPT/, - /FORWARD ACCEPT/, - /OUTPUT ACCEPT/, - /-A FORWARD -s 10.0.0.0\/(8|255\.0\.0\.0) -d 10.0.0.0\/(8|255\.0\.0\.0) -m comment --comment \"090 forward allow local\" -j ACCEPT/, - /-A FORWARD -s 10.0.0.0\/(8|255\.0\.0\.0) (! -d|-d !) 10.0.0.0\/(8|255\.0\.0\.0) -p icmp -m comment --comment \"100 forward standard allow icmp\" -j ACCEPT/, - /-A FORWARD -s 10.0.0.0\/(8|255\.0\.0\.0) (! -d|-d !) 10.0.0.0\/(8|255\.0\.0\.0) -p tcp -m multiport --ports 80,443,21,20,22,53,123,43,873,25,465 -m state --state NEW -m comment --comment \"100 forward standard allow tcp\" -j ACCEPT/, - /-A FORWARD -s 10.0.0.0\/(8|255\.0\.0\.0) (! -d|-d !) 10.0.0.0\/(8|255\.0\.0\.0) -p udp -m multiport --ports 53,123 -m comment --comment \"100 forward standard allow udp\" -j ACCEPT/ - ].each do |line| - expect(r.stdout).to match(line) + it 'applies cleanly' do + # Run it twice and test for idempotency + apply_manifest(pp1, catch_failures: true) + expect(apply_manifest(pp1, catch_failures: true).exit_code).to be_zero + end + regex_values = [ + %r{INPUT ACCEPT}, %r{FORWARD ACCEPT}, %r{OUTPUT ACCEPT}, + %r{-A FORWARD -s 10.0.0.0\/(8|255\.0\.0\.0) -d 10.0.0.0\/(8|255\.0\.0\.0) -m comment --comment \"090 forward allow local\" -j ACCEPT}, + %r{-A FORWARD -s 10.0.0.0\/(8|255\.0\.0\.0) (! -d|-d !) 10.0.0.0\/(8|255\.0\.0\.0) -p icmp -m comment --comment \"100 forward standard allow icmp\" -j ACCEPT}, + %r{-A FORWARD -s 10.0.0.0\/(8|255\.0\.0\.0) (! -d|-d !) 10.0.0.0\/(8|255\.0\.0\.0) -p tcp -m multiport --ports 80,443,21,20,22,53,123,43,873,25,465 -m state --state NEW -m comment --comment \"100 forward standard allow tcp\" -j ACCEPT}, # rubocop:disable Metrics/LineLength + %r{-A FORWARD -s 10.0.0.0\/(8|255\.0\.0\.0) (! -d|-d !) 10.0.0.0\/(8|255\.0\.0\.0) -p udp -m multiport --ports 53,123 -m comment --comment \"100 forward standard allow udp\" -j ACCEPT} + ] + it 'contains appropriate rules' do + shell('iptables-save') do |r| + regex_values.each do |line| + expect(r.stdout).to match(line) + end end end end -end -describe 'complex ruleset 2' do - after :all do - shell('iptables -t filter -P INPUT ACCEPT') - shell('iptables -t filter -P FORWARD ACCEPT') - shell('iptables -t filter -P OUTPUT ACCEPT') - shell('iptables -t filter --flush') - expect(shell('iptables -t filter -X LOCAL_INPUT').stderr).to eq("") - expect(shell('iptables -t filter -X LOCAL_INPUT_PRE').stderr).to eq("") - end + describe 'complex ruleset 2' do + after :all do + shell('iptables -t filter -P INPUT ACCEPT') + shell('iptables -t filter -P FORWARD ACCEPT') + shell('iptables -t filter -P OUTPUT ACCEPT') + shell('iptables -t filter --flush') + end - it 'applies cleanly' do - pp = <<-EOS - class { '::firewall': } + pp2 = <<-EOS + class { '::firewall': } - Firewall { - proto => 'all', - } - Firewallchain { - purge => 'true', - ignore => [ - '--comment "[^"]*(?i:ignore)[^"]*"', - ], - } + Firewall { + proto => 'all', + } + Firewallchain { + purge => 'true', + ignore => [ + '--comment "[^"]*(?i:ignore)[^"]*"', + ], + } - firewall { '001 ssh needed for beaker testing': - proto => 'tcp', - dport => '22', - action => 'accept', - before => Firewallchain['INPUT:filter:IPv4'], - } + firewall { '001 ssh needed for beaker testing': + proto => 'tcp', + dport => '22', + action => 'accept', + before => Firewallchain['INPUT:filter:IPv4'], + } - firewall { '010 INPUT allow established and related': - proto => 'all', - state => ['ESTABLISHED', 'RELATED'], - action => 'accept', - before => Firewallchain['INPUT:filter:IPv4'], - } + firewall { '010 INPUT allow established and related': + proto => 'all', + state => ['ESTABLISHED', 'RELATED'], + action => 'accept', + before => Firewallchain['INPUT:filter:IPv4'], + } - firewall { "011 reject local traffic not on loopback interface": - iniface => '! lo', - proto => 'all', - destination => '127.0.0.1/8', - action => 'reject', - } - firewall { '012 accept loopback': - iniface => 'lo', - action => 'accept', - before => Firewallchain['INPUT:filter:IPv4'], - } - firewall { '020 ssh': - proto => 'tcp', - dport => '22', - state => 'NEW', - action => 'accept', - before => Firewallchain['INPUT:filter:IPv4'], - } + firewall { "011 reject local traffic not on loopback interface": + iniface => '! lo', + proto => 'all', + destination => '127.0.0.1/8', + action => 'reject', + } + firewall { '012 accept loopback': + iniface => 'lo', + action => 'accept', + before => Firewallchain['INPUT:filter:IPv4'], + } + firewall { '020 ssh': + proto => 'tcp', + dport => '22', + state => 'NEW', + action => 'accept', + before => Firewallchain['INPUT:filter:IPv4'], + } - firewall { '025 smtp': - outiface => '! eth0:2', - chain => 'OUTPUT', - proto => 'tcp', - dport => '25', - state => 'NEW', - action => 'accept', - } - firewall { '013 icmp echo-request': - proto => 'icmp', - icmp => 'echo-request', - action => 'accept', - source => '10.0.0.0/8', - } - firewall { '013 icmp destination-unreachable': - proto => 'icmp', - icmp => 'destination-unreachable', - action => 'accept', - } - firewall { '013 icmp time-exceeded': - proto => 'icmp', - icmp => 'time-exceeded', - action => 'accept', - } - firewall { '443 ssl on aliased interface': - proto => 'tcp', - dport => '443', - state => 'NEW', - action => 'accept', - iniface => 'eth0:3', - } + firewall { '025 smtp': + outiface => '! eth0:2', + chain => 'OUTPUT', + proto => 'tcp', + dport => '25', + state => 'NEW', + action => 'accept', + } + firewall { '013 icmp echo-request': + proto => 'icmp', + icmp => 'echo-request', + action => 'accept', + source => '10.0.0.0/8', + } + firewall { '013 icmp destination-unreachable': + proto => 'icmp', + icmp => 'destination-unreachable', + action => 'accept', + } + firewall { '013 icmp time-exceeded': + proto => 'icmp', + icmp => 'time-exceeded', + action => 'accept', + } + firewall { '443 ssl on aliased interface': + proto => 'tcp', + dport => '443', + state => 'NEW', + action => 'accept', + iniface => 'eth0:3', + } - firewallchain { 'LOCAL_INPUT_PRE:filter:IPv4': } - firewall { '001 LOCAL_INPUT_PRE': - jump => 'LOCAL_INPUT_PRE', - require => Firewallchain['LOCAL_INPUT_PRE:filter:IPv4'], - } - firewallchain { 'LOCAL_INPUT:filter:IPv4': } - firewall { '900 LOCAL_INPUT': - jump => 'LOCAL_INPUT', - require => Firewallchain['LOCAL_INPUT:filter:IPv4'], - } - firewallchain { 'INPUT:filter:IPv4': - policy => 'drop', - ignore => [ - '-j fail2ban-ssh', - '--comment "[^"]*(?i:ignore)[^"]*"', - ], - } + firewallchain { 'LOCAL_INPUT_PRE:filter:IPv4': } + firewall { '001 LOCAL_INPUT_PRE': + jump => 'LOCAL_INPUT_PRE', + require => Firewallchain['LOCAL_INPUT_PRE:filter:IPv4'], + } + firewallchain { 'LOCAL_INPUT:filter:IPv4': } + firewall { '900 LOCAL_INPUT': + jump => 'LOCAL_INPUT', + require => Firewallchain['LOCAL_INPUT:filter:IPv4'], + } + firewallchain { 'INPUT:filter:IPv4': + policy => 'drop', + ignore => [ + '-j fail2ban-ssh', + '--comment "[^"]*(?i:ignore)[^"]*"', + ], + } - firewall { '010 allow established and related': - chain => 'FORWARD', - proto => 'all', - state => ['ESTABLISHED','RELATED'], - action => 'accept', - before => Firewallchain['FORWARD:filter:IPv4'], - } - firewallchain { 'FORWARD:filter:IPv4': - policy => 'drop', - } + firewall { '010 allow established and related': + chain => 'FORWARD', + proto => 'all', + state => ['ESTABLISHED','RELATED'], + action => 'accept', + before => Firewallchain['FORWARD:filter:IPv4'], + } + firewallchain { 'FORWARD:filter:IPv4': + policy => 'drop', + } - firewallchain { 'OUTPUT:filter:IPv4': } + firewallchain { 'OUTPUT:filter:IPv4': } - # purge unknown rules from mangle table - firewallchain { ['PREROUTING:mangle:IPv4', 'INPUT:mangle:IPv4', 'FORWARD:mangle:IPv4', 'OUTPUT:mangle:IPv4', 'POSTROUTING:mangle:IPv4']: } + # purge unknown rules from mangle table + firewallchain { ['PREROUTING:mangle:IPv4', 'INPUT:mangle:IPv4', 'FORWARD:mangle:IPv4', 'OUTPUT:mangle:IPv4', 'POSTROUTING:mangle:IPv4']: } - # and the nat table - firewallchain { ['PREROUTING:nat:IPv4', 'INPUT:nat:IPv4', 'OUTPUT:nat:IPv4', 'POSTROUTING:nat:IPv4']: } + # and the nat table + firewallchain { ['PREROUTING:nat:IPv4', 'INPUT:nat:IPv4', 'OUTPUT:nat:IPv4', 'POSTROUTING:nat:IPv4']: } EOS + it 'applies cleanly' do + # Run it twice and test for idempotency + apply_manifest(pp2, catch_failures: true) + apply_manifest(pp2, catch_changes: do_catch_changes) + end - # Run it twice and test for idempotency - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) - end - - it 'contains appropriate rules' do - shell('iptables-save') do |r| - [ - /INPUT DROP/, - /FORWARD DROP/, - /OUTPUT ACCEPT/, - /LOCAL_INPUT/, - /LOCAL_INPUT_PRE/, - /-A INPUT -m comment --comment \"001 LOCAL_INPUT_PRE\" -j LOCAL_INPUT_PRE/, - /-A INPUT -p tcp -m multiport --dports 22 -m comment --comment \"001 ssh needed for beaker testing\" -j ACCEPT/, - /-A INPUT -m state --state RELATED,ESTABLISHED -m comment --comment \"010 INPUT allow established and related\" -j ACCEPT/, - /-A INPUT -d 127.0.0.0\/(8|255\.0\.0\.0) (! -i|-i !) lo -m comment --comment \"011 reject local traffic not on loopback interface\" -j REJECT --reject-with icmp-port-unreachable/, - /-A INPUT -i lo -m comment --comment \"012 accept loopback\" -j ACCEPT/, - /-A INPUT -p icmp -m icmp --icmp-type 3 -m comment --comment \"013 icmp destination-unreachable\" -j ACCEPT/, - /-A INPUT -s 10.0.0.0\/(8|255\.0\.0\.0) -p icmp -m icmp --icmp-type 8 -m comment --comment \"013 icmp echo-request\" -j ACCEPT/, - /-A INPUT -p icmp -m icmp --icmp-type 11 -m comment --comment \"013 icmp time-exceeded\" -j ACCEPT/, - /-A INPUT -p tcp -m multiport --dports 22 -m state --state NEW -m comment --comment \"020 ssh\" -j ACCEPT/, - /-A INPUT -i eth0:3 -p tcp -m multiport --dports 443 -m state --state NEW -m comment --comment \"443 ssl on aliased interface\" -j ACCEPT/, - /-A INPUT -m comment --comment \"900 LOCAL_INPUT\" -j LOCAL_INPUT/, - /-A FORWARD -m state --state RELATED,ESTABLISHED -m comment --comment \"010 allow established and related\" -j ACCEPT/, - /-A OUTPUT (! -o|-o !) eth0:2 -p tcp -m multiport --dports 25 -m state --state NEW -m comment --comment \"025 smtp\" -j ACCEPT/ - ].each do |line| - expect(r.stdout).to match(line) + regex_values = [ + %r{INPUT DROP}, + %r{FORWARD DROP}, + %r{OUTPUT ACCEPT}, + %r{LOCAL_INPUT}, + %r{LOCAL_INPUT_PRE}, + %r{-A INPUT -m comment --comment \"001 LOCAL_INPUT_PRE\" -j LOCAL_INPUT_PRE}, + %r{-A INPUT -p tcp -m multiport --dports 22 -m comment --comment \"001 ssh needed for beaker testing\" -j ACCEPT}, + %r{-A INPUT -m state --state RELATED,ESTABLISHED -m comment --comment \"010 INPUT allow established and related\" -j ACCEPT}, + %r{-A INPUT -d 127.0.0.0\/(8|255\.0\.0\.0) (! -i|-i !) lo -m comment --comment \"011 reject local traffic not on loopback interface\" -j REJECT --reject-with icmp-port-unreachable}, + %r{-A INPUT -i lo -m comment --comment \"012 accept loopback\" -j ACCEPT}, + %r{-A INPUT -p icmp -m icmp --icmp-type 3 -m comment --comment \"013 icmp destination-unreachable\" -j ACCEPT}, + %r{-A INPUT -s 10.0.0.0\/(8|255\.0\.0\.0) -p icmp -m icmp --icmp-type 8 -m comment --comment \"013 icmp echo-request\" -j ACCEPT}, + %r{-A INPUT -p icmp -m icmp --icmp-type 11 -m comment --comment \"013 icmp time-exceeded\" -j ACCEPT}, + %r{-A INPUT -p tcp -m multiport --dports 22 -m state --state NEW -m comment --comment \"020 ssh\" -j ACCEPT}, + %r{-A INPUT -i eth0:3 -p tcp -m multiport --dports 443 -m state --state NEW -m comment --comment \"443 ssl on aliased interface\" -j ACCEPT}, + %r{-A INPUT -m comment --comment \"900 LOCAL_INPUT\" -j LOCAL_INPUT}, + %r{-A FORWARD -m state --state RELATED,ESTABLISHED -m comment --comment \"010 allow established and related\" -j ACCEPT}, + %r{-A OUTPUT (! -o|-o !) eth0:2 -p tcp -m multiport --dports 25 -m state --state NEW -m comment --comment \"025 smtp\" -j ACCEPT}, + ] + it 'contains appropriate rules' do + shell('iptables-save') do |r| + regex_values.each do |line| + expect(r.stdout).to match(line) + end end end end diff --git a/spec/acceptance/socket_spec.rb b/spec/acceptance/socket_spec.rb index 84a5361..d6af304 100644 --- a/spec/acceptance/socket_spec.rb +++ b/spec/acceptance/socket_spec.rb @@ -1,15 +1,14 @@ require 'spec_helper_acceptance' # RHEL5 does not support -m socket -describe 'firewall socket property', :unless => default['platform'] =~ /el-5/ || fact('operatingsystem') == 'SLES' do +describe 'firewall socket property', unless: default['platform'] =~ %r{el-5} || fact('operatingsystem') == 'SLES' do before :all do iptables_flush_all_tables ip6tables_flush_all_tables end - shared_examples "is idempotent" do |value, line_match| - it "changes the value to #{value}" do - pp = <<-EOS + shared_examples 'is idempotent' do |value, line_match| + pp1 = <<-EOS class { '::firewall': } firewall { '598 - test': ensure => present, @@ -18,19 +17,19 @@ describe 'firewall socket property', :unless => default['platform'] =~ /el-5/ || table => 'raw', #{value} } - EOS - - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => true) + EOS + it "changes the value to #{value}" do + apply_manifest(pp1, catch_failures: true) + apply_manifest(pp1, catch_changes: true) shell('iptables-save -t raw') do |r| - expect(r.stdout).to match(/#{line_match}/) + expect(r.stdout).to match(%r{#{line_match}}) end end end + shared_examples "doesn't change" do |value, line_match| - it "doesn't change the value to #{value}" do - pp = <<-EOS + pp2 = <<-EOS class { '::firewall': } firewall { '598 - test': ensure => present, @@ -39,12 +38,12 @@ describe 'firewall socket property', :unless => default['platform'] =~ /el-5/ || table => 'raw', #{value} } - EOS - - apply_manifest(pp, :catch_changes => true) + EOS + it "doesn't change the value to #{value}" do + apply_manifest(pp2, catch_changes: true) shell('iptables-save -t raw') do |r| - expect(r.stdout).to match(/#{line_match}/) + expect(r.stdout).to match(%r{#{line_match}}) end end end @@ -54,45 +53,50 @@ describe 'firewall socket property', :unless => default['platform'] =~ /el-5/ || before :all do iptables_flush_all_tables end - it_behaves_like 'is idempotent', '', /-A PREROUTING -p tcp -m comment --comment "598 - test"/ + it_behaves_like 'is idempotent', '', %r{-A PREROUTING -p tcp -m comment --comment "598 - test"} end context 'when set to true' do before :all do iptables_flush_all_tables end - it_behaves_like 'is idempotent', 'socket => true,', /-A PREROUTING -p tcp -m socket -m comment --comment "598 - test"/ + it_behaves_like 'is idempotent', 'socket => true,', %r{-A PREROUTING -p tcp -m socket -m comment --comment "598 - test"} end context 'when set to false' do before :all do iptables_flush_all_tables end - it_behaves_like "is idempotent", 'socket => false,', /-A PREROUTING -p tcp -m comment --comment "598 - test"/ + it_behaves_like 'is idempotent', 'socket => false,', %r{-A PREROUTING -p tcp -m comment --comment "598 - test"} end end + describe 'editing a rule' do - context 'when unset or false' do + context 'when unset or false and current value is false' do before :each do iptables_flush_all_tables shell('iptables -t raw -A PREROUTING -p tcp -m comment --comment "598 - test"') end - context 'and current value is false' do - it_behaves_like "doesn't change", 'socket => false,', /-A PREROUTING -p tcp -m comment --comment "598 - test"/ - end - context 'and current value is true' do - it_behaves_like "is idempotent", 'socket => true,', /-A PREROUTING -p tcp -m socket -m comment --comment "598 - test"/ + it_behaves_like "doesn't change", 'socket => false,', %r{-A PREROUTING -p tcp -m comment --comment "598 - test"} + end + context 'when unset or false and current value is true' do + before :each do + iptables_flush_all_tables + shell('iptables -t raw -A PREROUTING -p tcp -m comment --comment "598 - test"') end + it_behaves_like 'is idempotent', 'socket => true,', %r{-A PREROUTING -p tcp -m socket -m comment --comment "598 - test"} end - context 'when set to true' do + context 'when set to true and current value is false' do before :each do iptables_flush_all_tables shell('iptables -t raw -A PREROUTING -p tcp -m socket -m comment --comment "598 - test"') end - context 'and current value is false' do - it_behaves_like "is idempotent", 'socket => false,', /-A PREROUTING -p tcp -m comment --comment "598 - test"/ - end - context 'and current value is true' do - it_behaves_like "doesn't change", 'socket => true,', /-A PREROUTING -p tcp -m socket -m comment --comment "598 - test"/ + it_behaves_like 'is idempotent', 'socket => false,', %r{-A PREROUTING -p tcp -m comment --comment "598 - test"} + end + context 'when set to true and current value is true' do + before :each do + iptables_flush_all_tables + shell('iptables -t raw -A PREROUTING -p tcp -m socket -m comment --comment "598 - test"') end + it_behaves_like "doesn't change", 'socket => true,', %r{-A PREROUTING -p tcp -m socket -m comment --comment "598 - test"} end end end diff --git a/spec/acceptance/standard_usage_spec.rb b/spec/acceptance/standard_usage_spec.rb index 6c54f8c..69feb67 100644 --- a/spec/acceptance/standard_usage_spec.rb +++ b/spec/acceptance/standard_usage_spec.rb @@ -2,8 +2,7 @@ require 'spec_helper_acceptance' # Some tests for the standard recommended usage describe 'standard usage tests' do - it 'applies twice' do - pp = <<-EOS + pp = <<-EOS class my_fw::pre { Firewall { require => undef, @@ -51,10 +50,10 @@ describe 'standard usage tests' do proto => 'tcp', dport => 22, } - EOS - + EOS + it 'applies twice' do # Run it twice and test for idempotency - apply_manifest(pp, :catch_failures => true) - apply_manifest(pp, :catch_changes => do_catch_changes) + apply_manifest(pp, catch_failures: true) + apply_manifest(pp, catch_changes: do_catch_changes) end end diff --git a/spec/spec_helper_acceptance.rb b/spec/spec_helper_acceptance.rb index 5f16568..8fcc589 100644 --- a/spec/spec_helper_acceptance.rb +++ b/spec/spec_helper_acceptance.rb @@ -3,22 +3,22 @@ require 'beaker/puppet_install_helper' require 'beaker/module_install_helper' def iptables_flush_all_tables - ['filter', 'nat', 'mangle', 'raw'].each do |t| - expect(shell("iptables -t #{t} -F").stderr).to eq("") + %w[filter nat mangle raw].each do |t| + expect(shell("iptables -t #{t} -F").stderr).to eq('') end end def ip6tables_flush_all_tables - ['filter', 'mangle'].each do |t| - expect(shell("ip6tables -t #{t} -F").stderr).to eq("") + %w[filter mangle].each do |t| + expect(shell("ip6tables -t #{t} -F").stderr).to eq('') end end def do_catch_changes - if default['platform'] =~ /el-5/ - return false + if default['platform'] =~ %r{el-5} + false else - return true + true end end @@ -31,7 +31,7 @@ RSpec.configure do |c| c.before :suite do # Install module and dependencies hosts.each do |host| - on host, puppet('module', 'install', 'puppetlabs-stdlib'), { :acceptable_exit_codes => [0] } + on host, puppet('module', 'install', 'puppetlabs-stdlib'), acceptable_exit_codes: [0] # the ubuntu-14.04 docker image doesn't carry the iptables command apply_manifest_on host, 'package { "iptables": ensure => installed }' if fact('osfamily') == 'Debian' end diff --git a/spec/spec_helper_local.rb b/spec/spec_helper_local.rb index 6af3d0b..4abf9f9 100644 --- a/spec/spec_helper_local.rb +++ b/spec/spec_helper_local.rb @@ -5,10 +5,10 @@ end def with_debian_facts let :facts do { - :kernel => 'Linux', - :operatingsystem => 'Debian', - :operatingsystemrelease => '8.0', - :osfamily => 'Debian', + kernel: 'Linux', + operatingsystem: 'Debian', + operatingsystemrelease: '8.0', + osfamily: 'Debian', } end end diff --git a/spec/unit/classes/firewall_linux_archlinux_spec.rb b/spec/unit/classes/firewall_linux_archlinux_spec.rb index 36dc925..b63910a 100644 --- a/spec/unit/classes/firewall_linux_archlinux_spec.rb +++ b/spec/unit/classes/firewall_linux_archlinux_spec.rb @@ -1,38 +1,53 @@ require 'spec_helper' -describe 'firewall::linux::archlinux', :type => :class do +describe 'firewall::linux::archlinux', type: :class do let(:facts) do { - :osfamily => 'Archlinux', - :operatingsystem => 'Archlinux' + osfamily: 'Archlinux', + operatingsystem: 'Archlinux', } end - it { should contain_service('iptables').with( - :ensure => 'running', - :enable => 'true' - )} - it { should contain_service('ip6tables').with( - :ensure => 'running', - :enable => 'true' - )} + + it { + is_expected.to contain_service('iptables').with( + ensure: 'running', + enable: 'true', + ) + } + it { + is_expected.to contain_service('ip6tables').with( + ensure: 'running', + enable: 'true', + ) + } context 'ensure => stopped' do - let(:params) {{ :ensure => 'stopped' }} - it { should contain_service('iptables').with( - :ensure => 'stopped' - )} - it { should contain_service('ip6tables').with( - :ensure => 'stopped' - )} + let(:params) { { ensure: 'stopped' } } + + it { + is_expected.to contain_service('iptables').with( + ensure: 'stopped', + ) + } + it { + is_expected.to contain_service('ip6tables').with( + ensure: 'stopped', + ) + } end context 'enable => false' do - let(:params) {{ :enable => 'false' }} - it { should contain_service('iptables').with( - :enable => 'false' - )} - it { should contain_service('ip6tables').with( - :enable => 'false' - )} + let(:params) { { enable: 'false' } } + + it { + is_expected.to contain_service('iptables').with( + enable: 'false', + ) + } + it { + is_expected.to contain_service('ip6tables').with( + enable: 'false', + ) + } end end diff --git a/spec/unit/classes/firewall_linux_debian_spec.rb b/spec/unit/classes/firewall_linux_debian_spec.rb index e8af543..cc7d7a4 100644 --- a/spec/unit/classes/firewall_linux_debian_spec.rb +++ b/spec/unit/classes/firewall_linux_debian_spec.rb @@ -1,87 +1,123 @@ require 'spec_helper' -describe 'firewall::linux::debian', :type => :class do - context "Debian 7" do - let(:facts) {{ - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '7.0' - }} - it { should contain_package('iptables-persistent').with( - :ensure => 'present' - )} - it { should contain_service('iptables-persistent').with( - :ensure => nil, - :enable => 'true', - :require => 'Package[iptables-persistent]' - )} +describe 'firewall::linux::debian', type: :class do + context 'Debian 7' do + let(:facts) do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '7.0', + } + end + + it { + is_expected.to contain_package('iptables-persistent').with( + ensure: 'present', + ) + } + it { + is_expected.to contain_service('iptables-persistent').with( + ensure: nil, + enable: 'true', + require: 'Package[iptables-persistent]', + ) + } end context 'deb7 enable => false' do - let(:facts) {{ - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '7.0' - }} - let(:params) {{ :enable => 'false' }} - it { should contain_service('iptables-persistent').with( - :enable => 'false' - )} + let(:facts) do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '7.0', + } + end + let(:params) { { enable: 'false' } } + + it { + is_expected.to contain_service('iptables-persistent').with( + enable: 'false', + ) + } end - context "Debian 8" do - let(:facts) {{ - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => 'jessie/sid' - }} - it { should contain_package('iptables-persistent').with( - :ensure => 'present' - )} - it { should contain_service('netfilter-persistent').with( - :ensure => nil, - :enable => 'true', - :require => 'Package[iptables-persistent]' - )} + context 'Debian 8' do + let(:facts) do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: 'jessie/sid', + } + end + + it { + is_expected.to contain_package('iptables-persistent').with( + ensure: 'present', + ) + } + it { + is_expected.to contain_service('netfilter-persistent').with( + ensure: nil, + enable: 'true', + require: 'Package[iptables-persistent]', + ) + } end context 'deb8 enable => false' do - let(:facts) {{ - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => 'jessie/sid' - }} - let(:params) {{ :enable => 'false' }} - it { should contain_service('netfilter-persistent').with( - :enable => 'false' - )} + let(:facts) do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: 'jessie/sid', + } + end + let(:params) { { enable: 'false' } } + + it { + is_expected.to contain_service('netfilter-persistent').with( + enable: 'false', + ) + } end - context "Debian 8, alt operatingsystem" do - let(:facts) {{ - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '8.0' - }} - it { should contain_package('iptables-persistent').with( - :ensure => 'present' - )} - it { should contain_service('netfilter-persistent').with( - :ensure => nil, - :enable => 'true', - :require => 'Package[iptables-persistent]' - )} + context 'Debian 8, alt operatingsystem' do + let(:facts) do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '8.0', + } + end + + it { + is_expected.to contain_package('iptables-persistent').with( + ensure: 'present', + ) + } + it { + is_expected.to contain_service('netfilter-persistent').with( + ensure: nil, + enable: 'true', + require: 'Package[iptables-persistent]', + ) + } end context 'deb8, alt operatingsystem, enable => false' do - let(:facts) {{ - :osfamily => 'Debian', - :operatingsystem => 'Debian', - :operatingsystemrelease => '8.0' - }} - let(:params) {{ :enable => 'false' }} - it { should contain_service('netfilter-persistent').with( - :enable => 'false' - )} + let(:facts) do + { + osfamily: 'Debian', + operatingsystem: 'Debian', + operatingsystemrelease: '8.0', + } + end + let(:params) { { enable: 'false' } } + + it { + is_expected.to contain_service('netfilter-persistent').with( + enable: 'false', + ) + } end end diff --git a/spec/unit/classes/firewall_linux_gentoo_spec.rb b/spec/unit/classes/firewall_linux_gentoo_spec.rb index 942d8e4..75d683f 100644 --- a/spec/unit/classes/firewall_linux_gentoo_spec.rb +++ b/spec/unit/classes/firewall_linux_gentoo_spec.rb @@ -1,41 +1,58 @@ require 'spec_helper' -describe 'firewall::linux::gentoo', :type => :class do +describe 'firewall::linux::gentoo', type: :class do let(:facts) do { - :osfamily => 'Gentoo', - :operatingsystem => 'Gentoo' + osfamily: 'Gentoo', + operatingsystem: 'Gentoo', } end - it { should contain_service('iptables').with( - :ensure => 'running', - :enable => 'true' - )} - it { should contain_service('ip6tables').with( - :ensure => 'running', - :enable => 'true' - )} - it { should contain_package('net-firewall/iptables').with( - :ensure => 'present' - )} + + it { + is_expected.to contain_service('iptables').with( + ensure: 'running', + enable: 'true', + ) + } + it { + is_expected.to contain_service('ip6tables').with( + ensure: 'running', + enable: 'true', + ) + } + it { + is_expected.to contain_package('net-firewall/iptables').with( + ensure: 'present', + ) + } context 'ensure => stopped' do - let(:params) {{ :ensure => 'stopped' }} - it { should contain_service('iptables').with( - :ensure => 'stopped' - )} - it { should contain_service('ip6tables').with( - :ensure => 'stopped' - )} + let(:params) { { ensure: 'stopped' } } + + it { + is_expected.to contain_service('iptables').with( + ensure: 'stopped', + ) + } + it { + is_expected.to contain_service('ip6tables').with( + ensure: 'stopped', + ) + } end context 'enable => false' do - let(:params) {{ :enable => 'false' }} - it { should contain_service('iptables').with( - :enable => 'false' - )} - it { should contain_service('ip6tables').with( - :enable => 'false' - )} + let(:params) { { enable: 'false' } } + + it { + is_expected.to contain_service('iptables').with( + enable: 'false', + ) + } + it { + is_expected.to contain_service('ip6tables').with( + enable: 'false', + ) + } end end diff --git a/spec/unit/classes/firewall_linux_redhat_spec.rb b/spec/unit/classes/firewall_linux_redhat_spec.rb index 9e42469..b2714af 100644 --- a/spec/unit/classes/firewall_linux_redhat_spec.rb +++ b/spec/unit/classes/firewall_linux_redhat_spec.rb @@ -1,109 +1,141 @@ require 'spec_helper' -RSpec.shared_examples "ensures iptables service" do +RSpec.shared_examples 'ensures iptables service' do context 'default' do - it { should contain_service('iptables').with( - :ensure => 'running', - :enable => 'true' - )} + it { + is_expected.to contain_service('iptables').with( + ensure: 'running', + enable: 'true', + ) + } end context 'ensure => stopped' do - let(:params) {{ :ensure => 'stopped' }} - it { should contain_service('iptables').with( - :ensure => 'stopped' - )} + let(:params) { { ensure: 'stopped' } } + + it { + is_expected.to contain_service('iptables').with( + ensure: 'stopped', + ) + } end context 'enable => false' do - let(:params) {{ :enable => 'false' }} - it { should contain_service('iptables').with( - :enable => 'false' - )} + let(:params) { { enable: 'false' } } + + it { + is_expected.to contain_service('iptables').with( + enable: 'false', + ) + } end end -describe 'firewall::linux::redhat', :type => :class do - %w{RedHat CentOS Fedora}.each do |os| - oldreleases = (os == 'Fedora' ? ['14'] : ['6.5']) - newreleases = (os == 'Fedora' ? ['15','Rawhide'] : ['7.0.1406']) +describe 'firewall::linux::redhat', type: :class do + %w[RedHat CentOS Fedora].each do |os| + oldreleases = ((os == 'Fedora') ? ['14'] : ['6.5']) + newreleases = ((os == 'Fedora') ? %w[15 Rawhide] : ['7.0.1406']) oldreleases.each do |osrel| context "os #{os} and osrel #{osrel}" do - let(:facts) {{ - :operatingsystem => os, - :operatingsystemrelease => osrel, - :osfamily => 'RedHat', - :selinux => false, - :puppetversion => Puppet.version, - }} - - it { should_not contain_service('firewalld') } - it { should_not contain_package('iptables-services') } - - it_behaves_like "ensures iptables service" + let(:facts) do + { + operatingsystem: os, + operatingsystemrelease: osrel, + osfamily: 'RedHat', + selinux: false, + puppetversion: Puppet.version, + } + end + + it { is_expected.not_to contain_service('firewalld') } + it { is_expected.not_to contain_package('iptables-services') } + + it_behaves_like 'ensures iptables service' end end newreleases.each do |osrel| context "os #{os} and osrel #{osrel}" do - let(:facts) {{ - :operatingsystem => os, - :operatingsystemrelease => osrel, - :osfamily => 'RedHat', - :selinux => false, - :puppetversion => Puppet.version, - }} - - it { should contain_service('iptables').with( - :ensure => 'running', - :enable => 'true' - )} - it { should contain_service('ip6tables').with( - :ensure => 'running', - :enable => 'true' - )} + let(:facts) do + { + operatingsystem: os, + operatingsystemrelease: osrel, + osfamily: 'RedHat', + selinux: false, + puppetversion: Puppet.version, + } + end + + it { + is_expected.to contain_service('iptables').with( + ensure: 'running', + enable: 'true', + ) + } + it { + is_expected.to contain_service('ip6tables').with( + ensure: 'running', + enable: 'true', + ) + } context 'ensure => stopped' do - let(:params) {{ :ensure => 'stopped' }} - it { should contain_service('iptables').with( - :ensure => 'stopped' - )} + let(:params) { { ensure: 'stopped' } } + + it { + is_expected.to contain_service('iptables').with( + ensure: 'stopped', + ) + } end context 'ensure_v6 => stopped' do - let(:params) {{ :ensure_v6 => 'stopped' }} - it { should contain_service('ip6tables').with( - :ensure => 'stopped' - )} + let(:params) { { ensure_v6: 'stopped' } } + + it { + is_expected.to contain_service('ip6tables').with( + ensure: 'stopped', + ) + } end context 'enable => false' do - let(:params) {{ :enable => 'false' }} - it { should contain_service('iptables').with( - :enable => 'false' - )} - end + let(:params) { { enable: 'false' } } - context 'enable_v6 => false' do - let(:params) {{ :enable_v6 => 'false' }} - it { should contain_service('ip6tables').with( - :enable => 'false' - )} + it { + is_expected.to contain_service('iptables').with( + enable: 'false', + ) + } end - it { should contain_service('firewalld').with( - :ensure => 'stopped', - :enable => false, - :before => ['Package[iptables-services]', 'Service[iptables]'] - )} + context 'enable_v6 => false' do + let(:params) { { enable_v6: 'false' } } - it { should contain_package('iptables-services').with( - :ensure => 'present', - :before => 'Service[iptables]' - )} + it { + is_expected.to contain_service('ip6tables').with( + enable: 'false', + ) + } + end - it_behaves_like "ensures iptables service" + it { + is_expected.to contain_service('firewalld').with( + ensure: 'stopped', + enable: false, + before: ['Package[iptables-services]', 'Service[iptables]'], + ) + } + + it { + is_expected.to contain_package('iptables-services').with( + ensure: 'present', + before: 'Service[iptables]', + ) + } + + it_behaves_like 'ensures iptables service' end end end diff --git a/spec/unit/classes/firewall_linux_spec.rb b/spec/unit/classes/firewall_linux_spec.rb index b045801..056e308 100644 --- a/spec/unit/classes/firewall_linux_spec.rb +++ b/spec/unit/classes/firewall_linux_spec.rb @@ -1,45 +1,46 @@ require 'spec_helper' -describe 'firewall::linux', :type => :class do - context 'RedHat like' do - %w{RedHat CentOS Fedora}.each do |os| - context "operatingsystem => #{os}" do - releases = (os == 'Fedora' ? ['14','15','Rawhide'] : ['6','7']) - releases.each do |osrel| - context "operatingsystemrelease => #{osrel}" do - let(:facts) {{ - :kernel => 'Linux', - :operatingsystem => os, - :operatingsystemrelease => osrel, - :osfamily => 'RedHat', - :selinux => false, - :puppetversion => Puppet.version, - }} - it { should contain_class('firewall::linux::redhat').with_require('Package[iptables]') } - it { should contain_package('iptables').with_ensure('present') } +describe 'firewall::linux', type: :class do + %w[RedHat CentOS Fedora].each do |os| + context "Redhat Like: operatingsystem => #{os}" do + releases = ((os == 'Fedora') ? %w[14 15 Rawhide] : %w[6 7]) + releases.each do |osrel| + context "operatingsystemrelease => #{osrel}" do + let(:facts) do + { + kernel: 'Linux', + operatingsystem: os, + operatingsystemrelease: osrel, + osfamily: 'RedHat', + selinux: false, + puppetversion: Puppet.version, + } end + + it { is_expected.to contain_class('firewall::linux::redhat').with_require('Package[iptables]') } + it { is_expected.to contain_package('iptables').with_ensure('present') } end end end end - context 'Debian like' do - %w{Debian Ubuntu}.each do |os| - context "operatingsystem => #{os}" do - releases = (os == 'Debian' ? ['6','7','8'] : ['10.04','12.04','14.04']) - releases.each do |osrel| - let(:facts) {{ - :kernel => 'Linux', - :operatingsystem => os, - :operatingsystemrelease => osrel, - :osfamily => 'Debian', - :selinux => false, - :puppetversion => Puppet.version, - }} - - it { should contain_class('firewall::linux::debian').with_require('Package[iptables]') } - it { should contain_package('iptables').with_ensure('present') } + %w[Debian Ubuntu].each do |os| + context "Debian Like: operatingsystem => #{os}" do + releases = ((os == 'Debian') ? %w[6 7 8] : ['10.04', '12.04', '14.04']) + releases.each do |osrel| + let(:facts) do + { + kernel: 'Linux', + operatingsystem: os, + operatingsystemrelease: osrel, + osfamily: 'Debian', + selinux: false, + puppetversion: Puppet.version, + } end + + it { is_expected.to contain_class('firewall::linux::debian').with_require('Package[iptables]') } + it { is_expected.to contain_package('iptables').with_ensure('present') } end end end diff --git a/spec/unit/classes/firewall_spec.rb b/spec/unit/classes/firewall_spec.rb index 470e1b3..e237f20 100644 --- a/spec/unit/classes/firewall_spec.rb +++ b/spec/unit/classes/firewall_spec.rb @@ -1,41 +1,49 @@ require 'spec_helper' -describe 'firewall', :type => :class do +describe 'firewall', type: :class do context 'kernel => Linux' do with_debian_facts - it { should contain_class('firewall::linux').with_ensure('running') } + it { is_expected.to contain_class('firewall::linux').with_ensure('running') } end + # rubocop:disable RSpec/MultipleExpectations context 'kernel => Windows' do - let(:facts) {{ :kernel => 'Windows' }} - it { expect { should contain_class('firewall::linux') }.to raise_error(Puppet::Error) } + let(:facts) { { kernel: 'Windows' } } + + it { expect { is_expected.to contain_class('firewall::linux') }.to raise_error(Puppet::Error) } end context 'kernel => SunOS' do - let(:facts) {{ :kernel => 'SunOS' }} - it { expect { should contain_class('firewall::linux') }.to raise_error(Puppet::Error) } + let(:facts) { { kernel: 'SunOS' } } + + it { expect { is_expected.to contain_class('firewall::linux') }.to raise_error(Puppet::Error) } end context 'kernel => Darwin' do - let(:facts) {{ :kernel => 'Darwin' }} - it { expect { should contain_class('firewall::linux') }.to raise_error(Puppet::Error) } + let(:facts) { { kernel: 'Darwin' } } + + it { expect { is_expected.to contain_class('firewall::linux') }.to raise_error(Puppet::Error) } end context 'ensure => stopped' do with_debian_facts - let(:params) {{ :ensure => 'stopped' }} - it { should contain_class('firewall::linux').with_ensure('stopped') } + let(:params) { { ensure: 'stopped' } } + + it { is_expected.to contain_class('firewall::linux').with_ensure('stopped') } end context 'ensure => test' do - let(:facts) {{ :kernel => 'Linux' }} - let(:params) {{ :ensure => 'test' }} - it { expect { should contain_class('firewall::linux') }.to raise_error(Puppet::Error) } + let(:facts) { { kernel: 'Linux' } } + let(:params) { { ensure: 'test' } } + + it { expect { is_expected.to contain_class('firewall::linux') }.to raise_error(Puppet::Error) } end context 'ebtables_manage => true' do - let(:facts) {{ :kernel => 'Linux' }} - let(:params) {{ :ebtables_manage => true }} - it { expect { should contain_package('ebtables') }.to raise_error(Puppet::Error) } + let(:facts) { { kernel: 'Linux' } } + let(:params) { { ebtables_manage: true } } + + it { expect { is_expected.to contain_package('ebtables') }.to raise_error(Puppet::Error) } end + # rubocop:enable RSpec/MultipleExpectations end diff --git a/spec/unit/documentation/readme_spec.rb b/spec/unit/documentation/readme_spec.rb index d821bb2..e4dc37b 100644 --- a/spec/unit/documentation/readme_spec.rb +++ b/spec/unit/documentation/readme_spec.rb @@ -1,6 +1,6 @@ describe 'formatting in README.markdown' do - it 'should not contain badly formatted heading markers' do + it 'does not contain badly formatted heading markers' do content = File.read('README.markdown') - expect(content).to_not match /^#+[^# ]/ + expect(content).not_to match %r{^#+[^# ]} end end diff --git a/spec/unit/facter/iptables_persistent_version_spec.rb b/spec/unit/facter/iptables_persistent_version_spec.rb index 656e904..252089b 100644 --- a/spec/unit/facter/iptables_persistent_version_spec.rb +++ b/spec/unit/facter/iptables_persistent_version_spec.rb @@ -1,97 +1,96 @@ require 'spec_helper' -describe "Facter::Util::Fact iptables_persistent_version" do - - - context "iptables-persistent applicable" do - before { Facter.clear } +describe 'Facter::Util::Fact iptables_persistent_version' do + context 'iptables-persistent applicable' do + before(:each) { Facter.clear } let(:dpkg_cmd) { "dpkg-query -Wf '${Version}' iptables-persistent 2>/dev/null" } { - "Debian" => "0.0.20090701", - "Ubuntu" => "0.5.3ubuntu2", + 'Debian' => '0.0.20090701', + 'Ubuntu' => '0.5.3ubuntu2', }.each do |os, ver| - if os == "Debian" - os_release = "7.0" - elsif os == "Ubuntu" - os_release = "14.04" + if os == 'Debian' + os_release = '7.0' + elsif os == 'Ubuntu' + os_release = '14.04' end describe "#{os} package installed" do - before { + before(:each) do allow(Facter.fact(:operatingsystem)).to receive(:value).and_return(os) allow(Facter.fact(:operatingsystemrelease)).to receive(:value).and_return(os_release) - allow(Facter::Util::Resolution).to receive(:exec).with(dpkg_cmd). - and_return(ver) - } + allow(Facter::Util::Resolution).to receive(:exec).with(dpkg_cmd) + .and_return(ver) + end it { expect(Facter.fact(:iptables_persistent_version).value).to eql ver } end end describe 'Ubuntu package not installed' do - before { + before(:each) do allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Ubuntu') allow(Facter.fact(:operatingsystemrelease)).to receive(:value).and_return('14.04') - allow(Facter::Util::Resolution).to receive(:exec).with(dpkg_cmd). - and_return(nil) - } + allow(Facter::Util::Resolution).to receive(:exec).with(dpkg_cmd) + .and_return(nil) + end it { expect(Facter.fact(:iptables_persistent_version).value).to be_nil } end describe 'CentOS not supported' do - before { allow(Facter.fact(:operatingsystem)).to receive(:value). - and_return("CentOS") } + before(:each) do + allow(Facter.fact(:operatingsystem)).to receive(:value) + .and_return('CentOS') + end it { expect(Facter.fact(:iptables_persistent_version).value).to be_nil } end - end - context "netfilter-persistent applicable" do - before { Facter.clear } + context 'netfilter-persistent applicable' do + before(:each) { Facter.clear } let(:dpkg_cmd) { "dpkg-query -Wf '${Version}' netfilter-persistent 2>/dev/null" } { - "Debian" => "0.0.20090701", - "Ubuntu" => "0.5.3ubuntu2", + 'Debian' => '0.0.20090701', + 'Ubuntu' => '0.5.3ubuntu2', }.each do |os, ver| - if os == "Debian" - os_release = "8.0" - elsif os == "Ubuntu" - os_release = "14.10" + if os == 'Debian' + os_release = '8.0' + elsif os == 'Ubuntu' + os_release = '14.10' end describe "#{os} package installed" do - before { + before(:each) do allow(Facter.fact(:operatingsystem)).to receive(:value).and_return(os) allow(Facter.fact(:operatingsystemrelease)).to receive(:value).and_return(os_release) - allow(Facter::Util::Resolution).to receive(:exec).with(dpkg_cmd). - and_return(ver) - } + allow(Facter::Util::Resolution).to receive(:exec).with(dpkg_cmd) + .and_return(ver) + end it { expect(Facter.fact(:iptables_persistent_version).value).to eql ver } end end describe 'Ubuntu package not installed' do - os_release = "14.10" - before { + os_release = '14.10' + before(:each) do allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Ubuntu') allow(Facter.fact(:operatingsystemrelease)).to receive(:value).and_return(os_release) - allow(Facter::Util::Resolution).to receive(:exec).with(dpkg_cmd). - and_return(nil) - } + allow(Facter::Util::Resolution).to receive(:exec).with(dpkg_cmd) + .and_return(nil) + end it { expect(Facter.fact(:iptables_persistent_version).value).to be_nil } end describe 'CentOS not supported' do - before { allow(Facter.fact(:operatingsystem)).to receive(:value). - and_return("CentOS") } + before(:each) do + allow(Facter.fact(:operatingsystem)).to receive(:value) + .and_return('CentOS') + end it { expect(Facter.fact(:iptables_persistent_version).value).to be_nil } end - end - end diff --git a/spec/unit/facter/iptables_spec.rb b/spec/unit/facter/iptables_spec.rb index c17816c..0187540 100644 --- a/spec/unit/facter/iptables_spec.rb +++ b/spec/unit/facter/iptables_spec.rb @@ -1,23 +1,25 @@ require 'spec_helper' -describe "Facter::Util::Fact" do - before { +describe 'Facter::Util::Fact' do + before(:each) do Facter.clear allow(Facter.fact(:kernel)).to receive(:value).and_return('Linux') allow(Facter.fact(:kernelrelease)).to receive(:value).and_return('2.6') - } + end describe 'iptables_version' do it { - allow(Facter::Util::Resolution).to receive(:exec).with('iptables --version'). - and_return('iptables v1.4.7') + allow(Facter::Util::Resolution).to receive(:exec).with('iptables --version') + .and_return('iptables v1.4.7') expect(Facter.fact(:iptables_version).value).to eql '1.4.7' } end describe 'ip6tables_version' do - before { allow(Facter::Util::Resolution).to receive(:exec). - with('ip6tables --version').and_return('ip6tables v1.4.7') } + before(:each) do + allow(Facter::Util::Resolution).to receive(:exec) + .with('ip6tables --version').and_return('ip6tables v1.4.7') + end it { expect(Facter.fact(:ip6tables_version).value).to eql '1.4.7' } end end diff --git a/spec/unit/puppet/provider/ip6tables_spec.rb b/spec/unit/puppet/provider/ip6tables_spec.rb index 6e8b866..4814f15 100644 --- a/spec/unit/puppet/provider/ip6tables_spec.rb +++ b/spec/unit/puppet/provider/ip6tables_spec.rb @@ -1,4 +1,4 @@ -#!/usr/bin/env rspec +#!/usr/bin/env rspec # rubocop:disable Lint/ScriptPermission : Puppet error? require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '3.4.0') < 0 @@ -8,26 +8,25 @@ else end provider_class = Puppet::Type.type(:firewall).provider(:ip6tables) describe 'ip6tables' do - let(:params) { {:name => '000 test foo', :action => 'accept'} } + let(:params) { { name: '000 test foo', action: 'accept' } } let(:provider) { provider_class } let(:resource) { Puppet::Type.type(:firewall) } let(:ip6tables_version) { '1.4.0' } before :each do - end def stub_iptables allow(Puppet::Type::Firewall).to receive(:defaultprovider).and_return provider # Stub confine facts - allow(provider).to receive(:command).with(:iptables_save).and_return "/sbin/iptables-save" + allow(provider).to receive(:command).with(:iptables_save).and_return '/sbin/iptables-save' allow(Facter.fact(:kernel)).to receive(:value).and_return('Linux') allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Debian') allow(Facter.fact('ip6tables_version')).to receive(:value).and_return(ip6tables_version) - allow(Puppet::Util::Execution).to receive(:execute).and_return "" - allow(Puppet::Util).to receive(:which).with("iptables-save"). - and_return "/sbin/iptables-save" + allow(Puppet::Util::Execution).to receive(:execute).and_return '' + allow(Puppet::Util).to receive(:which).with('iptables-save') + .and_return '/sbin/iptables-save' end shared_examples 'raise error' do @@ -45,17 +44,17 @@ describe 'ip6tables' do } end context 'iptables 1.3' do - let(:params) { {:name => '000 test foo', :action => 'accept'} } - let(:error_message) { /The ip6tables provider is not supported on version 1\.3 of iptables/ } + let(:params) { { name: '000 test foo', action: 'accept' } } + let(:error_message) { %r{The ip6tables provider is not supported on version 1\.3 of iptables} } let(:ip6tables_version) { '1.3.10' } - it_should_behave_like 'raise error' + + it_behaves_like 'raise error' end context 'ip6tables nil' do - let(:params) { {:name => '000 test foo', :action => 'accept'} } - let(:error_message) { /The ip6tables provider is not supported on version 1\.3 of iptables/ } + let(:params) { { name: '000 test foo', action: 'accept' } } + let(:error_message) { %r{The ip6tables provider is not supported on version 1\.3 of iptables} } let(:ip6tables_version) { nil } - it_should_behave_like 'run' - end - + it_behaves_like 'run' + end end diff --git a/spec/unit/puppet/provider/iptables_chain_spec.rb b/spec/unit/puppet/provider/iptables_chain_spec.rb index 78db555..c5c8461 100755 --- a/spec/unit/puppet/provider/iptables_chain_spec.rb +++ b/spec/unit/puppet/provider/iptables_chain_spec.rb @@ -7,231 +7,226 @@ else require 'puppet/confine/exists' end -describe 'iptables chain provider detection' do - if Puppet::Util::Package.versioncmp(Puppet.version, '3.4.0') < 0 - let(:exists) { - Puppet::Provider::Confine::Exists - } - else - let(:exists) { - Puppet::Confine::Exists - } - end +describe 'iptables chain' do + describe 'iptables chain provider detection' do + if Puppet::Util::Package.versioncmp(Puppet.version, '3.4.0') < 0 + let(:exists) do + Puppet::Provider::Confine::Exists + end + else + let(:exists) do + Puppet::Confine::Exists + end + end - before :each do - # Reset the default provider - Puppet::Type.type(:firewallchain).defaultprovider = nil + before :each do + # Reset the default provider + Puppet::Type.type(:firewallchain).defaultprovider = nil + + # Stub confine facts + allow(Facter.fact(:kernel)).to receive(:value).and_return('Linux') + allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Debian') + + # Stub lookup for /sbin/iptables & /sbin/iptables-save + allow(exists).to receive(:which).with('ebtables') + .and_return '/sbin/ebtables' + allow(exists).to receive(:which).with('ebtables-save') + .and_return '/sbin/ebtables-save' + + allow(exists).to receive(:which).with('iptables') + .and_return '/sbin/iptables' + allow(exists).to receive(:which).with('iptables-save') + .and_return '/sbin/iptables-save' + + allow(exists).to receive(:which).with('ip6tables') + .and_return '/sbin/ip6tables' + allow(exists).to receive(:which).with('ip6tables-save') + .and_return '/sbin/ip6tables-save' + + # Every other command should return false so we don't pick up any + # other providers + allow(exists).to receive(:which) { |value| + value !~ %r{(eb|ip|ip6)tables(-save)?$} + }.and_return false + end - # Stub confine facts - allow(Facter.fact(:kernel)).to receive(:value).and_return('Linux') - allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Debian') + it 'defaults to iptables provider if /sbin/(eb|ip|ip6)tables[-save] exists' do + # Create a resource instance and make sure the provider is iptables + resource = Puppet::Type.type(:firewallchain).new(name: 'test:filter:IPv4') + expect(resource.provider.class.to_s).to eq('Puppet::Type::Firewallchain::ProviderIptables_chain') + end end - it "should default to iptables provider if /sbin/(eb|ip|ip6)tables[-save] exists" do - # Stub lookup for /sbin/iptables & /sbin/iptables-save - allow(exists).to receive(:which).with("ebtables"). - and_return "/sbin/ebtables" - allow(exists).to receive(:which).with("ebtables-save"). - and_return "/sbin/ebtables-save" - - allow(exists).to receive(:which).with("iptables"). - and_return "/sbin/iptables" - allow(exists).to receive(:which).with("iptables-save"). - and_return "/sbin/iptables-save" - - allow(exists).to receive(:which).with("ip6tables"). - and_return "/sbin/ip6tables" - allow(exists).to receive(:which).with("ip6tables-save"). - and_return "/sbin/ip6tables-save" - - # Every other command should return false so we don't pick up any - # other providers - allow(exists).to receive(:which) { |value| - value !~ /(eb|ip|ip6)tables(-save)?$/ - }.and_return false - - # Create a resource instance and make sure the provider is iptables - resource = Puppet::Type.type(:firewallchain).new({ - :name => 'test:filter:IPv4', - }) - expect(resource.provider.class.to_s).to eq("Puppet::Type::Firewallchain::ProviderIptables_chain") - end -end + describe 'iptables chain provider' do + let(:provider) { Puppet::Type.type(:firewallchain).provider(:iptables_chain) } + let(:resource) do + Puppet::Type.type(:firewallchain).new(name: ':test:') + end -describe 'iptables chain provider' do - let(:provider) { Puppet::Type.type(:firewallchain).provider(:iptables_chain) } - let(:resource) { - Puppet::Type.type(:firewallchain).new({ - :name => ':test:', - }) - } - - before :each do - allow(Puppet::Type::Firewallchain).to receive(:defaultprovider).and_return provider - allow(provider).to receive(:command).with(:ebtables_save).and_return "/sbin/ebtables-save" - allow(provider).to receive(:command).with(:iptables_save).and_return "/sbin/iptables-save" - allow(provider).to receive(:command).with(:ip6tables_save).and_return "/sbin/ip6tables-save" - end + before :each do + allow(Puppet::Type::Firewallchain).to receive(:defaultprovider).and_return provider + allow(provider).to receive(:command).with(:ebtables_save).and_return '/sbin/ebtables-save' + allow(provider).to receive(:command).with(:iptables_save).and_return '/sbin/iptables-save' + allow(provider).to receive(:command).with(:ip6tables_save).and_return '/sbin/ip6tables-save' - it 'should be able to get a list of existing rules' do - # Pretend to return nil from iptables - allow(provider).to receive(:execute).with(['/sbin/ip6tables-save']).and_return("") - allow(provider).to receive(:execute).with(['/sbin/ebtables-save']).and_return("") - allow(provider).to receive(:execute).with(['/sbin/iptables-save']).and_return("") + # Pretend to return nil from iptables + allow(provider).to receive(:execute).with(['/sbin/ip6tables-save']).and_return('') + allow(provider).to receive(:execute).with(['/sbin/ebtables-save']).and_return('') + allow(provider).to receive(:execute).with(['/sbin/iptables-save']).and_return('') + end - provider.instances.each do |chain| - expect(chain).to be_instance_of(provider) - expect(chain.properties[:provider].to_s).to eq(provider.name.to_s) + it 'is able to get a list of existing rules' do # rubocop:disable RSpec/MultipleExpectations + provider.instances.each do |chain| + expect(chain).to be_instance_of(provider) + expect(chain.properties[:provider].to_s).to eq(provider.name.to_s) + end end end -end - -describe 'iptables chain resource parsing' do - let(:provider) { Puppet::Type.type(:firewallchain).provider(:iptables_chain) } - - before :each do - ebtables = ['BROUTE:BROUTING:ethernet', - 'BROUTE:broute:ethernet', - ':INPUT:ethernet', - ':FORWARD:ethernet', - ':OUTPUT:ethernet', - ':filter:ethernet', - ':filterdrop:ethernet', - ':filterreturn:ethernet', - 'NAT:PREROUTING:ethernet', - 'NAT:OUTPUT:ethernet', - 'NAT:POSTROUTING:ethernet', - ] - allow(provider).to receive(:execute).with(['/sbin/ebtables-save']).and_return(' -*broute -:BROUTING ACCEPT -:broute ACCEPT - -*filter -:INPUT ACCEPT -:FORWARD ACCEPT -:OUTPUT ACCEPT -:filter ACCEPT -:filterdrop DROP -:filterreturn RETURN - -*nat -:PREROUTING ACCEPT -:OUTPUT ACCEPT -:POSTROUTING ACCEPT -') - - iptables = [ - 'raw:PREROUTING:IPv4', - 'raw:OUTPUT:IPv4', - 'raw:raw:IPv4', - 'mangle:PREROUTING:IPv4', - 'mangle:INPUT:IPv4', - 'mangle:FORWARD:IPv4', - 'mangle:OUTPUT:IPv4', - 'mangle:POSTROUTING:IPv4', - 'mangle:mangle:IPv4', - 'NAT:PREROUTING:IPv4', - 'NAT:OUTPUT:IPv4', - 'NAT:POSTROUTING:IPv4', - 'NAT:mangle:IPv4', - 'NAT:mangle:IPv4', - 'NAT:mangle:IPv4', - 'security:INPUT:IPv4', - 'security:FORWARD:IPv4', - 'security:OUTPUT:IPv4', - ':$5()*&%\'"^$): :IPv4', - ] - allow(provider).to receive(:execute).with(['/sbin/iptables-save']).and_return(' -# Generated by iptables-save v1.4.9 on Mon Jan 2 01:20:06 2012 -*raw -:PREROUTING ACCEPT [12:1780] -:OUTPUT ACCEPT [19:1159] -:raw - [0:0] -COMMIT -# Completed on Mon Jan 2 01:20:06 2012 -# Generated by iptables-save v1.4.9 on Mon Jan 2 01:20:06 2012 -*mangle -:PREROUTING ACCEPT [12:1780] -:INPUT ACCEPT [12:1780] -:FORWARD ACCEPT [0:0] -:OUTPUT ACCEPT [19:1159] -:POSTROUTING ACCEPT [19:1159] -:mangle - [0:0] -COMMIT -# Completed on Mon Jan 2 01:20:06 2012 -# Generated by iptables-save v1.4.9 on Mon Jan 2 01:20:06 2012 -*nat -:PREROUTING ACCEPT [2242:639750] -:OUTPUT ACCEPT [5176:326206] -:POSTROUTING ACCEPT [5162:325382] -COMMIT -# Completed on Mon Jan 2 01:20:06 2012 -# Generated by iptables-save v1.4.9 on Mon Jan 2 01:20:06 2012 -*filter -:INPUT ACCEPT [0:0] -:FORWARD DROP [0:0] -:OUTPUT ACCEPT [5673:420879] -:$5()*&%\'"^$): - [0:0] -COMMIT -# Completed on Mon Jan 2 01:20:06 2012 -') - ip6tables = [ - 'raw:PREROUTING:IPv6', - 'raw:OUTPUT:IPv6', - 'raw:ff:IPv6', - 'mangle:PREROUTING:IPv6', - 'mangle:INPUT:IPv6', - 'mangle:FORWARD:IPv6', - 'mangle:OUTPUT:IPv6', - 'mangle:POSTROUTING:IPv6', - 'mangle:ff:IPv6', - 'security:INPUT:IPv6', - 'security:FORWARD:IPv6', - 'security:OUTPUT:IPv6', - ':INPUT:IPv6', - ':FORWARD:IPv6', - ':OUTPUT:IPv6', - ':test:IPv6', - ] - allow(provider).to receive(:execute).with(['/sbin/ip6tables-save']).and_return(' -# Generated by ip6tables-save v1.4.9 on Mon Jan 2 01:31:39 2012 -*raw -:PREROUTING ACCEPT [2173:489241] -:OUTPUT ACCEPT [0:0] -:ff - [0:0] -COMMIT -# Completed on Mon Jan 2 01:31:39 2012 -# Generated by ip6tables-save v1.4.9 on Mon Jan 2 01:31:39 2012 -*mangle -:PREROUTING ACCEPT [2301:518373] -:INPUT ACCEPT [0:0] -:FORWARD ACCEPT [0:0] -:OUTPUT ACCEPT [0:0] -:POSTROUTING ACCEPT [0:0] -:ff - [0:0] -COMMIT -# Completed on Mon Jan 2 01:31:39 2012 -# Generated by ip6tables-save v1.4.9 on Mon Jan 2 01:31:39 2012 -*filter -:INPUT ACCEPT [0:0] -:FORWARD DROP [0:0] -:OUTPUT ACCEPT [20:1292] -:test - [0:0] -COMMIT -# Completed on Mon Jan 2 01:31:39 2012 -') - @all = ebtables + iptables + ip6tables - # IPv4 and IPv6 names also exist as resources {table}:{chain}:IP and {table}:{chain}: - iptables.each { |name| @all += [ name[0..-3], name[0..-5] ] } - ip6tables.each { |name| @all += [ name[0..-3], name[0..-5] ] } - end + describe 'iptables chain resource parsing' do + let(:provider) { Puppet::Type.type(:firewallchain).provider(:iptables_chain) } + + before :each do + ebtables = ['BROUTE:BROUTING:ethernet', + 'BROUTE:broute:ethernet', + ':INPUT:ethernet', + ':FORWARD:ethernet', + ':OUTPUT:ethernet', + ':filter:ethernet', + ':filterdrop:ethernet', + ':filterreturn:ethernet', + 'NAT:PREROUTING:ethernet', + 'NAT:OUTPUT:ethernet', + 'NAT:POSTROUTING:ethernet'] + allow(provider).to receive(:execute).with(['/sbin/ebtables-save']).and_return(' + *broute + :BROUTING ACCEPT + :broute ACCEPT + + *filter + :INPUT ACCEPT + :FORWARD ACCEPT + :OUTPUT ACCEPT + :filter ACCEPT + :filterdrop DROP + :filterreturn RETURN + + *nat + :PREROUTING ACCEPT + :OUTPUT ACCEPT + :POSTROUTING ACCEPT + ') + + iptables = [ + 'raw:PREROUTING:IPv4', + 'raw:OUTPUT:IPv4', + 'raw:raw:IPv4', + 'mangle:PREROUTING:IPv4', + 'mangle:INPUT:IPv4', + 'mangle:FORWARD:IPv4', + 'mangle:OUTPUT:IPv4', + 'mangle:POSTROUTING:IPv4', + 'mangle:mangle:IPv4', + 'NAT:PREROUTING:IPv4', + 'NAT:OUTPUT:IPv4', + 'NAT:POSTROUTING:IPv4', + 'NAT:mangle:IPv4', + 'NAT:mangle:IPv4', + 'NAT:mangle:IPv4', + 'security:INPUT:IPv4', + 'security:FORWARD:IPv4', + 'security:OUTPUT:IPv4', + ':$5()*&%\'"^$): :IPv4', + ] + allow(provider).to receive(:execute).with(['/sbin/iptables-save']).and_return(' + # Generated by iptables-save v1.4.9 on Mon Jan 2 01:20:06 2012 + *raw + :PREROUTING ACCEPT [12:1780] + :OUTPUT ACCEPT [19:1159] + :raw - [0:0] + COMMIT + # Completed on Mon Jan 2 01:20:06 2012 + # Generated by iptables-save v1.4.9 on Mon Jan 2 01:20:06 2012 + *mangle + :PREROUTING ACCEPT [12:1780] + :INPUT ACCEPT [12:1780] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [19:1159] + :POSTROUTING ACCEPT [19:1159] + :mangle - [0:0] + COMMIT + # Completed on Mon Jan 2 01:20:06 2012 + # Generated by iptables-save v1.4.9 on Mon Jan 2 01:20:06 2012 + *nat + :PREROUTING ACCEPT [2242:639750] + :OUTPUT ACCEPT [5176:326206] + :POSTROUTING ACCEPT [5162:325382] + COMMIT + # Completed on Mon Jan 2 01:20:06 2012 + # Generated by iptables-save v1.4.9 on Mon Jan 2 01:20:06 2012 + *filter + :INPUT ACCEPT [0:0] + :FORWARD DROP [0:0] + :OUTPUT ACCEPT [5673:420879] + :$5()*&%\'"^$): - [0:0] + COMMIT + # Completed on Mon Jan 2 01:20:06 2012 + ') + ip6tables = [ + 'raw:PREROUTING:IPv6', + 'raw:OUTPUT:IPv6', + 'raw:ff:IPv6', + 'mangle:PREROUTING:IPv6', + 'mangle:INPUT:IPv6', + 'mangle:FORWARD:IPv6', + 'mangle:OUTPUT:IPv6', + 'mangle:POSTROUTING:IPv6', + 'mangle:ff:IPv6', + 'security:INPUT:IPv6', + 'security:FORWARD:IPv6', + 'security:OUTPUT:IPv6', + ':INPUT:IPv6', + ':FORWARD:IPv6', + ':OUTPUT:IPv6', + ':test:IPv6', + ] + allow(provider).to receive(:execute).with(['/sbin/ip6tables-save']).and_return(' + # Generated by ip6tables-save v1.4.9 on Mon Jan 2 01:31:39 2012 + *raw + :PREROUTING ACCEPT [2173:489241] + :OUTPUT ACCEPT [0:0] + :ff - [0:0] + COMMIT + # Completed on Mon Jan 2 01:31:39 2012 + # Generated by ip6tables-save v1.4.9 on Mon Jan 2 01:31:39 2012 + *mangle + :PREROUTING ACCEPT [2301:518373] + :INPUT ACCEPT [0:0] + :FORWARD ACCEPT [0:0] + :OUTPUT ACCEPT [0:0] + :POSTROUTING ACCEPT [0:0] + :ff - [0:0] + COMMIT + # Completed on Mon Jan 2 01:31:39 2012 + # Generated by ip6tables-save v1.4.9 on Mon Jan 2 01:31:39 2012 + *filter + :INPUT ACCEPT [0:0] + :FORWARD DROP [0:0] + :OUTPUT ACCEPT [20:1292] + :test - [0:0] + COMMIT + # Completed on Mon Jan 2 01:31:39 2012 + ') + @all = ebtables + iptables + ip6tables + # IPv4 and IPv6 names also exist as resources {table}:{chain}:IP and {table}:{chain}: + iptables.each { |name| @all += [name[0..-3], name[0..-5]] } + ip6tables.each { |name| @all += [name[0..-3], name[0..-5]] } + end - it 'should have all in parsed resources' do - provider.instances.each do |resource| - @all.include?(resource.name) + it 'has all in parsed resources' do + provider.instances.each do |resource| + @all.include?(resource.name) # rubocop:disable RSpec/InstanceVariable + end end end - end diff --git a/spec/unit/puppet/provider/iptables_spec.rb b/spec/unit/puppet/provider/iptables_spec.rb index 4faacab..b686116 100644 --- a/spec/unit/puppet/provider/iptables_spec.rb +++ b/spec/unit/puppet/provider/iptables_spec.rb @@ -1,4 +1,4 @@ -#!/usr/bin/env rspec +#!/usr/bin/env rspec # rubocop:disable Lint/ScriptPermission : Puppet error? require 'spec_helper' if Puppet::Util::Package.versioncmp(Puppet.version, '3.4.0') < 0 @@ -7,15 +7,15 @@ else require 'puppet/confine/exists' end -describe 'iptables provider detection' do +describe 'iptables provider detection' do # rubocop:disable RSpec/MultipleDescribes if Puppet::Util::Package.versioncmp(Puppet.version, '3.4.0') < 0 - let(:exists) { + let(:exists) do Puppet::Provider::Confine::Exists - } + end else - let(:exists) { + let(:exists) do Puppet::Confine::Exists - } + end end before :each do @@ -27,49 +27,41 @@ describe 'iptables provider detection' do allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Debian') end - it "is expected to default to iptables provider if /sbin/iptables[-save] exists" do + it 'is expected to default to iptables provider if /sbin/iptables[-save] exists' do # Stub lookup for /sbin/iptables & /sbin/iptables-save - allow(exists).to receive(:which).with("iptables"). - and_return "/sbin/iptables" - allow(exists).to receive(:which).with("iptables-save"). - and_return "/sbin/iptables-save" + allow(exists).to receive(:which).with('iptables').and_return '/sbin/iptables' + allow(exists).to receive(:which).with('iptables-save').and_return '/sbin/iptables-save' # Every other command is expected to return false so we don't pick up any # other providers - allow(exists).to receive(:which) { |value| - ! ["iptables","iptables-save"].include?(value) - }.and_return false + allow(exists).to receive(:which) { |value| !['iptables', 'iptables-save'].include?(value) }.and_return false # Create a resource instance and make sure the provider is iptables - resource = Puppet::Type.type(:firewall).new({ - :name => '000 test foo', - }) - expect(resource.provider.class.to_s).to eq("Puppet::Type::Firewall::ProviderIptables") + resource = Puppet::Type.type(:firewall).new(name: '000 test foo') + expect(resource.provider.class.to_s).to eq('Puppet::Type::Firewall::ProviderIptables') end end describe 'iptables provider' do let(:provider) { Puppet::Type.type(:firewall).provider(:iptables) } - let(:resource) { - Puppet::Type.type(:firewall).new({ - :name => '000 test foo', - :action => 'accept', - }) - } + let(:resource) do + Puppet::Type.type(:firewall).new(name: '000 test foo', + action: 'accept') + end before :each do allow(Puppet::Type::Firewall).to receive(:defaultprovider).and_return provider - allow(provider).to receive(:command).with(:iptables_save).and_return "/sbin/iptables-save" + allow(provider).to receive(:command).with(:iptables_save).and_return '/sbin/iptables-save' # Stub iptables version - allow(Facter.fact(:iptables_version)).to receive(:value).and_return("1.4.2") + allow(Facter.fact(:iptables_version)).to receive(:value).and_return('1.4.2') - allow(Puppet::Util::Execution).to receive(:execute).and_return "" - allow(Puppet::Util).to receive(:which).with("iptables-save"). - and_return "/sbin/iptables-save" + allow(Puppet::Util::Execution).to receive(:execute).and_return '' + allow(Puppet::Util).to receive(:which).with('iptables-save') + .and_return '/sbin/iptables-save' end - it 'is expected to be able to get a list of existing rules' do + it 'is expected to be able to get a list of existing rules' do # rubocop:disable RSpec/MultipleExpectations provider.instances.each do |rule| expect(rule).to be_instance_of(provider) expect(rule.properties[:provider].to_s).to eq(provider.name.to_s) @@ -77,131 +69,140 @@ describe 'iptables provider' do end it 'is expected to ignore lines with fatal errors' do - allow(Puppet::Util::Execution).to receive(:execute).with(['/sbin/iptables-save']). - and_return("FATAL: Could not load /lib/modules/2.6.18-028stab095.1/modules.dep: No such file or directory") + allow(Puppet::Util::Execution).to receive(:execute).with(['/sbin/iptables-save']) + .and_return('FATAL: Could not load /lib/modules/2.6.18-028stab095.1/modules.dep: No such file or directory') expect(provider.instances.length).to be_zero end describe '#insert_order' do - let(:iptables_save_output) { [ - '-A INPUT -s 8.0.0.2/32 -p tcp -m multiport --ports 100 -m comment --comment "100 test" -j ACCEPT', - '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 200 -m comment --comment "200 test" -j ACCEPT', - '-A INPUT -s 8.0.0.4/32 -p tcp -m multiport --ports 300 -m comment --comment "300 test" -j ACCEPT' - ] } + let(:iptables_save_output) do + [ + '-A INPUT -s 8.0.0.2/32 -p tcp -m multiport --ports 100 -m comment --comment "100 test" -j ACCEPT', + '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 200 -m comment --comment "200 test" -j ACCEPT', + '-A INPUT -s 8.0.0.4/32 -p tcp -m multiport --ports 300 -m comment --comment "300 test" -j ACCEPT', + ] + end let(:resources) do - iptables_save_output.each_with_index.collect { |l,index| provider.rule_to_hash(l, 'filter', index) } + iptables_save_output.each_with_index.map { |l, index| provider.rule_to_hash(l, 'filter', index) } end let(:providers) do - resources.collect { |r| provider.new(r) } + resources.map { |r| provider.new(r) } end + it 'understands offsets for adding rules to the beginning' do - resource = Puppet::Type.type(:firewall).new({ :name => '001 test', }) + resource = Puppet::Type.type(:firewall).new(name: '001 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(1) # 1-indexed end it 'understands offsets for editing rules at the beginning' do - resource = Puppet::Type.type(:firewall).new({ :name => '100 test', }) + resource = Puppet::Type.type(:firewall).new(name: '100 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(1) end it 'understands offsets for adding rules to the middle' do - resource = Puppet::Type.type(:firewall).new({ :name => '101 test', }) + resource = Puppet::Type.type(:firewall).new(name: '101 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(2) end it 'understands offsets for editing rules at the middle' do - resource = Puppet::Type.type(:firewall).new({ :name => '200 test', }) + resource = Puppet::Type.type(:firewall).new(name: '200 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(2) end it 'understands offsets for adding rules to the end' do - resource = Puppet::Type.type(:firewall).new({ :name => '301 test', }) + resource = Puppet::Type.type(:firewall).new(name: '301 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(4) end it 'understands offsets for editing rules at the end' do - resource = Puppet::Type.type(:firewall).new({ :name => '300 test', }) + resource = Puppet::Type.type(:firewall).new(name: '300 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(3) end context 'with unname rules between' do - let(:iptables_save_output) { [ - '-A INPUT -s 8.0.0.2/32 -p tcp -m multiport --ports 100 -m comment --comment "100 test" -j ACCEPT', - '-A INPUT -s 8.0.0.2/32 -p tcp -m multiport --ports 150 -m comment --comment "150 test" -j ACCEPT', - '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 200 -j ACCEPT', - '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 250 -j ACCEPT', - '-A INPUT -s 8.0.0.4/32 -p tcp -m multiport --ports 300 -m comment --comment "300 test" -j ACCEPT', - '-A INPUT -s 8.0.0.4/32 -p tcp -m multiport --ports 350 -m comment --comment "350 test" -j ACCEPT', - ] } + let(:iptables_save_output) do + [ + '-A INPUT -s 8.0.0.2/32 -p tcp -m multiport --ports 100 -m comment --comment "100 test" -j ACCEPT', + '-A INPUT -s 8.0.0.2/32 -p tcp -m multiport --ports 150 -m comment --comment "150 test" -j ACCEPT', + '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 200 -j ACCEPT', + '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 250 -j ACCEPT', + '-A INPUT -s 8.0.0.4/32 -p tcp -m multiport --ports 300 -m comment --comment "300 test" -j ACCEPT', + '-A INPUT -s 8.0.0.4/32 -p tcp -m multiport --ports 350 -m comment --comment "350 test" -j ACCEPT', + ] + end + it 'understands offsets for adding rules before unnamed rules' do - resource = Puppet::Type.type(:firewall).new({ :name => '001 test', }) + resource = Puppet::Type.type(:firewall).new(name: '001 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(1) end it 'understands offsets for editing rules before unnamed rules' do - resource = Puppet::Type.type(:firewall).new({ :name => '100 test', }) + resource = Puppet::Type.type(:firewall).new(name: '100 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(1) end it 'understands offsets for adding rules between managed rules' do - resource = Puppet::Type.type(:firewall).new({ :name => '120 test', }) + resource = Puppet::Type.type(:firewall).new(name: '120 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(2) end it 'understands offsets for adding rules between unnamed rules' do - resource = Puppet::Type.type(:firewall).new({ :name => '151 test', }) + resource = Puppet::Type.type(:firewall).new(name: '151 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(3) end it 'understands offsets for adding rules after unnamed rules' do - resource = Puppet::Type.type(:firewall).new({ :name => '351 test', }) + resource = Puppet::Type.type(:firewall).new(name: '351 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(7) end end context 'with unname rules before and after' do - let(:iptables_save_output) { [ - '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 050 -j ACCEPT', - '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 090 -j ACCEPT', - '-A INPUT -s 8.0.0.2/32 -p tcp -m multiport --ports 100 -m comment --comment "100 test" -j ACCEPT', - '-A INPUT -s 8.0.0.2/32 -p tcp -m multiport --ports 150 -m comment --comment "150 test" -j ACCEPT', - '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 200 -j ACCEPT', - '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 250 -j ACCEPT', - '-A INPUT -s 8.0.0.4/32 -p tcp -m multiport --ports 300 -m comment --comment "300 test" -j ACCEPT', - '-A INPUT -s 8.0.0.4/32 -p tcp -m multiport --ports 350 -m comment --comment "350 test" -j ACCEPT', - '-A INPUT -s 8.0.0.5/32 -p tcp -m multiport --ports 400 -j ACCEPT', - '-A INPUT -s 8.0.0.5/32 -p tcp -m multiport --ports 450 -j ACCEPT', - ] } + let(:iptables_save_output) do + [ + '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 050 -j ACCEPT', + '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 090 -j ACCEPT', + '-A INPUT -s 8.0.0.2/32 -p tcp -m multiport --ports 100 -m comment --comment "100 test" -j ACCEPT', + '-A INPUT -s 8.0.0.2/32 -p tcp -m multiport --ports 150 -m comment --comment "150 test" -j ACCEPT', + '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 200 -j ACCEPT', + '-A INPUT -s 8.0.0.3/32 -p tcp -m multiport --ports 250 -j ACCEPT', + '-A INPUT -s 8.0.0.4/32 -p tcp -m multiport --ports 300 -m comment --comment "300 test" -j ACCEPT', + '-A INPUT -s 8.0.0.4/32 -p tcp -m multiport --ports 350 -m comment --comment "350 test" -j ACCEPT', + '-A INPUT -s 8.0.0.5/32 -p tcp -m multiport --ports 400 -j ACCEPT', + '-A INPUT -s 8.0.0.5/32 -p tcp -m multiport --ports 450 -j ACCEPT', + ] + end + it 'understands offsets for adding rules before unnamed rules' do - resource = Puppet::Type.type(:firewall).new({ :name => '001 test', }) + resource = Puppet::Type.type(:firewall).new(name: '001 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(1) end it 'understands offsets for editing rules before unnamed rules' do - resource = Puppet::Type.type(:firewall).new({ :name => '100 test', }) + resource = Puppet::Type.type(:firewall).new(name: '100 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(3) end it 'understands offsets for adding rules between managed rules' do - resource = Puppet::Type.type(:firewall).new({ :name => '120 test', }) + resource = Puppet::Type.type(:firewall).new(name: '120 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(4) end it 'understands offsets for adding rules between unnamed rules' do - resource = Puppet::Type.type(:firewall).new({ :name => '151 test', }) + resource = Puppet::Type.type(:firewall).new(name: '151 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(5) end it 'understands offsets for adding rules after unnamed rules' do - resource = Puppet::Type.type(:firewall).new({ :name => '351 test', }) + resource = Puppet::Type.type(:firewall).new(name: '351 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(9) end it 'understands offsets for adding rules at the end' do - resource = Puppet::Type.type(:firewall).new({ :name => '950 test', }) + resource = Puppet::Type.type(:firewall).new(name: '950 test') allow(resource.provider.class).to receive(:instances).and_return(providers) expect(resource.provider.insert_order).to eq(11) end @@ -212,29 +213,30 @@ describe 'iptables provider' do load 'spec/fixtures/iptables/conversion_hash.rb' describe 'when converting rules to resources' do - ARGS_TO_HASH.each do |test_name,data| + ARGS_TO_HASH.each do |test_name, data| describe "for test data '#{test_name}'" do let(:resource) { provider.rule_to_hash(data[:line], data[:table], 0) } + # If this option is enabled, make sure the error was raised - if data[:produce_warning] then - it "the input rules should produce a warning by rules_to_hash" do - expect(provider).to receive(:warning).with(/Skipping unparsable iptables rule/) - resource # force resource to get evaluated + if data[:produce_warning] + it 'the input rules should produce a warning by rules_to_hash' do + allow(provider).to receive(:warning).with(%r{Skipping unparsable iptables rule}) + resource # force resource to get evaluated end end # If this option is enabled, make sure the parameters exactly match - if data[:compare_all] then - it "the parameter hash keys should be the same as returned by rules_to_hash" do + if data[:compare_all] + it 'the parameter hash keys should be the same as returned by rules_to_hash' do expect(resource.keys).to match_array(data[:params].keys) end end # Iterate across each parameter, creating an example for comparison data[:params].each do |param_name, param_value| - it "the parameter '#{param_name.to_s}' should match #{param_value.inspect}" do + it "the parameter '#{param_name}' should match #{param_value.inspect}" do # rubocop:disable RSpec/MultipleExpectations # booleans get cludged to string "true" - if param_value == true then + if param_value == true expect(resource[param_name]).to be_truthy else expect(resource[param_name]).to eq(data[:params][param_name]) @@ -246,7 +248,7 @@ describe 'iptables provider' do end describe 'when working out general_args' do - HASH_TO_ARGS.each do |test_name,data| + HASH_TO_ARGS.each do |test_name, data| describe "for test data '#{test_name}'" do let(:resource) { Puppet::Type.type(:firewall).new(data[:params]) } let(:provider) { Puppet::Type.type(:firewall).provider(:iptables) } @@ -260,9 +262,9 @@ describe 'iptables provider' do end describe 'when converting rules without comments to resources' do - let(:sample_rule) { + let(:sample_rule) do '-A INPUT -s 1.1.1.1 -d 1.1.1.1 -p tcp -m multiport --dports 7061,7062 -m multiport --sports 7061,7062 -j ACCEPT' - } + end let(:resource) { provider.rule_to_hash(sample_rule, 'filter', 0) } let(:instance) { provider.new(resource) } @@ -270,22 +272,20 @@ describe 'iptables provider' do expect(resource[:name]).to eq("9000 #{Digest::MD5.hexdigest(resource[:line])}") end + resource_types = [:chain, :source, :destination, :proto, :dport, :sport, :action] + rule_values = ['INPUT', '1.1.1.1/32', '1.1.1.1/32', 'tcp', %w[7061 7062], %w[7061 7062], 'accept'] it 'parsed the rule arguments correctly' do - expect(resource[:chain]).to eq('INPUT') - expect(resource[:source]).to eq('1.1.1.1/32') - expect(resource[:destination]).to eq('1.1.1.1/32') - expect(resource[:proto]).to eq('tcp') - expect(resource[:dport]).to eq(['7061', '7062']) - expect(resource[:sport]).to eq(['7061', '7062']) - expect(resource[:action]).to eq('accept') + resource_types.each_with_index do |type, index| + expect(resource[type]).to eq(rule_values[index]) + end end end describe 'when converting existing rules generates by system-config-firewall-tui to resources' do - let(:sample_rule) { + let(:sample_rule) do # as generated by iptables-save from rules created with system-config-firewall-tui '-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT' - } + end let(:resource) { provider.rule_to_hash(sample_rule, 'filter', 0) } let(:instance) { provider.new(resource) } @@ -293,12 +293,12 @@ describe 'iptables provider' do expect(resource[:name]).to eq("9000 #{Digest::MD5.hexdigest(resource[:line])}") end + resource_types = [:chain, :proto, :dport, :state, :action] + rule_values = ['INPUT', 'tcp', ['22'], ['NEW'], 'accept'] it 'parse arguments' do - expect(resource[:chain]).to eq('INPUT') - expect(resource[:proto]).to eq('tcp') - expect(resource[:dport]).to eq(['22']) - expect(resource[:state]).to eq(['NEW']) - expect(resource[:action]).to eq('accept') + resource_types.each_with_index do |type, index| + expect(resource[type]).to eq(rule_values[index]) + end end end @@ -318,35 +318,33 @@ describe 'iptables provider' do end it 'fails when modifying the chain' do - expect { instance.chain = "OUTPUT" }.to raise_error(/is not supported/) + expect { instance.chain = 'OUTPUT' }.to raise_error(%r{is not supported}) end end describe 'when inverting rules' do - let(:resource) { - Puppet::Type.type(:firewall).new({ - :name => '040 partial invert', - :table => 'filter', - :action => 'accept', - :chain => 'nova-compute-FORWARD', - :source => '0.0.0.0/32', - :destination => '255.255.255.255/32', - :sport => ['! 78','79','http'], - :dport => ['77','! 76'], - :proto => 'udp', - }) - } + let(:resource) do + Puppet::Type.type(:firewall).new(name: '040 partial invert', + table: 'filter', + action: 'accept', + chain: 'nova-compute-FORWARD', + source: '0.0.0.0/32', + destination: '255.255.255.255/32', + sport: ['! 78', '79', 'http'], + dport: ['77', '! 76'], + proto: 'udp') + end let(:instance) { provider.new(resource) } it 'fails when not all array items are inverted' do - expect { instance.insert }.to raise_error Puppet::Error, /but '79', '80' are not prefixed/ + expect { instance.insert }.to raise_error RuntimeError, %r{but '79', '80' are not prefixed} end end describe 'when deleting resources' do - let(:sample_rule) { + let(:sample_rule) do '-A INPUT -s 1.1.1.1 -d 1.1.1.1 -p tcp -m multiport --dports 7061,7062 -m multiport --sports 7061,7062 -j ACCEPT' - } + end let(:resource) { provider.rule_to_hash(sample_rule, 'filter', 0) } let(:instance) { provider.new(resource) } @@ -359,35 +357,33 @@ describe 'iptables provider' do end it 'delete_args is the same as the rule string when joined' do - expect(instance.delete_args.join(' ')).to eq(sample_rule.gsub(/\-A/, - '-t filter -D')) + expect(instance.delete_args.join(' ')).to eq(sample_rule.gsub(%r{\-A}, + '-t filter -D')) end end end describe 'ip6tables provider' do let(:provider6) { Puppet::Type.type(:firewall).provider(:ip6tables) } - let(:resource) { - Puppet::Type.type(:firewall).new({ - :name => '000 test foo', - :action => 'accept', - :provider => "ip6tables", - }) - } + let(:resource) do + Puppet::Type.type(:firewall).new(name: '000 test foo', + action: 'accept', + provider: 'ip6tables') + end before :each do allow(Puppet::Type::Firewall).to receive(:ip6tables).and_return provider6 - allow(provider6).to receive(:command).with(:ip6tables_save).and_return "/sbin/ip6tables-save" + allow(provider6).to receive(:command).with(:ip6tables_save).and_return '/sbin/ip6tables-save' # Stub iptables version allow(Facter.fact(:ip6tables_version)).to receive(:value).and_return '1.4.7' allow(Puppet::Util::Execution).to receive(:execute).and_return '' - allow(Puppet::Util).to receive(:which).with("ip6tables-save"). - and_return "/sbin/ip6tables-save" + allow(Puppet::Util).to receive(:which).with('ip6tables-save') + .and_return '/sbin/ip6tables-save' end - it 'is expected to be able to get a list of existing rules' do + it 'is expected to be able to get a list of existing rules' do # rubocop:disable RSpec/MultipleExpectations provider6.instances.each do |rule| expect(rule).to be_instance_of(provider6) expect(rule.properties[:provider6].to_s).to eql provider6.name.to_s @@ -395,8 +391,8 @@ describe 'ip6tables provider' do end it 'is expected to ignore lines with fatal errors' do - allow(Puppet::Util::Execution).to receive(:execute).with(['/sbin/ip6tables-save']). - and_return("FATAL: Could not load /lib/modules/2.6.18-028stab095.1/modules.dep: No such file or directory") + allow(Puppet::Util::Execution).to receive(:execute).with(['/sbin/ip6tables-save']) + .and_return('FATAL: Could not load /lib/modules/2.6.18-028stab095.1/modules.dep: No such file or directory') expect(provider6.instances.length).to eq 0 end @@ -404,20 +400,20 @@ describe 'ip6tables provider' do load 'spec/fixtures/ip6tables/conversion_hash.rb' describe 'when converting rules to resources' do - ARGS_TO_HASH6.each do |test_name,data| + ARGS_TO_HASH6.each do |test_name, data| describe "for test data '#{test_name}'" do let(:resource) { provider6.rule_to_hash(data[:line], data[:table], 0) } # If this option is enabled, make sure the parameters exactly match - if data[:compare_all] then - it "the parameter hash keys should be the same as returned by rules_to_hash" do + if data[:compare_all] + it 'the parameter hash keys should be the same as returned by rules_to_hash' do expect(resource.keys).to match data[:params].keys end end # Iterate across each parameter, creating an example for comparison data[:params].each do |param_name, param_value| - it "the parameter '#{param_name.to_s}' should match #{param_value.inspect}" do + it "the parameter '#{param_name}' should match #{param_value.inspect}" do expect(resource[param_name]).to eql data[:params][param_name] end end @@ -426,14 +422,14 @@ describe 'ip6tables provider' do end describe 'when working out general_args' do - HASH_TO_ARGS6.each do |test_name,data| + HASH_TO_ARGS6.each do |test_name, data| describe "for test data '#{test_name}'" do let(:resource) { Puppet::Type.type(:firewall).new(data[:params]) } let(:provider6) { Puppet::Type.type(:firewall).provider(:ip6tables) } let(:instance) { provider6.new(resource) } it 'general_args should be valid' do - data[:args].unshift("--wait") if instance.general_args.flatten.include? '--wait' + data[:args].unshift('--wait') if instance.general_args.flatten.include? '--wait' expect(instance.general_args.flatten).to eql data[:args] end end diff --git a/spec/unit/puppet/type/firewall_spec.rb b/spec/unit/puppet/type/firewall_spec.rb index d09886b..bba2f15 100755 --- a/spec/unit/puppet/type/firewall_spec.rb +++ b/spec/unit/puppet/type/firewall_spec.rb @@ -4,14 +4,14 @@ require 'spec_helper' firewall = Puppet::Type.type(:firewall) -describe firewall do - before :each do - @class = firewall - @provider = double 'provider' - allow(@provider).to receive(:name).and_return(:iptables) - allow(Puppet::Type::Firewall).to receive(:defaultprovider).and_return @provider +describe firewall do # rubocop:disable RSpec/MultipleDescribes + let(:firewall_class) { firewall } + let(:provider) { instance_double('provider') } + let(:resource) { firewall_class.new(name: '000 test foo') } - @resource = @class.new({:name => '000 test foo'}) + before :each do + allow(provider).to receive(:name).and_return(:iptables) + allow(Puppet::Type::Firewall).to receive(:defaultprovider).and_return provider # Stub iptables version allow(Facter.fact(:iptables_version)).to receive(:value).and_return('1.4.2') @@ -22,117 +22,117 @@ describe firewall do allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Debian') end - it 'should have :name be its namevar' do - expect(@class.key_attributes).to eql [:name] + it 'has :name be its namevar' do + expect(firewall_class.key_attributes).to eql [:name] end describe ':name' do - it 'should accept a name' do - @resource[:name] = '000-test-foo' - expect(@resource[:name]).to eql '000-test-foo' + it 'accepts a name' do + resource[:name] = '000-test-foo' + expect(resource[:name]).to eql '000-test-foo' end - it 'should not accept a name with non-ASCII chars' do - expect(lambda { @resource[:name] = '%*#^(#$' }).to raise_error(Puppet::Error) + it 'does not accept a name with non-ASCII chars' do + expect(-> { resource[:name] = '%*#^(#$' }).to raise_error(Puppet::Error) end end describe ':action' do - it "should have no default" do - res = @class.new(:name => "000 test") - expect(res.parameters[:action]).to eql nil + it 'has no default' do + res = firewall_class.new(name: '000 test') + expect(res.parameters[:action]).to be nil end [:accept, :drop, :reject].each do |action| it "should accept value #{action}" do - @resource[:action] = action - expect(@resource[:action]).to eql action + resource[:action] = action + expect(resource[:action]).to eql action end end - it 'should fail when value is not recognized' do - expect(lambda { @resource[:action] = 'not valid' }).to raise_error(Puppet::Error) + it 'fails when value is not recognized' do + expect(-> { resource[:action] = 'not valid' }).to raise_error(Puppet::Error) end end describe ':chain' do [:INPUT, :FORWARD, :OUTPUT, :PREROUTING, :POSTROUTING].each do |chain| it "should accept chain value #{chain}" do - @resource[:chain] = chain - expect(@resource[:chain]).to eql chain + resource[:chain] = chain + expect(resource[:chain]).to eql chain end end - it 'should fail when the chain value is not recognized' do - expect(lambda { @resource[:chain] = 'not valid' }).to raise_error(Puppet::Error) + it 'fails when the chain value is not recognized' do + expect(-> { resource[:chain] = 'not valid' }).to raise_error(Puppet::Error) end end describe ':table' do [:nat, :mangle, :filter, :raw].each do |table| it "should accept table value #{table}" do - @resource[:table] = table - expect(@resource[:table]).to eql table + resource[:table] = table + expect(resource[:table]).to eql table end end - it "should fail when table value is not recognized" do - expect(lambda { @resource[:table] = 'not valid' }).to raise_error(Puppet::Error) + it 'fails when table value is not recognized' do + expect(-> { resource[:table] = 'not valid' }).to raise_error(Puppet::Error) end end describe ':proto' do [:ip, :tcp, :udp, :icmp, :esp, :ah, :vrrp, :igmp, :ipencap, :ipv4, :ipv6, :ospf, :gre, :pim, :all].each do |proto| it "should accept proto value #{proto}" do - @resource[:proto] = proto - expect(@resource[:proto]).to eql proto + resource[:proto] = proto + expect(resource[:proto]).to eql proto end end - it "should fail when proto value is not recognized" do - expect(lambda { @resource[:proto] = 'foo' }).to raise_error(Puppet::Error) + it 'fails when proto value is not recognized' do + expect(-> { resource[:proto] = 'foo' }).to raise_error(Puppet::Error) end end describe ':jump' do - it "should have no default" do - res = @class.new(:name => "000 test") - expect(res.parameters[:jump]).to eql nil + it 'has no default' do + res = firewall_class.new(name: '000 test') + expect(res.parameters[:jump]).to be nil end - ['QUEUE', 'RETURN', 'DNAT', 'SNAT', 'LOG', 'NFLOG', 'MASQUERADE', 'REDIRECT', 'MARK'].each do |jump| + %w[QUEUE RETURN DNAT SNAT LOG NFLOG MASQUERADE REDIRECT MARK].each do |jump| it "should accept jump value #{jump}" do - @resource[:jump] = jump - expect(@resource[:jump]).to eql jump + resource[:jump] = jump + expect(resource[:jump]).to eql jump end end - ['ACCEPT', 'DROP', 'REJECT'].each do |jump| + %w[ACCEPT DROP REJECT].each do |jump| it "should now fail when value #{jump}" do - expect(lambda { @resource[:jump] = jump }).to raise_error(Puppet::Error) + expect(-> { resource[:jump] = jump }).to raise_error(Puppet::Error) end end - it "should fail when jump value is not recognized" do - expect(lambda { @resource[:jump] = '%^&*' }).to raise_error(Puppet::Error) + it 'fails when jump value is not recognized' do + expect(-> { resource[:jump] = '%^&*' }).to raise_error(Puppet::Error) end end [:source, :destination].each do |addr| describe addr do it "should accept a #{addr} as a string" do - @resource[addr] = '127.0.0.1' - expect(@resource[addr]).to eql '127.0.0.1/32' + resource[addr] = '127.0.0.1' + expect(resource[addr]).to eql '127.0.0.1/32' end ['0.0.0.0/0', '::/0'].each do |prefix| it "should be nil for zero prefix length address #{prefix}" do - @resource[addr] = prefix - expect(@resource[addr]).to eql nil + resource[addr] = prefix + expect(resource[addr]).to be nil end end it "should accept a negated #{addr} as a string" do - @resource[addr] = '! 127.0.0.1' - expect(@resource[addr]).to eql '! 127.0.0.1/32' + resource[addr] = '! 127.0.0.1' + expect(resource[addr]).to eql '! 127.0.0.1/32' end end end @@ -140,88 +140,88 @@ describe firewall do [:dport, :sport].each do |port| describe port do it "should accept a #{port} as string" do - @resource[port] = '22' - expect(@resource[port]).to eql ['22'] + resource[port] = '22' + expect(resource[port]).to eql ['22'] end it "should accept a #{port} as an array" do - @resource[port] = ['22','23'] - expect(@resource[port]).to eql ['22','23'] + resource[port] = %w[22 23] + expect(resource[port]).to eql %w[22 23] end it "should accept a #{port} as a number" do - @resource[port] = 22 - expect(@resource[port]).to eql ['22'] + resource[port] = 22 + expect(resource[port]).to eql ['22'] end it "should accept a #{port} as a hyphen separated range" do - @resource[port] = ['22-1000'] - expect(@resource[port]).to eql ['22-1000'] + resource[port] = ['22-1000'] + expect(resource[port]).to eql ['22-1000'] end it "should accept a #{port} as a combination of arrays of single and " \ - "hyphen separated ranges" do + 'hyphen separated ranges' do - @resource[port] = ['22-1000','33','3000-4000'] - expect(@resource[port]).to eql ['22-1000','33','3000-4000'] + resource[port] = ['22-1000', '33', '3000-4000'] + expect(resource[port]).to eql ['22-1000', '33', '3000-4000'] end it "should convert a port name for #{port} to its number" do - @resource[port] = 'ssh' - expect(@resource[port]).to eql ['22'] + resource[port] = 'ssh' + expect(resource[port]).to eql ['22'] end it "should not accept something invalid for #{port}" do - expect { @resource[port] = 'something odd' }.to raise_error(Puppet::Error, /^Parameter .+ failed.+Munging failed for value ".+" in class .+: no such service/) + expect { resource[port] = 'something odd' }.to raise_error(Puppet::Error, %r{^Parameter .+ failed.+Munging failed for value ".+" in class .+: no such service}) end it "should not accept something invalid in an array for #{port}" do - expect { @resource[port] = ['something odd','something even odder'] }.to raise_error(Puppet::Error, /^Parameter .+ failed.+Munging failed for value ".+" in class .+: no such service/) + expect { resource[port] = ['something odd', 'something even odder'] }.to raise_error(Puppet::Error, %r{^Parameter .+ failed.+Munging failed for value ".+" in class .+: no such service}) end end end describe 'port deprecated' do - it "raises a warning" do - expect(Puppet).to receive(:warning).with /port to firewall is deprecated/ - @resource[:port] = "22" + it 'raises a warning' do + allow(Puppet).to receive(:warning).with %r{port to firewall is deprecated} + resource[:port] = '22' end end [:dst_type, :src_type].each do |addrtype| describe addrtype do - it "should have no default" do - res = @class.new(:name => "000 test") - expect(res.parameters[addrtype]).to eql nil + it 'has no default' do + res = firewall_class.new(name: '000 test') + expect(res.parameters[addrtype]).to be nil end end [:UNSPEC, :UNICAST, :LOCAL, :BROADCAST, :ANYCAST, :MULTICAST, :BLACKHOLE, :UNREACHABLE, :PROHIBIT, :THROW, :NAT, :XRESOLVE].each do |type| it "should accept #{addrtype} value #{type}" do - @resource[addrtype] = type - expect(@resource[addrtype]).to eql type + resource[addrtype] = type + expect(resource[addrtype]).to eql type end end it "should fail when #{addrtype} value is not recognized" do - expect(lambda { @resource[addrtype] = 'foo' }).to raise_error(Puppet::Error) + expect(-> { resource[addrtype] = 'foo' }).to raise_error(Puppet::Error) end end [:iniface, :outiface].each do |iface| describe iface do it "should accept #{iface} value as a string" do - @resource[iface] = 'eth1' - expect(@resource[iface]).to eql 'eth1' + resource[iface] = 'eth1' + expect(resource[iface]).to eql 'eth1' end it "should accept a negated #{iface} value as a string" do - @resource[iface] = '! eth1' - expect(@resource[iface]).to eql '! eth1' + resource[iface] = '! eth1' + expect(resource[iface]).to eql '! eth1' end it "should accept an interface alias for the #{iface} value as a string" do - @resource[iface] = 'eth1:2' - expect(@resource[iface]).to eql 'eth1:2' + resource[iface] = 'eth1:2' + expect(resource[iface]).to eql 'eth1:2' end end end @@ -229,7 +229,7 @@ describe firewall do [:tosource, :todest, :to].each do |addr| describe addr do it "should accept #{addr} value as a string" do - @resource[addr] = '127.0.0.1' + resource[addr] = '127.0.0.1' end end end @@ -242,62 +242,61 @@ describe firewall do 'err' => '3', 'warn' => '4', 'warning' => '4', - 'not' => '5', + 'not' => '5', 'notice' => '5', 'info' => '6', - 'debug' => '7' + 'debug' => '7', } - values.each do |k,v| + values.each do |k, v| it { - @resource[:log_level] = k - expect(@resource[:log_level]).to eql v + resource[:log_level] = k + expect(resource[:log_level]).to eql v } it { - @resource[:log_level] = 3 - expect(@resource[:log_level]).to eql 3 + resource[:log_level] = 3 + expect(resource[:log_level]).to be 3 } - it { expect(lambda { @resource[:log_level] = 'foo' }).to raise_error(Puppet::Error) } + it { expect(-> { resource[:log_level] = 'foo' }).to raise_error(Puppet::Error) } end end describe 'NFLOG' do describe ':nflog_group' do - - [0,1,5,10].each do |v| + [0, 1, 5, 10].each do |v| it { - @resource[:nflog_group] = v - expect(@resource[:nflog_group]).to eq v + resource[:nflog_group] = v + expect(resource[:nflog_group]).to eq v } end - [-3,999999].each do |v| + [-3, 999_999].each do |v| it { - expect(lambda { @resource[:nflog_group] = v }).to raise_error(Puppet::Error, /2\^16\-1/) + expect(-> { resource[:nflog_group] = v }).to raise_error(Puppet::Error, %r{2\^16\-1}) } end end describe ':nflog_prefix' do - let(:valid_prefix) { "This is a valid prefix" } - let(:invalid_prefix) { "This is not a valid prefix. !t is longer than 64 char@cters for sure. How do I know? I c0unted." } + let(:valid_prefix) { 'This is a valid prefix' } + let(:invalid_prefix) { 'This is not a valid prefix. !t is longer than 64 char@cters for sure. How do I know? I c0unted.' } it { - @resource[:nflog_prefix] = valid_prefix - expect(@resource[:nflog_prefix]).to eq valid_prefix + resource[:nflog_prefix] = valid_prefix + expect(resource[:nflog_prefix]).to eq valid_prefix } it { - expect(lambda { @resource[:nflog_prefix] = invalid_prefix }).to raise_error(Puppet::Error, /64 characters/) + expect(-> { resource[:nflog_prefix] = invalid_prefix }).to raise_error(Puppet::Error, %r{64 characters}) } end end describe ':icmp' do icmp_codes = { - :iptables => { + iptables: { '0' => 'echo-reply', '3' => 'destination-unreachable', '4' => 'source-quench', @@ -310,9 +309,9 @@ describe firewall do '13' => 'timestamp-request', '14' => 'timestamp-reply', '17' => 'address-mask-request', - '18' => 'address-mask-reply' + '18' => 'address-mask-reply', }, - :ip6tables => { + ip6tables: { '1' => 'destination-unreachable', '2' => 'too-big', '3' => 'time-exceeded', @@ -321,199 +320,198 @@ describe firewall do '129' => 'echo-reply', '133' => 'router-solicitation', '134' => 'router-advertisement', - '137' => 'redirect' - } + '137' => 'redirect', + }, } icmp_codes.each do |provider, values| describe provider do - values.each do |k,v| - it 'should convert icmp string to number' do - @resource[:provider] = provider - expect(@resource[:provider]).to eql provider - @resource[:icmp] = v - expect(@resource[:icmp]).to eql k + values.each do |k, v| + resource_type = [:provider, :icmp] + resource_value = [provider, v] + resource_expected = [provider, k] + it 'converts icmp string to number' do + resource_type.each_with_index do |type, index| + resource[type] = resource_value[index] + expect(resource[type]).to eql resource_expected[index] + end end end end end - it 'should accept values as integers' do - @resource[:icmp] = 9 - expect(@resource[:icmp]).to eql 9 + it 'accepts values as integers' do + resource[:icmp] = 9 + expect(resource[:icmp]).to be 9 end - it 'should fail if icmp type is "any"' do - expect(lambda { @resource[:icmp] = 'any' }).to raise_error(Puppet::Error) + it 'fails if icmp type is "any"' do + expect(-> { resource[:icmp] = 'any' }).to raise_error(Puppet::Error) end - it 'should fail if icmp type is an array' do - expect(lambda { @resource[:icmp] = "['0', '8']" }).to raise_error(Puppet::Error) + it 'fails if icmp type is an array' do + expect(-> { resource[:icmp] = "['0', '8']" }).to raise_error(Puppet::Error) end - it 'should fail if icmp type cannot be mapped to a numeric' do - expect(lambda { @resource[:icmp] = 'foo' }).to raise_error(Puppet::Error) + it 'fails if icmp type cannot be mapped to a numeric' do + expect(-> { resource[:icmp] = 'foo' }).to raise_error(Puppet::Error) end end describe ':state' do - it 'should accept value as a string' do - @resource[:state] = :INVALID - expect(@resource[:state]).to eql [:INVALID] + it 'accepts value as a string - INVALID' do + resource[:state] = :INVALID + expect(resource[:state]).to eql [:INVALID] end - it 'should accept value as a string' do - @resource[:state] = :UNTRACKED - expect(@resource[:state]).to eql [:UNTRACKED] + it 'accepts value as a string - UNTRACKED' do + resource[:state] = :UNTRACKED + expect(resource[:state]).to eql [:UNTRACKED] end - it 'should accept value as an array' do - @resource[:state] = [:INVALID, :NEW] - expect(@resource[:state]).to eql [:INVALID, :NEW] + it 'accepts value as an array - INVALID, NEW' do + resource[:state] = [:INVALID, :NEW] + expect(resource[:state]).to eql [:INVALID, :NEW] end - it 'should sort values alphabetically' do - @resource[:state] = [:NEW, :UNTRACKED, :ESTABLISHED] - expect(@resource[:state]).to eql [:ESTABLISHED, :NEW, :UNTRACKED] + it 'sorts values alphabetically - NEW, UNTRACKED, ESTABLISHED' do + resource[:state] = [:NEW, :UNTRACKED, :ESTABLISHED] + expect(resource[:state]).to eql [:ESTABLISHED, :NEW, :UNTRACKED] end end describe ':ctstate' do - it 'should accept value as a string' do - @resource[:ctstate] = :INVALID - expect(@resource[:ctstate]).to eql [:INVALID] + it 'accepts value as a string - INVALID' do + resource[:ctstate] = :INVALID + expect(resource[:ctstate]).to eql [:INVALID] end - it 'should accept value as a string' do - @resource[:state] = :UNTRACKED - expect(@resource[:state]).to eql [:UNTRACKED] + it 'accepts value as a string - UNTRACKED' do + resource[:state] = :UNTRACKED + expect(resource[:state]).to eql [:UNTRACKED] end - it 'should accept value as an array' do - @resource[:ctstate] = [:INVALID, :NEW] - expect(@resource[:ctstate]).to eql [:INVALID, :NEW] + it 'accepts value as an array - INVALID, NEW' do + resource[:ctstate] = [:INVALID, :NEW] + expect(resource[:ctstate]).to eql [:INVALID, :NEW] end - it 'should sort values alphabetically' do - @resource[:ctstate] = [:NEW, :ESTABLISHED] - expect(@resource[:ctstate]).to eql [:ESTABLISHED, :NEW] + it 'sorts values alphabetically - NEW, ESTABLISHED' do + resource[:ctstate] = [:NEW, :ESTABLISHED] + expect(resource[:ctstate]).to eql [:ESTABLISHED, :NEW] end end describe ':burst' do - it 'should accept numeric values' do - @resource[:burst] = 12 - expect(@resource[:burst]).to eql 12 + it 'accepts numeric values' do + resource[:burst] = 12 + expect(resource[:burst]).to be 12 end - it 'should fail if value is not numeric' do - expect(lambda { @resource[:burst] = 'foo' }).to raise_error(Puppet::Error) + it 'fails if value is not numeric' do + expect(-> { resource[:burst] = 'foo' }).to raise_error(Puppet::Error) end end describe ':recent' do - ['set', 'update', 'rcheck', 'remove'].each do |recent| + %w[set update rcheck remove].each do |recent| it "should accept recent value #{recent}" do - @resource[:recent] = recent - expect(@resource[:recent]).to eql "--#{recent}" + resource[:recent] = recent + expect(resource[:recent]).to eql "--#{recent}" end end end describe ':action and :jump' do - it 'should allow only 1 to be set at a time' do + it 'allows only 1 to be set at a time' do expect { - @class.new( - :name => "001-test", - :action => "accept", - :jump => "custom_chain" - ) - }.to raise_error(Puppet::Error, /Only one of the parameters 'action' and 'jump' can be set$/) + firewall_class.new(name: '001-test', action: 'accept', jump: 'custom_chain') + }.to raise_error(RuntimeError, %r{Only one of the parameters 'action' and 'jump' can be set$}) end end describe ':gid and :uid' do - it 'should allow me to set uid' do - @resource[:uid] = 'root' - expect(@resource[:uid]).to eql 'root' + it 'allows me to set uid' do + resource[:uid] = 'root' + expect(resource[:uid]).to eql 'root' end - it 'should allow me to set uid as an array, and silently hide my error' do - @resource[:uid] = ['root', 'bobby'] - expect(@resource[:uid]).to eql 'root' + it 'allows me to set uid as an array, and silently hide my error' do + resource[:uid] = %w[root bobby] + expect(resource[:uid]).to eql 'root' end - it 'should allow me to set gid' do - @resource[:gid] = 'root' - expect(@resource[:gid]).to eql 'root' + it 'allows me to set gid' do + resource[:gid] = 'root' + expect(resource[:gid]).to eql 'root' end - it 'should allow me to set gid as an array, and silently hide my error' do - @resource[:gid] = ['root', 'bobby'] - expect(@resource[:gid]).to eql 'root' + it 'allows me to set gid as an array, and silently hide my error' do + resource[:gid] = %w[root bobby] + expect(resource[:gid]).to eql 'root' end end describe ':set_mark' do ['1.3.2', '1.4.2'].each do |iptables_version| describe "with iptables #{iptables_version}" do - before { + before(:each) do Facter.clear allow(Facter.fact(:iptables_version)).to receive(:value).and_return iptables_version allow(Facter.fact(:ip6tables_version)).to receive(:value).and_return iptables_version - } + end if iptables_version == '1.3.2' - it 'should allow me to set set-mark without mask' do - @resource[:set_mark] = '0x3e8' - expect(@resource[:set_mark]).to eql '0x3e8' + it 'allows me to set set-mark without mask' do + resource[:set_mark] = '0x3e8' + expect(resource[:set_mark]).to eql '0x3e8' end - it 'should convert int to hex without mask' do - @resource[:set_mark] = '1000' - expect(@resource[:set_mark]).to eql '0x3e8' + it 'converts int to hex without mask' do + resource[:set_mark] = '1000' + expect(resource[:set_mark]).to eql '0x3e8' end - it 'should fail if mask is present' do - expect(lambda { @resource[:set_mark] = '0x3e8/0xffffffff'}).to raise_error( - Puppet::Error, /iptables version #{iptables_version} does not support masks on MARK rules$/ + it 'fails if mask is present' do + expect(-> { resource[:set_mark] = '0x3e8/0xffffffff' }).to raise_error( + Puppet::Error, %r{iptables version #{iptables_version} does not support masks on MARK rules$} ) end end if iptables_version == '1.4.2' - it 'should allow me to set set-mark with mask' do - @resource[:set_mark] = '0x3e8/0xffffffff' - expect(@resource[:set_mark]).to eql '0x3e8/0xffffffff' + it 'allows me to set set-mark with mask' do + resource[:set_mark] = '0x3e8/0xffffffff' + expect(resource[:set_mark]).to eql '0x3e8/0xffffffff' end - it 'should convert int to hex and add a 32 bit mask' do - @resource[:set_mark] = '1000' - expect(@resource[:set_mark]).to eql '0x3e8/0xffffffff' + it 'converts int to hex and add a 32 bit mask' do + resource[:set_mark] = '1000' + expect(resource[:set_mark]).to eql '0x3e8/0xffffffff' end - it 'should add a 32 bit mask' do - @resource[:set_mark] = '0x32' - expect(@resource[:set_mark]).to eql '0x32/0xffffffff' + it 'adds a 32 bit mask' do + resource[:set_mark] = '0x32' + expect(resource[:set_mark]).to eql '0x32/0xffffffff' end - it 'should use the mask provided' do - @resource[:set_mark] = '0x32/0x4' - expect(@resource[:set_mark]).to eql '0x32/0x4' + it 'uses the mask provided' do + resource[:set_mark] = '0x32/0x4' + expect(resource[:set_mark]).to eql '0x32/0x4' end - it 'should use the mask provided and convert int to hex' do - @resource[:set_mark] = '1000/0x4' - expect(@resource[:set_mark]).to eql '0x3e8/0x4' + it 'uses the mask provided and convert int to hex' do + resource[:set_mark] = '1000/0x4' + expect(resource[:set_mark]).to eql '0x3e8/0x4' end - it 'should fail if mask value is more than 32 bits' do - expect(lambda { @resource[:set_mark] = '1/4294967296'}).to raise_error( - Puppet::Error, /MARK mask must be integer or hex between 0 and 0xffffffff$/ + it 'fails if mask value is more than 32 bits' do + expect(-> { resource[:set_mark] = '1/4294967296' }).to raise_error( + Puppet::Error, %r{MARK mask must be integer or hex between 0 and 0xffffffff$} ) end - it 'should fail if mask is malformed' do - expect(lambda { @resource[:set_mark] = '1000/0xq4'}).to raise_error( - Puppet::Error, /MARK mask must be integer or hex between 0 and 0xffffffff$/ + it 'fails if mask is malformed' do + expect(-> { resource[:set_mark] = '1000/0xq4' }).to raise_error( + Puppet::Error, %r{MARK mask must be integer or hex between 0 and 0xffffffff$} ) end end ['/', '1000/', 'pwnie'].each do |bad_mark| it "should fail with malformed mark '#{bad_mark}'" do - expect(lambda { @resource[:set_mark] = bad_mark}).to raise_error(Puppet::Error) + expect(-> { resource[:set_mark] = bad_mark }).to raise_error(Puppet::Error) end end - it 'should fail if mark value is more than 32 bits' do - expect(lambda { @resource[:set_mark] = '4294967296'}).to raise_error( - Puppet::Error, /MARK value must be integer or hex between 0 and 0xffffffff$/ + it 'fails if mark value is more than 32 bits' do + expect(-> { resource[:set_mark] = '4294967296' }).to raise_error( + Puppet::Error, %r{MARK value must be integer or hex between 0 and 0xffffffff$} ) end end @@ -522,200 +520,207 @@ describe firewall do [:chain, :jump].each do |param| describe param do - it 'should autorequire fwchain when table and provider are undefined' do - @resource[param] = 'FOO' - expect(@resource[:table]).to eql :filter - expect(@resource[:provider]).to eql :iptables - - chain = Puppet::Type.type(:firewallchain).new(:name => 'FOO:filter:IPv4') + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations + it 'autorequires fwchain when table and provider are undefined' do + resource[param] = 'FOO' + expect(resource[:table]).to be :filter + expect(resource[:provider]).to be :iptables + + chain = Puppet::Type.type(:firewallchain).new(name: 'FOO:filter:IPv4') catalog = Puppet::Resource::Catalog.new - catalog.add_resource @resource + catalog.add_resource resource catalog.add_resource chain - rel = @resource.autorequire[0] + rel = resource.autorequire[0] expect(rel.source.ref).to eql chain.ref - expect(rel.target.ref).to eql @resource.ref + expect(rel.target.ref).to eql resource.ref end - it 'should autorequire fwchain when table is undefined and provider is ip6tables' do - @resource[param] = 'FOO' - expect(@resource[:table]).to eql :filter - @resource[:provider] = :ip6tables + it 'autorequires fwchain when table is undefined and provider is ip6tables' do + resource[param] = 'FOO' + expect(resource[:table]).to be :filter + resource[:provider] = :ip6tables - chain = Puppet::Type.type(:firewallchain).new(:name => 'FOO:filter:IPv6') + chain = Puppet::Type.type(:firewallchain).new(name: 'FOO:filter:IPv6') catalog = Puppet::Resource::Catalog.new - catalog.add_resource @resource + catalog.add_resource resource catalog.add_resource chain - rel = @resource.autorequire[0] + rel = resource.autorequire[0] expect(rel.source.ref).to eql chain.ref - expect(rel.target.ref).to eql @resource.ref + expect(rel.target.ref).to eql resource.ref end - it 'should autorequire fwchain when table is raw and provider is undefined' do - @resource[param] = 'FOO' - @resource[:table] = :raw - expect(@resource[:provider]).to eql :iptables + it 'autorequires fwchain when table is raw and provider is undefined' do + resource[param] = 'FOO' + resource[:table] = :raw + expect(resource[:provider]).to be :iptables - chain = Puppet::Type.type(:firewallchain).new(:name => 'FOO:raw:IPv4') + chain = Puppet::Type.type(:firewallchain).new(name: 'FOO:raw:IPv4') catalog = Puppet::Resource::Catalog.new - catalog.add_resource @resource + catalog.add_resource resource catalog.add_resource chain - rel = @resource.autorequire[0] + rel = resource.autorequire[0] expect(rel.source.ref).to eql chain.ref - expect(rel.target.ref).to eql @resource.ref + expect(rel.target.ref).to eql resource.ref end - it 'should autorequire fwchain when table is raw and provider is ip6tables' do - @resource[param] = 'FOO' - @resource[:table] = :raw - @resource[:provider] = :ip6tables + it 'autorequires fwchain when table is raw and provider is ip6tables' do + resource[param] = 'FOO' + resource[:table] = :raw + resource[:provider] = :ip6tables - chain = Puppet::Type.type(:firewallchain).new(:name => 'FOO:raw:IPv6') + chain = Puppet::Type.type(:firewallchain).new(name: 'FOO:raw:IPv6') catalog = Puppet::Resource::Catalog.new - catalog.add_resource @resource + catalog.add_resource resource catalog.add_resource chain - rel = @resource.autorequire[0] + rel = resource.autorequire[0] expect(rel.source.ref).to eql chain.ref - expect(rel.target.ref).to eql @resource.ref + expect(rel.target.ref).to eql resource.ref end # test where autorequire is still needed (table != filter) - ['INPUT', 'OUTPUT', 'FORWARD'].each do |test_chain| + %w[INPUT OUTPUT FORWARD].each do |test_chain| it "should autorequire fwchain #{test_chain} when table is mangle and provider is undefined" do - @resource[param] = test_chain - @resource[:table] = :mangle - expect(@resource[:provider]).to eql :iptables + resource[param] = test_chain + resource[:table] = :mangle + expect(resource[:provider]).to be :iptables - chain = Puppet::Type.type(:firewallchain).new(:name => "#{test_chain}:mangle:IPv4") + chain = Puppet::Type.type(:firewallchain).new(name: "#{test_chain}:mangle:IPv4") catalog = Puppet::Resource::Catalog.new - catalog.add_resource @resource + catalog.add_resource resource catalog.add_resource chain - rel = @resource.autorequire[0] + rel = resource.autorequire[0] expect(rel.source.ref).to eql chain.ref - expect(rel.target.ref).to eql @resource.ref + expect(rel.target.ref).to eql resource.ref end it "should autorequire fwchain #{test_chain} when table is mangle and provider is ip6tables" do - @resource[param] = test_chain - @resource[:table] = :mangle - @resource[:provider] = :ip6tables + resource[param] = test_chain + resource[:table] = :mangle + resource[:provider] = :ip6tables - chain = Puppet::Type.type(:firewallchain).new(:name => "#{test_chain}:mangle:IPv6") + chain = Puppet::Type.type(:firewallchain).new(name: "#{test_chain}:mangle:IPv6") catalog = Puppet::Resource::Catalog.new - catalog.add_resource @resource + catalog.add_resource resource catalog.add_resource chain - rel = @resource.autorequire[0] + rel = resource.autorequire[0] expect(rel.source.ref).to eql chain.ref - expect(rel.target.ref).to eql @resource.ref + expect(rel.target.ref).to eql resource.ref end end # test of case where autorequire should not happen - ['INPUT', 'OUTPUT', 'FORWARD'].each do |test_chain| - + %w[INPUT OUTPUT FORWARD].each do |test_chain| it "should not autorequire fwchain #{test_chain} when table and provider are undefined" do - @resource[param] = test_chain - expect(@resource[:table]).to eql :filter - expect(@resource[:provider]).to eql :iptables + resource[param] = test_chain + expect(resource[:table]).to be :filter + expect(resource[:provider]).to be :iptables - chain = Puppet::Type.type(:firewallchain).new(:name => "#{test_chain}:filter:IPv4") + chain = Puppet::Type.type(:firewallchain).new(name: "#{test_chain}:filter:IPv4") catalog = Puppet::Resource::Catalog.new - catalog.add_resource @resource + catalog.add_resource resource catalog.add_resource chain - rel = @resource.autorequire[0] - expect(rel).to eql nil + rel = resource.autorequire[0] + expect(rel).to be nil end it "should not autorequire fwchain #{test_chain} when table is undefined and provider is ip6tables" do - @resource[param] = test_chain - expect(@resource[:table]).to eql :filter - @resource[:provider] = :ip6tables + resource[param] = test_chain + expect(resource[:table]).to be :filter + resource[:provider] = :ip6tables - chain = Puppet::Type.type(:firewallchain).new(:name => "#{test_chain}:filter:IPv6") + chain = Puppet::Type.type(:firewallchain).new(name: "#{test_chain}:filter:IPv6") catalog = Puppet::Resource::Catalog.new - catalog.add_resource @resource + catalog.add_resource resource catalog.add_resource chain - rel = @resource.autorequire[0] - expect(rel).to eql nil + rel = resource.autorequire[0] + expect(rel).to be nil end end end end - describe ":chain and :jump" do - it 'should autorequire independent fwchains' do - @resource[:chain] = 'FOO' - @resource[:jump] = 'BAR' - expect(@resource[:table]).to eql :filter - expect(@resource[:provider]).to eql :iptables + describe ':chain and :jump' do + it 'autorequires independent fwchains' do + resource[:chain] = 'FOO' + resource[:jump] = 'BAR' + expect(resource[:table]).to be :filter + expect(resource[:provider]).to be :iptables - chain_foo = Puppet::Type.type(:firewallchain).new(:name => 'FOO:filter:IPv4') - chain_bar = Puppet::Type.type(:firewallchain).new(:name => 'BAR:filter:IPv4') + chain_foo = Puppet::Type.type(:firewallchain).new(name: 'FOO:filter:IPv4') + chain_bar = Puppet::Type.type(:firewallchain).new(name: 'BAR:filter:IPv4') catalog = Puppet::Resource::Catalog.new - catalog.add_resource @resource + catalog.add_resource resource catalog.add_resource chain_foo catalog.add_resource chain_bar - rel = @resource.autorequire + rel = resource.autorequire expect(rel[0].source.ref).to eql chain_foo.ref - expect(rel[0].target.ref).to eql @resource.ref + expect(rel[0].target.ref).to eql resource.ref expect(rel[1].source.ref).to eql chain_bar.ref - expect(rel[1].target.ref).to eql @resource.ref + expect(rel[1].target.ref).to eql resource.ref end end + # rubocop:enable RSpec/ExampleLength + # rubocop:enable RSpec/MultipleExpectations describe ':pkttype' do [:multicast, :broadcast, :unicast].each do |pkttype| it "should accept pkttype value #{pkttype}" do - @resource[:pkttype] = pkttype - expect(@resource[:pkttype]).to eql pkttype + resource[:pkttype] = pkttype + expect(resource[:pkttype]).to eql pkttype end end - it 'should fail when the pkttype value is not recognized' do - expect(lambda { @resource[:pkttype] = 'not valid' }).to raise_error(Puppet::Error) + it 'fails when the pkttype value is not recognized' do + expect(-> { resource[:pkttype] = 'not valid' }).to raise_error(Puppet::Error) end end describe 'autorequire packages' do + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations [:iptables, :ip6tables].each do |provider| it "provider #{provider} should autorequire package iptables" do - @resource[:provider] = provider - expect(@resource[:provider]).to eql provider - package = Puppet::Type.type(:package).new(:name => 'iptables') + resource[:provider] = provider + expect(resource[:provider]).to eql provider + package = Puppet::Type.type(:package).new(name: 'iptables') catalog = Puppet::Resource::Catalog.new - catalog.add_resource @resource + catalog.add_resource resource catalog.add_resource package - rel = @resource.autorequire[0] + rel = resource.autorequire[0] expect(rel.source.ref).to eql package.ref - expect(rel.target.ref).to eql @resource.ref + expect(rel.target.ref).to eql resource.ref end it "provider #{provider} should autorequire packages iptables, iptables-persistent, and iptables-services" do - @resource[:provider] = provider - expect(@resource[:provider]).to eql provider + resource[:provider] = provider + expect(resource[:provider]).to eql provider packages = [ - Puppet::Type.type(:package).new(:name => 'iptables'), - Puppet::Type.type(:package).new(:name => 'iptables-persistent'), - Puppet::Type.type(:package).new(:name => 'iptables-services') + Puppet::Type.type(:package).new(name: 'iptables'), + Puppet::Type.type(:package).new(name: 'iptables-persistent'), + Puppet::Type.type(:package).new(name: 'iptables-services'), ] catalog = Puppet::Resource::Catalog.new - catalog.add_resource @resource + catalog.add_resource resource packages.each do |package| catalog.add_resource package end - packages.zip(@resource.autorequire) do |package, rel| + packages.zip(resource.autorequire) do |package, rel| expect(rel.source.ref).to eql package.ref - expect(rel.target.ref).to eql @resource.ref + expect(rel.target.ref).to eql resource.ref end end end + # rubocop:enable RSpec/ExampleLength + # rubocop:enable RSpec/MultipleExpectations end it 'is suitable' do - expect(@resource.suitable?).to be_truthy + expect(resource).to be_suitable end end describe 'firewall on unsupported platforms' do - it 'is not suitable' do + it 'is not suitable' do # rubocop:disable RSpec/ExampleLength # Stub iptables version allow(Facter.fact(:iptables_version)).to receive(:value).and_return(nil) allow(Facter.fact(:ip6tables_version)).to receive(:value).and_return(nil) @@ -723,11 +728,11 @@ describe 'firewall on unsupported platforms' do # Stub confine facts allow(Facter.fact(:kernel)).to receive(:value).and_return('Darwin') allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Darwin') - resource = firewall.new(:name => "000 test foo", :ensure => :present) + resource = firewall.new(name: '000 test foo', ensure: :present) # If our provider list is nil, then the Puppet::Transaction#evaluate will # say 'Error: Could not find a suitable provider for firewall' but there # isn't a unit testable way to get this. - expect(resource.suitable?).to be_falsey + expect(resource).not_to be_suitable end end diff --git a/spec/unit/puppet/type/firewallchain_spec.rb b/spec/unit/puppet/type/firewallchain_spec.rb index 440534e..ae71adf 100755 --- a/spec/unit/puppet/type/firewallchain_spec.rb +++ b/spec/unit/puppet/type/firewallchain_spec.rb @@ -4,37 +4,36 @@ require 'spec_helper' firewallchain = Puppet::Type.type(:firewallchain) -describe firewallchain do +describe firewallchain do # rubocop:disable RSpec/MultipleDescribes before(:each) do # Stub confine facts allow(Facter.fact(:kernel)).to receive(:value).and_return('Linux') allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Debian') end let(:klass) { firewallchain } - let(:provider) { - prov = double 'provider' + let(:provider) do + prov = instance_double('provider') allow(prov).to receive(:name).and_return(:iptables_chain) prov - } - let(:resource) { + end + let(:resource) do allow(Puppet::Type::Firewallchain).to receive(:defaultprovider).and_return provider - klass.new({:name => 'INPUT:filter:IPv4', :policy => :accept }) - } + klass.new(name: 'INPUT:filter:IPv4', policy: :accept) + end - it 'should have :name be its namevar' do + it 'has :name be its namevar' do expect(klass.key_attributes).to eql [:name] end describe ':name' do - {'nat' => ['PREROUTING', 'POSTROUTING', 'INPUT', 'OUTPUT'], - 'mangle' => [ 'PREROUTING', 'POSTROUTING', 'INPUT', 'FORWARD', 'OUTPUT' ], - 'filter' => ['INPUT','OUTPUT','FORWARD'], - 'raw' => [ 'PREROUTING', 'OUTPUT'], - 'broute' => ['BROUTING'], - 'security' => ['INPUT','OUTPUT','FORWARD'] - }.each_pair do |table, allowedinternalchains| - ['IPv4', 'IPv6', 'ethernet'].each do |protocol| - [ 'test', '$5()*&%\'"^$09):' ].each do |chainname| + { 'nat' => %w[PREROUTING POSTROUTING INPUT OUTPUT], + 'mangle' => %w[PREROUTING POSTROUTING INPUT FORWARD OUTPUT], + 'filter' => %w[INPUT OUTPUT FORWARD], + 'raw' => %w[PREROUTING OUTPUT], + 'broute' => ['BROUTING'], + 'security' => %w[INPUT OUTPUT FORWARD] }.each_pair do |table, allowedinternalchains| + %w[IPv4 IPv6 ethernet].each do |protocol| + ['test', '$5()*&%\'"^$09):'].each do |chainname| name = "#{chainname}:#{table}:#{protocol}" if table == 'nat' && protocol == 'IPv6' it "should accept #{name} for Linux 3.7+" do @@ -47,11 +46,11 @@ describe firewallchain do expect { resource[:name] = name }.to raise_error(Puppet::Error) end elsif protocol != 'ethernet' && table == 'broute' - it "should fail #{name}" do + it "should fail #{name}" do # rubocop:disable RSpec/RepeatedExample expect { resource[:name] = name }.to raise_error(Puppet::Error) end else - it "should accept name #{name}" do + it "should accept name #{name}" do # rubocop:disable RSpec/RepeatedExample resource[:name] = name expect(resource[:name]).to eql name end @@ -59,41 +58,38 @@ describe firewallchain do end # chainname end # protocol - [ 'PREROUTING', 'POSTROUTING', 'BROUTING', 'INPUT', 'FORWARD', 'OUTPUT' ].each do |internalchain| + %w[PREROUTING POSTROUTING BROUTING INPUT FORWARD OUTPUT].each do |internalchain| name = internalchain + ':' + table + ':' - if internalchain == 'BROUTING' - name += 'ethernet' - elsif table == 'nat' - name += 'IPv4' - else - name += 'IPv4' - end + name += if internalchain == 'BROUTING' + 'ethernet' + elsif table == 'nat' + 'IPv4' + else + 'IPv4' + end if allowedinternalchains.include? internalchain - it "should allow #{name}" do + it "should allow #{name}" do # rubocop:disable RSpec/RepeatedExample resource[:name] = name expect(resource[:name]).to eql name end else - it "should fail #{name}" do + it "should fail #{name}" do # rubocop:disable RSpec/RepeatedExample expect { resource[:name] = name }.to raise_error(Puppet::Error) end end end # internalchain - end # table, allowedinternalchainnames - it 'should fail with invalid table names' do + it 'fails with invalid table names' do expect { resource[:name] = 'wrongtablename:test:IPv4' }.to raise_error(Puppet::Error) end - it 'should fail with invalid protocols names' do + it 'fails with invalid protocols names' do expect { resource[:name] = 'test:filter:IPv5' }.to raise_error(Puppet::Error) end - end describe ':policy' do - [:accept, :drop, :queue, :return].each do |policy| it "should accept policy #{policy}" do resource[:policy] = policy @@ -101,25 +97,26 @@ describe firewallchain do end end - it 'should fail when value is not recognized' do + it 'fails when value is not recognized' do expect { resource[:policy] = 'not valid' }.to raise_error(Puppet::Error) end [:accept, :drop, :queue, :return].each do |policy| it "non-inbuilt chains should not accept policy #{policy}" do - expect { klass.new({:name => 'testchain:filter:IPv4', :policy => policy }) }.to raise_error(Puppet::Error) + expect { klass.new(name: 'testchain:filter:IPv4', policy: policy) }.to raise_error(RuntimeError) end it "non-inbuilt chains can accept policies on protocol = ethernet (policy #{policy})" do - klass.new({:name => 'testchain:filter:ethernet', :policy => policy }) + klass.new(name: 'testchain:filter:ethernet', policy: policy) end end - end describe 'autorequire packages' do - it "provider iptables_chain should autorequire package iptables" do - expect(resource[:provider]).to eql :iptables_chain - package = Puppet::Type.type(:package).new(:name => 'iptables') + # rubocop:disable RSpec/ExampleLength + # rubocop:disable RSpec/MultipleExpectations + it 'provider iptables_chain should autorequire package iptables' do + expect(resource[:provider]).to be :iptables_chain + package = Puppet::Type.type(:package).new(name: 'iptables') catalog = Puppet::Resource::Catalog.new catalog.add_resource resource catalog.add_resource package @@ -128,12 +125,12 @@ describe firewallchain do expect(rel.target.ref).to eql resource.ref end - it "provider iptables_chain should autorequire packages iptables, iptables-persistent, and iptables-services" do - expect(resource[:provider]).to eql :iptables_chain + it 'provider iptables_chain should autorequire packages iptables, iptables-persistent, and iptables-services' do + expect(resource[:provider]).to be :iptables_chain packages = [ - Puppet::Type.type(:package).new(:name => 'iptables'), - Puppet::Type.type(:package).new(:name => 'iptables-persistent'), - Puppet::Type.type(:package).new(:name => 'iptables-services') + Puppet::Type.type(:package).new(name: 'iptables'), + Puppet::Type.type(:package).new(name: 'iptables-persistent'), + Puppet::Type.type(:package).new(name: 'iptables-services'), ] catalog = Puppet::Resource::Catalog.new catalog.add_resource resource @@ -145,9 +142,12 @@ describe firewallchain do expect(rel.target.ref).to eql resource.ref end end + # rubocop:enable RSpec/ExampleLength + # rubocop:enable RSpec/MultipleExpectations end describe 'purge iptables rules' do + # rubocop:disable Layout/IndentHeredoc before(:each) do stub_return = < 'INPUT:filter:IPv4', :purge => true) + it 'generates iptables resources' do + allow(Facter.fact(:ip6tables_version)).to receive(:value).and_return('1.4.21') + resource = Puppet::Type::Firewallchain.new(name: 'INPUT:filter:IPv4', purge: true) expect(resource.generate.size).to eq(3) end - it 'should not generate ignored iptables rules' do - allow(Facter.fact(:ip6tables_version)).to receive(:value).and_return("1.4.21") - resource = Puppet::Type::Firewallchain.new(:name => 'INPUT:filter:IPv4', :purge => true, :ignore => ['-j fail2ban-ssh']) + it 'does not generate ignored iptables rules' do + allow(Facter.fact(:ip6tables_version)).to receive(:value).and_return('1.4.21') + resource = Puppet::Type::Firewallchain.new(name: 'INPUT:filter:IPv4', purge: true, ignore: ['-j fail2ban-ssh']) expect(resource.generate.size).to eq(2) end - it 'should not generate iptables resources when not enabled' do - resource = Puppet::Type::Firewallchain.new(:name => 'INPUT:filter:IPv4') + it 'does not generate iptables resources when not enabled' do + resource = Puppet::Type::Firewallchain.new(name: 'INPUT:filter:IPv4') expect(resource.generate.size).to eq(0) end end it 'is suitable' do - expect(resource.suitable?).to be_truthy + expect(resource).to be_suitable end end describe 'firewall on unsupported platforms' do - it 'is not suitable' do + it 'is not suitable' do # rubocop:disable RSpec/ExampleLength # Stub iptables version allow(Facter.fact(:iptables_version)).to receive(:value).and_return(nil) allow(Facter.fact(:ip6tables_version)).to receive(:value).and_return(nil) @@ -207,11 +208,11 @@ describe 'firewall on unsupported platforms' do # Stub confine facts allow(Facter.fact(:kernel)).to receive(:value).and_return('Darwin') allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Darwin') - resource = firewallchain.new(:name => "INPUT:filter:IPv4", :ensure => :present) + resource = firewallchain.new(name: 'INPUT:filter:IPv4', ensure: :present) # If our provider list is nil, then the Puppet::Transaction#evaluate will # say 'Error: Could not find a suitable provider for firewall' but there # isn't a unit testable way to get this. - expect(resource.suitable?).to be_falsey + expect(resource).not_to be_suitable end end diff --git a/spec/unit/puppet/util/firewall_spec.rb b/spec/unit/puppet/util/firewall_spec.rb index 0addb67..8a45f45 100644 --- a/spec/unit/puppet/util/firewall_spec.rb +++ b/spec/unit/puppet/util/firewall_spec.rb @@ -1,20 +1,21 @@ require 'spec_helper' describe 'Puppet::Util::Firewall' do - let(:resource) { + let(:resource) do type = Puppet::Type.type(:firewall) - provider = double 'provider' + provider = instance_double('provider') allow(provider).to receive(:name).and_return(:iptables) allow(Puppet::Type::Firewall).to receive(:defaultprovider).and_return(provider) - type.new({:name => '000 test foo'}) - } + type.new(name: '000 test foo') + end before(:each) { resource } describe '#host_to_ip' do subject { resource } - it { - expect(Resolv).to receive(:each_address).at_least(:once).with('puppetlabs.com').and_yield('96.126.112.51').and_yield('2001:DB8:4650::13:8A') + + it { # rubocop:disable RSpec/MultipleExpectations + allow(Resolv).to receive(:each_address).at_least(:once).with('puppetlabs.com').and_yield('96.126.112.51').and_yield('2001:DB8:4650::13:8A') expect(subject.host_to_ip('puppetlabs.com', :IPv4)).to eql '96.126.112.51/32' expect(subject.host_to_ip('puppetlabs.com', :IPv6)).to eql '2001:db8:4650::13:8a/128' } @@ -22,14 +23,15 @@ describe 'Puppet::Util::Firewall' do it { expect(subject.host_to_ip('96.126.112.51/32')).to eql '96.126.112.51/32' } it { expect(subject.host_to_ip('2001:db8:85a3:0:0:8a2e:370:7334')).to eql '2001:db8:85a3::8a2e:370:7334/128' } it { expect(subject.host_to_ip('2001:db8:1234::/48')).to eql '2001:db8:1234::/48' } - it { expect(subject.host_to_ip('0.0.0.0/0')).to eql nil } - it { expect(subject.host_to_ip('::/0')).to eql nil } + it { expect(subject.host_to_ip('0.0.0.0/0')).to be nil } + it { expect(subject.host_to_ip('::/0')).to be nil } end describe '#host_to_mask' do subject { resource } - it { - expect(Resolv).to receive(:each_address).at_least(:once).with('puppetlabs.com').and_yield('96.126.112.51').and_yield('2001:DB8:4650::13:8A') + + it { # rubocop:disable RSpec/MultipleExpectations + allow(Resolv).to receive(:each_address).at_least(:once).with('puppetlabs.com').and_yield('96.126.112.51').and_yield('2001:DB8:4650::13:8A') expect(subject.host_to_mask('puppetlabs.com', :IPv4)).to eql '96.126.112.51/32' expect(subject.host_to_mask('!puppetlabs.com', :IPv4)).to eql '! 96.126.112.51/32' expect(subject.host_to_mask('puppetlabs.com', :IPv6)).to eql '2001:db8:4650::13:8a/128' @@ -43,20 +45,20 @@ describe 'Puppet::Util::Firewall' do it { expect(subject.host_to_mask('!2001:db8:85a3:0:0:8a2e:370:7334', :IPv6)).to eql '! 2001:db8:85a3::8a2e:370:7334/128' } it { expect(subject.host_to_mask('2001:db8:1234::/48', :IPv6)).to eql '2001:db8:1234::/48' } it { expect(subject.host_to_mask('! 2001:db8:1234::/48', :IPv6)).to eql '! 2001:db8:1234::/48' } - it { expect(subject.host_to_mask('0.0.0.0/0', :IPv4)).to eql nil } - it { expect(subject.host_to_mask('!0.0.0.0/0', :IPv4)).to eql nil } - it { expect(subject.host_to_mask('::/0', :IPv6)).to eql nil } - it { expect(subject.host_to_mask('! ::/0', :IPv6)).to eql nil } + it { expect(subject.host_to_mask('0.0.0.0/0', :IPv4)).to be nil } + it { expect(subject.host_to_mask('!0.0.0.0/0', :IPv4)).to be nil } + it { expect(subject.host_to_mask('::/0', :IPv6)).to be nil } + it { expect(subject.host_to_mask('! ::/0', :IPv6)).to be nil } end describe '#icmp_name_to_number' do describe 'proto unsupported' do subject { resource } - %w{inet5 inet8 foo}.each do |proto| + %w[inet5 inet8 foo].each do |proto| it "should reject invalid proto #{proto}" do - expect { subject.icmp_name_to_number('echo-reply', proto) }. - to raise_error(ArgumentError, "unsupported protocol family '#{proto}'") + expect { subject.icmp_name_to_number('echo-reply', proto) } + .to raise_error(ArgumentError, "unsupported protocol family '#{proto}'") end end end @@ -64,6 +66,7 @@ describe 'Puppet::Util::Firewall' do describe 'proto IPv4' do proto = 'inet' subject { resource } + it { expect(subject.icmp_name_to_number('echo-reply', proto)).to eql '0' } it { expect(subject.icmp_name_to_number('destination-unreachable', proto)).to eql '3' } it { expect(subject.icmp_name_to_number('source-quench', proto)).to eql '4' } @@ -82,6 +85,7 @@ describe 'Puppet::Util::Firewall' do describe 'proto IPv6' do proto = 'inet6' subject { resource } + it { expect(subject.icmp_name_to_number('destination-unreachable', proto)).to eql '1' } it { expect(subject.icmp_name_to_number('time-exceeded', proto)).to eql '3' } it { expect(subject.icmp_name_to_number('parameter-problem', proto)).to eql '4' } @@ -97,27 +101,30 @@ describe 'Puppet::Util::Firewall' do describe '#string_to_port' do subject { resource } - it { expect(subject.string_to_port('80','tcp')).to eql '80' } - it { expect(subject.string_to_port(80,'tcp')).to eql '80' } - it { expect(subject.string_to_port('http','tcp')).to eql '80' } - it { expect(subject.string_to_port('domain','udp')).to eql '53' } + + it { expect(subject.string_to_port('80', 'tcp')).to eql '80' } + it { expect(subject.string_to_port(80, 'tcp')).to eql '80' } + it { expect(subject.string_to_port('http', 'tcp')).to eql '80' } + it { expect(subject.string_to_port('domain', 'udp')).to eql '53' } end describe '#to_hex32' do subject { resource } + it { expect(subject.to_hex32('0')).to eql '0x0' } it { expect(subject.to_hex32('0x32')).to eql '0x32' } it { expect(subject.to_hex32('42')).to eql '0x2a' } it { expect(subject.to_hex32('4294967295')).to eql '0xffffffff' } - it { expect(subject.to_hex32('4294967296')).to eql nil } - it { expect(subject.to_hex32('-1')).to eql nil } - it { expect(subject.to_hex32('bananas')).to eql nil } + it { expect(subject.to_hex32('4294967296')).to be nil } + it { expect(subject.to_hex32('-1')).to be nil } + it { expect(subject.to_hex32('bananas')).to be nil } end describe '#persist_iptables' do - before { Facter.clear } + before(:each) { Facter.clear } subject { resource } + # rubocop:disable RSpec/SubjectStub describe 'when proto is IPv4' do let(:proto) { 'IPv4' } @@ -126,7 +133,7 @@ describe 'Puppet::Util::Firewall' do allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('RedHat') allow(Facter.fact(:operatingsystemrelease)).to receive(:value).and_return('6') - expect(subject).to receive(:execute).with(%w{/sbin/service iptables save}) + allow(subject).to receive(:execute).with(%w[/sbin/service iptables save]) subject.persist_iptables(proto) end @@ -135,7 +142,7 @@ describe 'Puppet::Util::Firewall' do allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('RedHat') allow(Facter.fact(:operatingsystemrelease)).to receive(:value).and_return('7') - expect(subject).to receive(:execute).with(%w{/usr/libexec/iptables/iptables.init save}) + allow(subject).to receive(:execute).with(%w[/usr/libexec/iptables/iptables.init save]) subject.persist_iptables(proto) end @@ -144,7 +151,7 @@ describe 'Puppet::Util::Firewall' do allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Fedora') allow(Facter.fact(:operatingsystemrelease)).to receive(:value).and_return('15') - expect(subject).to receive(:execute).with(%w{/usr/libexec/iptables/iptables.init save}) + allow(subject).to receive(:execute).with(%w[/usr/libexec/iptables/iptables.init save]) subject.persist_iptables(proto) end @@ -152,7 +159,7 @@ describe 'Puppet::Util::Firewall' do allow(Facter.fact(:osfamily)).to receive(:value).and_return(nil) allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('CentOS') allow(Facter.fact(:operatingsystemrelease)).to receive(:value).and_return('6.5') - expect(subject).to receive(:execute).with(%w{/sbin/service iptables save}) + allow(subject).to receive(:execute).with(%w[/sbin/service iptables save]) subject.persist_iptables(proto) end @@ -160,24 +167,24 @@ describe 'Puppet::Util::Firewall' do allow(Facter.fact(:osfamily)).to receive(:value).and_return(nil) allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('CentOS') allow(Facter.fact(:operatingsystemrelease)).to receive(:value).and_return('7.0.1406') - expect(subject).to receive(:execute).with(%w{/usr/libexec/iptables/iptables.init save}) + allow(subject).to receive(:execute).with(%w[/usr/libexec/iptables/iptables.init save]) subject.persist_iptables(proto) end it 'is expected to exec for Archlinux identified from osfamily' do allow(Facter.fact(:osfamily)).to receive(:value).and_return('Archlinux') - expect(subject).to receive(:execute).with(['/bin/sh', '-c', '/usr/sbin/iptables-save > /etc/iptables/iptables.rules']) + allow(subject).to receive(:execute).with(['/bin/sh', '-c', '/usr/sbin/iptables-save > /etc/iptables/iptables.rules']) subject.persist_iptables(proto) end - it 'is expected to raise a warning when exec fails' do + it 'is expected to raise a warning when exec fails' do # rubocop:disable RSpec/ExampleLength allow(Facter.fact(:osfamily)).to receive(:value).and_return('RedHat') allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('RedHat') allow(Facter.fact(:operatingsystemrelease)).to receive(:value).and_return('6') - expect(subject).to receive(:execute).with(%w{/sbin/service iptables save}). - and_raise(Puppet::ExecutionFailure, 'some error') - expect(subject).to receive(:warning).with('Unable to persist firewall rules: some error') + allow(subject).to receive(:execute).with(%w[/sbin/service iptables save]) + .and_raise(Puppet::ExecutionFailure, 'some error') + allow(subject).to receive(:warning).with('Unable to persist firewall rules: some error') subject.persist_iptables(proto) end end @@ -189,7 +196,7 @@ describe 'Puppet::Util::Firewall' do allow(Facter.fact(:osfamily)).to receive(:value).and_return(nil) allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Ubuntu') allow(Facter.fact(:iptables_persistent_version)).to receive(:value).and_return('0.5.3ubuntu2') - expect(subject).to receive(:execute).with(%w{/usr/sbin/service iptables-persistent save}) + allow(subject).to receive(:execute).with(%w[/usr/sbin/service iptables-persistent save]) subject.persist_iptables(proto) end @@ -197,15 +204,16 @@ describe 'Puppet::Util::Firewall' do allow(Facter.fact(:osfamily)).to receive(:value).and_return(nil) allow(Facter.fact(:operatingsystem)).to receive(:value).and_return('Ubuntu') allow(Facter.fact(:iptables_persistent_version)).to receive(:value).and_return('0.0.20090701') - expect(subject).to receive(:execute).never + allow(subject).to receive(:execute).never subject.persist_iptables(proto) end it 'is expected to not exec for Suse which is not supported' do allow(Facter.fact(:osfamily)).to receive(:value).and_return('Suse') - expect(subject).to receive(:execute).never + allow(subject).to receive(:execute).never subject.persist_iptables(proto) end end + # rubocop:enable RSpec/SubjectStub end end diff --git a/spec/unit/puppet/util/ipcidr_spec.rb b/spec/unit/puppet/util/ipcidr_spec.rb index 9e591be..5b72418 100644 --- a/spec/unit/puppet/util/ipcidr_spec.rb +++ b/spec/unit/puppet/util/ipcidr_spec.rb @@ -3,76 +3,94 @@ require 'puppet/util/ipcidr' describe 'Puppet::Util::IPCidr' do describe 'ipv4 address' do - before { @ipaddr = Puppet::Util::IPCidr.new('96.126.112.51') } - subject { @ipaddr } + subject { ipaddr } + + let(:ipaddr) { Puppet::Util::IPCidr.new('96.126.112.51') } + it { expect(subject.cidr).to eql '96.126.112.51/32' } - it { expect(subject.prefixlen).to eql 32 } + it { expect(subject.prefixlen).to be 32 } it { expect(subject.netmask).to eql '255.255.255.255' } end describe 'single ipv4 address with cidr' do - before { @ipcidr = Puppet::Util::IPCidr.new('96.126.112.51/32') } - subject { @ipcidr } + subject { ipcidr } + + let(:ipcidr) { Puppet::Util::IPCidr.new('96.126.112.51/32') } + it { expect(subject.cidr).to eql '96.126.112.51/32' } - it { expect(subject.prefixlen).to eql 32 } + it { expect(subject.prefixlen).to be 32 } it { expect(subject.netmask).to eql '255.255.255.255' } end describe 'ipv4 address range with cidr' do - before { @ipcidr = Puppet::Util::IPCidr.new('96.126.112.0/24') } - subject { @ipcidr } + subject { ipcidr } + + let(:ipcidr) { Puppet::Util::IPCidr.new('96.126.112.0/24') } + it { expect(subject.cidr).to eql '96.126.112.0/24' } - it { expect(subject.prefixlen).to eql 24 } + it { expect(subject.prefixlen).to be 24 } it { expect(subject.netmask).to eql '255.255.255.0' } end # https://tickets.puppetlabs.com/browse/MODULES-3215 describe 'ipv4 address range with invalid cidr' do - before { @ipcidr = Puppet::Util::IPCidr.new('96.126.112.20/24') } - subject { @ipcidr } - specify { subject.cidr.should == '96.126.112.0/24' } # .20 is expected to - # be silently dropped. + subject { ipcidr } + + let(:ipcidr) { Puppet::Util::IPCidr.new('96.126.112.20/24') } + + specify { subject.cidr.should == '96.126.112.0/24' } # .20 is expected to + # be silently dropped. specify { subject.prefixlen.should == 24 } specify { subject.netmask.should == '255.255.255.0' } end describe 'ipv4 open range with cidr' do - before { @ipcidr = Puppet::Util::IPCidr.new('0.0.0.0/0') } - subject { @ipcidr } + subject { ipcidr } + + let(:ipcidr) { Puppet::Util::IPCidr.new('0.0.0.0/0') } + it { expect(subject.cidr).to eql '0.0.0.0/0' } - it { expect(subject.prefixlen).to eql 0 } + it { expect(subject.prefixlen).to be 0 } it { expect(subject.netmask).to eql '0.0.0.0' } end describe 'ipv6 address' do - before { @ipaddr = Puppet::Util::IPCidr.new('2001:db8:85a3:0:0:8a2e:370:7334') } - subject { @ipaddr } + subject { ipaddr } + + let(:ipaddr) { Puppet::Util::IPCidr.new('2001:db8:85a3:0:0:8a2e:370:7334') } + it { expect(subject.cidr).to eql '2001:db8:85a3::8a2e:370:7334/128' } - it { expect(subject.prefixlen).to eql 128 } + it { expect(subject.prefixlen).to be 128 } it { expect(subject.netmask).to eql 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' } end describe 'single ipv6 addr with cidr' do - before { @ipaddr = Puppet::Util::IPCidr.new('2001:db8:85a3:0:0:8a2e:370:7334/128') } - subject { @ipaddr } + subject { ipaddr } + + let(:ipaddr) { Puppet::Util::IPCidr.new('2001:db8:85a3:0:0:8a2e:370:7334/128') } + it { expect(subject.cidr).to eql '2001:db8:85a3::8a2e:370:7334/128' } - it { expect(subject.prefixlen).to eql 128 } + it { expect(subject.prefixlen).to be 128 } it { expect(subject.netmask).to eql 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff' } end describe 'ipv6 addr range with cidr' do - before { @ipaddr = Puppet::Util::IPCidr.new('2001:db8:1234::/48') } - subject { @ipaddr } + subject { ipaddr } + + let(:ipaddr) { Puppet::Util::IPCidr.new('2001:db8:1234::/48') } + it { expect(subject.cidr).to eql '2001:db8:1234::/48' } - it { expect(subject.prefixlen).to eql 48 } + it { expect(subject.prefixlen).to be 48 } it { expect(subject.netmask).to eql 'ffff:ffff:ffff:0000:0000:0000:0000:0000' } end describe 'ipv6 open range with cidr' do - before { @ipaddr = Puppet::Util::IPCidr.new('::/0') } - subject { @ipaddr } + subject { ipaddr } + + let(:ipaddr) { Puppet::Util::IPCidr.new('::/0') } + it { expect(subject.cidr).to eql '::/0' } - it { expect(subject.prefixlen).to eql 0 } + it { expect(subject.prefixlen).to be 0 } it { expect(subject.netmask).to eql '0000:0000:0000:0000:0000:0000:0000:0000' } end end -- 2.45.2