From 16c9a1bfd23fa30e275e6e480970fa72f7d635c8 Mon Sep 17 00:00:00 2001 From: Steven Pritchard Date: Fri, 13 Dec 2024 20:57:05 -0600 Subject: [PATCH] Clean up for rubocop --- .github/workflows/pr_tests.yml | 11 +- .rubocop.yml | 699 ++++++++++++++++++ Gemfile | 11 +- lib/facter/apache_version.rb | 8 +- lib/puppet/functions/simp_apache/auth.rb | 45 +- lib/puppet/functions/simp_apache/limits.rb | 33 +- .../simp_apache/munge_httpd_networks.rb | 17 +- lib/puppet/provider/htaccess/htaccess.rb | 70 +- lib/puppet/type/htaccess.rb | 15 +- spec/acceptance/suites/default/class_spec.rb | 29 +- .../suites/htaccess/htaccess_spec.rb | 46 +- spec/classes/conf_spec.rb | 18 +- spec/classes/expected/httpd.conf_default_el9 | 332 +++++++++ spec/classes/init_spec.rb | 32 +- spec/classes/ssl_spec.rb | 24 +- spec/defines/site_spec.rb | 5 +- spec/functions/simp_apache/auth_spec.rb | 71 +- spec/functions/simp_apache/limits_spec.rb | 42 +- .../simp_apache/munge_httpd_networks_spec.rb | 11 +- spec/spec_helper.rb | 15 +- spec/spec_helper_acceptance.rb | 25 +- .../compliance_engine_enforce_spec.rb | 85 ++- .../puppet/provider/htaccess/htaccess_spec.rb | 54 +- spec/unit/puppet/type/htaccess_spec.rb | 29 +- 24 files changed, 1381 insertions(+), 346 deletions(-) create mode 100644 .rubocop.yml create mode 100644 spec/classes/expected/httpd.conf_default_el9 diff --git a/.github/workflows/pr_tests.yml b/.github/workflows/pr_tests.yml index 21ca28c..bcc5fb0 100644 --- a/.github/workflows/pr_tests.yml +++ b/.github/workflows/pr_tests.yml @@ -35,7 +35,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - name: "Install Ruby ${{matrix.puppet.ruby_version}}" + - name: "Install Ruby 2.7" uses: ruby/setup-ruby@v1 # ruby/setup-ruby@ec106b438a1ff6ff109590de34ddc62c540232e0 with: ruby-version: 2.7 @@ -47,7 +47,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - name: "Install Ruby ${{matrix.puppet.ruby_version}}" + - name: "Install Ruby 2.7" uses: ruby/setup-ruby@v1 with: ruby-version: 2.7 @@ -56,13 +56,12 @@ jobs: - run: "bundle exec rake metadata_lint" ruby-style: - if: false # TODO Modules will need: rubocop in Gemfile, .rubocop.yml - name: 'Ruby Style (experimental)' + name: 'Ruby Style' runs-on: ubuntu-latest continue-on-error: true steps: - uses: actions/checkout@v3 - - name: "Install Ruby ${{matrix.puppet.ruby_version}}" + - name: "Install Ruby 2.7" uses: ruby/setup-ruby@v1 with: ruby-version: 2.7 @@ -89,7 +88,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - - name: 'Install Ruby ${{matrix.puppet.ruby_version}}' + - name: 'Install Ruby 2.7' uses: ruby/setup-ruby@v1 with: ruby-version: 2.7 diff --git a/.rubocop.yml b/.rubocop.yml new file mode 100644 index 0000000..65c8c0a --- /dev/null +++ b/.rubocop.yml @@ -0,0 +1,699 @@ +--- +require: + - rubocop-performance + - rubocop-rake + - rubocop-rspec +AllCops: + NewCops: enable + DisplayCopNames: true + TargetRubyVersion: "2.7" + Include: + - "**/*.rb" + Exclude: + - bin/* + - ".vendor/**/*" + - pkg/**/* + - spec/fixtures/**/* + - vendor/**/* + - "**/Puppetfile" + - "**/Vagrantfile" + - "**/Guardfile" +Layout/LineLength: + 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 +RSpec/DescribeSymbol: + Exclude: + - spec/unit/facter/**/*.rb +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: + 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 +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/TrailingCommaInArrayLiteral: + 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 +RSpec/MessageSpies: + EnforcedStyle: receive +Style/Documentation: + Exclude: + - lib/puppet/parser/functions/**/* + - spec/**/* +Style/WordArray: + EnforcedStyle: brackets +Performance/AncestorsInclude: + Enabled: true +Performance/BigDecimalWithNumericArgument: + Enabled: true +Performance/BlockGivenWithExplicitBlock: + Enabled: true +Performance/CaseWhenSplat: + Enabled: true +Performance/ConstantRegexp: + Enabled: true +Performance/MethodObjectAsBlock: + Enabled: true +Performance/RedundantSortBlock: + Enabled: true +Performance/RedundantStringChars: + Enabled: true +Performance/ReverseFirst: + Enabled: true +Performance/SortReverse: + Enabled: true +Performance/Squeeze: + Enabled: true +Performance/StringInclude: + Enabled: true +Performance/Sum: + Enabled: true +Style/CollectionMethods: + Enabled: true +Style/MethodCalledOnDoEndBlock: + Enabled: true +Style/StringMethods: + Enabled: true +Bundler/GemFilename: + Enabled: false +Bundler/InsecureProtocolSource: + Enabled: false +Gemspec/DuplicatedAssignment: + Enabled: false +Gemspec/OrderedDependencies: + Enabled: false +Gemspec/RequiredRubyVersion: + Enabled: false +Gemspec/RubyVersionGlobalsUsage: + Enabled: false +Layout/ArgumentAlignment: + Enabled: false +Layout/BeginEndAlignment: + Enabled: false +Layout/ClosingHeredocIndentation: + Enabled: false +Layout/EmptyComment: + Enabled: false +Layout/EmptyLineAfterGuardClause: + Enabled: false +Layout/EmptyLinesAroundArguments: + Enabled: false +Layout/EmptyLinesAroundAttributeAccessor: + Enabled: false +Layout/EndOfLine: + Enabled: false +Layout/FirstArgumentIndentation: + Enabled: false +Layout/HashAlignment: + Enabled: false +Layout/HeredocIndentation: + Enabled: false +Layout/LeadingEmptyLines: + Enabled: false +Layout/SpaceAroundMethodCallOperator: + Enabled: false +Layout/SpaceInsideArrayLiteralBrackets: + Enabled: false +Layout/SpaceInsideReferenceBrackets: + Enabled: false +Lint/BigDecimalNew: + Enabled: false +Lint/BooleanSymbol: + Enabled: false +Lint/ConstantDefinitionInBlock: + Enabled: false +Lint/DeprecatedOpenSSLConstant: + Enabled: false +Lint/DisjunctiveAssignmentInConstructor: + Enabled: false +Lint/DuplicateElsifCondition: + Enabled: false +Lint/DuplicateRequire: + Enabled: false +Lint/DuplicateRescueException: + Enabled: false +Lint/EmptyConditionalBody: + Enabled: false +Lint/EmptyFile: + Enabled: false +Lint/ErbNewArguments: + Enabled: false +Lint/FloatComparison: + Enabled: false +Lint/HashCompareByIdentity: + Enabled: false +Lint/IdentityComparison: + Enabled: false +Lint/InterpolationCheck: + Enabled: false +Lint/MissingCopEnableDirective: + Enabled: false +Lint/MixedRegexpCaptureTypes: + Enabled: false +Lint/NestedPercentLiteral: + Enabled: false +Lint/NonDeterministicRequireOrder: + Enabled: false +Lint/OrderedMagicComments: + Enabled: false +Lint/OutOfRangeRegexpRef: + Enabled: false +Lint/RaiseException: + Enabled: false +Lint/RedundantCopEnableDirective: + Enabled: false +Lint/RedundantRequireStatement: + Enabled: false +Lint/RedundantSafeNavigation: + Enabled: false +Lint/RedundantWithIndex: + Enabled: false +Lint/RedundantWithObject: + Enabled: false +Lint/RegexpAsCondition: + Enabled: false +Lint/ReturnInVoidContext: + Enabled: false +Lint/SafeNavigationConsistency: + Enabled: false +Lint/SafeNavigationWithEmpty: + Enabled: false +Lint/SelfAssignment: + Enabled: false +Lint/SendWithMixinArgument: + Enabled: false +Lint/ShadowedArgument: + Enabled: false +Lint/StructNewOverride: + Enabled: false +Lint/ToJSON: + Enabled: false +Lint/TopLevelReturnWithArgument: + Enabled: false +Lint/TrailingCommaInAttributeDeclaration: + Enabled: false +Lint/UnreachableLoop: + Enabled: false +Lint/UriEscapeUnescape: + Enabled: false +Lint/UriRegexp: + Enabled: false +Lint/UselessMethodDefinition: + Enabled: false +Lint/UselessTimes: + Enabled: false +Metrics/AbcSize: + Enabled: false +Metrics/BlockLength: + Enabled: false +Metrics/BlockNesting: + 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 +Migration/DepartmentName: + Enabled: false +Naming/AccessorMethodName: + Enabled: false +Naming/BlockParameterName: + Enabled: false +Naming/HeredocDelimiterCase: + Enabled: false +Naming/HeredocDelimiterNaming: + Enabled: false +Naming/MemoizedInstanceVariableName: + Enabled: false +Naming/MethodParameterName: + Enabled: false +Naming/RescuedExceptionsVariableName: + Enabled: false +Naming/VariableNumber: + Enabled: false +Performance/BindCall: + Enabled: false +Performance/DeletePrefix: + Enabled: false +Performance/DeleteSuffix: + Enabled: false +Performance/InefficientHashSearch: + Enabled: false +Performance/UnfreezeString: + Enabled: false +Performance/UriDefaultParser: + Enabled: false +RSpec/Be: + Enabled: false +RSpec/Dialect: + Enabled: false +RSpec/ContainExactly: + Enabled: false +RSpec/ContextMethod: + Enabled: false +RSpec/ContextWording: + Enabled: false +RSpec/DescribeClass: + Enabled: false +RSpec/EmptyHook: + Enabled: false +RSpec/EmptyLineAfterExample: + Enabled: false +RSpec/EmptyLineAfterExampleGroup: + Enabled: false +RSpec/EmptyLineAfterHook: + Enabled: false +RSpec/ExampleLength: + Enabled: false +RSpec/ExampleWithoutDescription: + Enabled: false +RSpec/ExpectChange: + Enabled: false +RSpec/ExpectInHook: + Enabled: false +RSpec/HooksBeforeExamples: + Enabled: false +RSpec/ImplicitBlockExpectation: + Enabled: false +RSpec/ImplicitSubject: + Enabled: false +RSpec/LeakyConstantDeclaration: + Enabled: false +RSpec/LetBeforeExamples: + Enabled: false +RSpec/MatchArray: + Enabled: false +RSpec/MissingExampleGroupArgument: + Enabled: false +RSpec/MultipleExpectations: + Enabled: false +RSpec/MultipleMemoizedHelpers: + Enabled: false +RSpec/MultipleSubjects: + Enabled: false +RSpec/NestedGroups: + Enabled: false +RSpec/PredicateMatcher: + Enabled: false +RSpec/ReceiveCounts: + Enabled: false +RSpec/ReceiveNever: + Enabled: false +RSpec/RepeatedExampleGroupBody: + Enabled: false +RSpec/RepeatedExampleGroupDescription: + Enabled: false +RSpec/RepeatedIncludeExample: + Enabled: false +RSpec/ReturnFromStub: + Enabled: false +RSpec/SharedExamples: + Enabled: false +RSpec/StubbedMock: + Enabled: false +RSpec/UnspecifiedException: + Enabled: false +RSpec/VariableDefinition: + Enabled: false +RSpec/VoidExpect: + Enabled: false +RSpec/Yield: + Enabled: false +Security/Open: + Enabled: false +Style/AccessModifierDeclarations: + Enabled: false +Style/AccessorGrouping: + Enabled: false +Style/BisectedAttrAccessor: + Enabled: false +Style/CaseLikeIf: + Enabled: false +Style/ClassEqualityComparison: + Enabled: false +Style/ColonMethodDefinition: + Enabled: false +Style/CombinableLoops: + Enabled: false +Style/CommentedKeyword: + Enabled: false +Style/Dir: + Enabled: false +Style/DoubleCopDisableDirective: + Enabled: false +Style/EmptyBlockParameter: + Enabled: false +Style/EmptyLambdaParameter: + Enabled: false +Style/Encoding: + Enabled: false +Style/EvalWithLocation: + Enabled: false +Style/ExpandPathArguments: + Enabled: false +Style/ExplicitBlockArgument: + Enabled: false +Style/ExponentialNotation: + Enabled: false +Style/FloatDivision: + Enabled: false +Style/FrozenStringLiteralComment: + Enabled: false +Style/GlobalStdStream: + Enabled: false +Style/HashAsLastArrayItem: + Enabled: false +Style/HashLikeCase: + Enabled: false +Style/HashTransformKeys: + Enabled: false +Style/HashTransformValues: + Enabled: false +Style/IfUnlessModifier: + Enabled: false +Style/KeywordParametersOrder: + Enabled: false +Style/MinMax: + Enabled: false +Style/MixinUsage: + Enabled: false +Style/MultilineWhenThen: + Enabled: false +Style/NegatedUnless: + Enabled: false +Style/NumericPredicate: + Enabled: false +Style/OptionalBooleanParameter: + Enabled: false +Style/OrAssignment: + Enabled: false +Style/RandomWithOffset: + Enabled: false +Style/RedundantAssignment: + Enabled: false +Style/RedundantCondition: + Enabled: false +Style/RedundantConditional: + Enabled: false +Style/RedundantFetchBlock: + Enabled: false +Style/RedundantFileExtensionInRequire: + Enabled: false +Style/RedundantRegexpCharacterClass: + Enabled: false +Style/RedundantRegexpEscape: + Enabled: false +Style/RedundantSelfAssignment: + Enabled: false +Style/RedundantSort: + Enabled: false +Style/RescueStandardError: + Enabled: false +Style/SingleArgumentDig: + Enabled: false +Style/SlicingWithRange: + Enabled: false +Style/SoleNestedConditional: + Enabled: false +Style/StderrPuts: + Enabled: false +Style/StringConcatenation: + Enabled: false +Style/Strip: + Enabled: false +Style/SymbolProc: + Enabled: false +Style/TrailingBodyOnClass: + Enabled: false +Style/TrailingBodyOnMethodDefinition: + Enabled: false +Style/TrailingBodyOnModule: + Enabled: false +Style/TrailingCommaInHashLiteral: + Enabled: false +Style/TrailingMethodEndStatement: + Enabled: false +Style/UnpackFirst: + Enabled: false +Gemspec/DeprecatedAttributeAssignment: + Enabled: false +Gemspec/DevelopmentDependencies: + Enabled: false +Gemspec/RequireMFA: + Enabled: false +Layout/LineContinuationLeadingSpace: + Enabled: false +Layout/LineContinuationSpacing: + Enabled: false +Layout/LineEndStringConcatenationIndentation: + Enabled: false +Layout/SpaceBeforeBrackets: + Enabled: false +Lint/AmbiguousAssignment: + Enabled: false +Lint/AmbiguousOperatorPrecedence: + Enabled: false +Lint/AmbiguousRange: + Enabled: false +Lint/ConstantOverwrittenInRescue: + Enabled: false +Lint/DeprecatedConstants: + Enabled: false +Lint/DuplicateBranch: + Enabled: false +Lint/DuplicateMagicComment: + Enabled: false +Lint/DuplicateMatchPattern: + Enabled: false +Lint/DuplicateRegexpCharacterClassElement: + Enabled: false +Lint/EmptyBlock: + Enabled: false +Lint/EmptyClass: + Enabled: false +Lint/EmptyInPattern: + Enabled: false +Lint/IncompatibleIoSelectWithFiberScheduler: + Enabled: false +Lint/LambdaWithoutLiteralBlock: + Enabled: false +Lint/NoReturnInBeginEndBlocks: + Enabled: false +Lint/NonAtomicFileOperation: + Enabled: false +Lint/NumberedParameterAssignment: + Enabled: false +Lint/OrAssignmentToConstant: + Enabled: false +Lint/RedundantDirGlobSort: + Enabled: false +Lint/RefinementImportMethods: + Enabled: false +Lint/RequireRangeParentheses: + Enabled: false +Lint/RequireRelativeSelfPath: + Enabled: false +Lint/SymbolConversion: + Enabled: false +Lint/ToEnumArguments: + Enabled: false +Lint/TripleQuotes: + Enabled: false +Lint/UnexpectedBlockArity: + Enabled: false +Lint/UnmodifiedReduceAccumulator: + Enabled: false +Lint/UselessRescue: + Enabled: false +Lint/UselessRuby2Keywords: + Enabled: false +Metrics/CollectionLiteralLength: + Enabled: false +Naming/BlockForwarding: + Enabled: false +Performance/CollectionLiteralInLoop: + Enabled: false +Performance/ConcurrentMonotonicTime: + Enabled: false +Performance/MapCompact: + Enabled: false +Performance/RedundantEqualityComparisonBlock: + Enabled: false +Performance/RedundantSplitRegexpArgument: + Enabled: false +Performance/StringIdentifierArgument: + Enabled: false +RSpec/BeEq: + Enabled: false +RSpec/BeNil: + Enabled: false +RSpec/ChangeByZero: + Enabled: false +RSpec/ClassCheck: + Enabled: false +RSpec/DuplicatedMetadata: + Enabled: false +RSpec/ExcessiveDocstringSpacing: + Enabled: false +RSpec/IdenticalEqualityAssertion: + Enabled: false +RSpec/NoExpectationExample: + Enabled: false +RSpec/PendingWithoutReason: + Enabled: false +RSpec/RedundantAround: + Enabled: false +RSpec/SkipBlockInsideExample: + Enabled: false +RSpec/SortMetadata: + Enabled: false +RSpec/SubjectDeclaration: + Enabled: false +RSpec/VerifiedDoubleReference: + Enabled: false +Security/CompoundHash: + Enabled: false +Security/IoMethods: + Enabled: false +Style/ArgumentsForwarding: + Enabled: false +Style/ArrayIntersect: + Enabled: false +Style/CollectionCompact: + Enabled: false +Style/ComparableClamp: + Enabled: false +Style/ConcatArrayLiterals: + Enabled: false +Style/DataInheritance: + Enabled: false +Style/DirEmpty: + Enabled: false +Style/DocumentDynamicEvalDefinition: + Enabled: false +Style/EmptyHeredoc: + Enabled: false +Style/EndlessMethod: + Enabled: false +Style/EnvHome: + Enabled: false +Style/FetchEnvVar: + Enabled: false +Style/FileEmpty: + Enabled: false +Style/FileRead: + Enabled: false +Style/FileWrite: + Enabled: false +Style/HashConversion: + Enabled: false +Style/HashExcept: + Enabled: false +Style/IfWithBooleanLiteralBranches: + Enabled: false +Style/InPatternThen: + Enabled: false +Style/MagicCommentFormat: + Enabled: false +Style/MapCompactWithConditionalBlock: + Enabled: false +Style/MapToHash: + Enabled: false +Style/MapToSet: + Enabled: false +Style/MinMaxComparison: + Enabled: false +Style/MultilineInPatternThen: + Enabled: false +Style/NegatedIfElseCondition: + Enabled: false +Style/NestedFileDirname: + Enabled: false +Style/NilLambda: + Enabled: false +Style/NumberedParameters: + Enabled: false +Style/NumberedParametersLimit: + Enabled: false +Style/ObjectThen: + Enabled: false +Style/OpenStructUse: + Enabled: false +Style/OperatorMethodCall: + Enabled: false +Style/QuotedSymbols: + Enabled: false +Style/RedundantArgument: + Enabled: false +Style/RedundantConstantBase: + Enabled: false +Style/RedundantDoubleSplatHashBraces: + Enabled: false +Style/RedundantEach: + Enabled: false +Style/RedundantHeredocDelimiterQuotes: + Enabled: false +Style/RedundantInitialize: + Enabled: false +Style/RedundantLineContinuation: + Enabled: false +Style/RedundantSelfAssignmentBranch: + Enabled: false +Style/RedundantStringEscape: + Enabled: false +Style/SelectByRegexp: + Enabled: false +Style/StringChars: + Enabled: false +Style/SwapValues: + Enabled: false diff --git a/Gemfile b/Gemfile index e74c3da..7c330d6 100644 --- a/Gemfile +++ b/Gemfile @@ -10,16 +10,23 @@ ENV['PDK_DISABLE_ANALYTICS'] ||= 'true' gem_sources.each { |gem_source| source gem_source } +group :syntax do + gem 'metadata-json-lint' + gem 'puppet-lint-trailing_comma-check', require: false + gem 'rubocop', '~> 1.68.0' + gem 'rubocop-performance', '~> 1.23.0' + gem 'rubocop-rake', '~> 0.6.0' + gem 'rubocop-rspec', '~> 3.2.0' +end + group :test do puppet_version = ENV.fetch('PUPPET_VERSION', ['>= 7', '< 9']) major_puppet_version = Array(puppet_version).first.scan(%r{(\d+)(?:\.|\Z)}).flatten.first.to_i gem 'hiera-puppet-helper' - gem 'metadata-json-lint' gem 'pathspec', '~> 0.2' if Gem::Requirement.create('< 2.6').satisfied_by?(Gem::Version.new(RUBY_VERSION.dup)) gem('pdk', ENV.fetch('PDK_VERSION', ['>= 2.0', '< 4.0']), require: false) if major_puppet_version > 5 gem 'puppet', puppet_version gem 'puppetlabs_spec_helper' - gem 'puppet-lint-trailing_comma-check', require: false gem 'puppet-strings' gem 'rake' gem 'rspec' diff --git a/lib/facter/apache_version.rb b/lib/facter/apache_version.rb index 0c099a5..c8a0254 100644 --- a/lib/facter/apache_version.rb +++ b/lib/facter/apache_version.rb @@ -3,17 +3,17 @@ # # Returns 'unknown' if the version cannot be determined. # -Facter.add("apache_version") do +Facter.add('apache_version') do apachectl = Facter::Core::Execution.which('apachectl') confine { apachectl } setcode do apache_version = 'unknown' begin - %x{#{apachectl} -v}.to_s.split("\n").first =~ /((\d\.?)+)/ - apache_version = $1 if not $1.to_s.empty? + `#{apachectl} -v`.to_s.split("\n").first =~ %r{((\d\.?)+)} + apache_version = Regexp.last_match(1) unless Regexp.last_match(1).to_s.empty? rescue Errno::ENOENT - #No-op because we only care that the version is unknown if we can't execute a version check. + # No-op because we only care that the version is unknown if we can't execute a version check. end apache_version end diff --git a/lib/puppet/functions/simp_apache/auth.rb b/lib/puppet/functions/simp_apache/auth.rb index e55b547..d288b88 100644 --- a/lib/puppet/functions/simp_apache/auth.rb +++ b/lib/puppet/functions/simp_apache/auth.rb @@ -3,7 +3,6 @@ # # Currently, only htaccess and LDAP support are implemented. Puppet::Functions.create_function(:'simp_apache::auth') do - # @param auth_hash Hash containing desired Apache authentication # methods and relevant parameters as key value pairs. The # key is the authentication method, while the corresponding @@ -59,8 +58,8 @@ def format_auth(auth_hash) begin send("auth_#{auth_method}", auth_hash[auth_method], method_content) enabled_methods << auth_method - rescue NoMethodError => e - fail("simp_apache::auth(): Error, '#{auth_method}' not yet supported") + rescue NoMethodError + raise("simp_apache::auth(): Error, '#{auth_method}' not yet supported") end end @@ -68,48 +67,48 @@ def format_auth(auth_hash) # here. unless enabled_methods.empty? apache_auth_content << 'AuthName "Please Authenticate"' - apache_auth_content << "AuthType Basic" + apache_auth_content << 'AuthType Basic' apache_auth_content << "AuthBasicProvider #{enabled_methods.join(' ')}" apache_auth_content += method_content end - return apache_auth_content.join("\n") + apache_auth_content.join("\n") end def true?(val) - return val.to_s.downcase == 'true' + val.to_s.downcase == 'true' end - def check_required_opts(required_opts,opts) + def check_required_opts(required_opts, opts) opt_test = required_opts - opts - unless opt_test.empty? - fail("simp_apache::auth(): Error, missing option(s) '#{opt_test.join(', ')}'") - end + return if opt_test.empty? + raise("simp_apache::auth(): Error, missing option(s) '#{opt_test.join(', ')}'") + end - def auth_ldap(opts,content) + def auth_ldap(opts, content) required_opts = [ 'url', 'search', - 'posix_group' + 'posix_group', ] valid_sec_methods = [ 'NONE', 'SSL', 'TLS', - 'STARTTLS' + 'STARTTLS', ] - check_required_opts(required_opts,opts.keys) + check_required_opts(required_opts, opts.keys) - ldapuri = 'ldap://' + Array(opts['url']).join(' ').gsub(/ldap:\/\//,'') + ldapuri = 'ldap://' + Array(opts['url']).join(' ').gsub('ldap://', '') ldapuri = ldapuri + '/' + opts['search'] ldapuri = '"' + ldapuri + '"' if opts['security'] unless valid_sec_methods.include?(opts['security']) - fail("simp_apache::auth(): Error, 'security' must be one of {#{valid_sec_methods.join(', ')}}. Got: '#{opts['security']}'") + raise("simp_apache::auth(): Error, 'security' must be one of {#{valid_sec_methods.join(', ')}}. Got: '#{opts['security']}'") end ldapuri = "#{ldapuri} #{opts['security']}" end @@ -117,19 +116,19 @@ def auth_ldap(opts,content) content << "AuthLDAPUrl #{ldapuri}" if opts['binddn'] content << "AuthLDAPBindDN \"#{opts['binddn']}\"" - content << "AuthLDAPBindPassword '#{opts['bindpw'].gsub(/'/, "\\\\'")}'" if opts['bindpw'] + content << "AuthLDAPBindPassword '#{opts['bindpw'].gsub(''', "\\\\'")}'" if opts['bindpw'] end - if true?(opts['posix_group']) - content << "AuthLDAPGroupAttributeIsDN off" - content << "AuthLDAPGroupAttribute memberUid" - end + return unless true?(opts['posix_group']) + content << 'AuthLDAPGroupAttributeIsDN off' + content << 'AuthLDAPGroupAttribute memberUid' + end - def auth_file(opts,content) + def auth_file(opts, content) required_opts = [ 'user_file' ] - check_required_opts(required_opts,opts.keys) + check_required_opts(required_opts, opts.keys) content << "AuthUserFile #{opts['user_file']}" end diff --git a/lib/puppet/functions/simp_apache/limits.rb b/lib/puppet/functions/simp_apache/limits.rb index df040db..cece8c0 100644 --- a/lib/puppet/functions/simp_apache/limits.rb +++ b/lib/puppet/functions/simp_apache/limits.rb @@ -1,7 +1,7 @@ # Takes a hash of arguments related to Apache 'Limits' settings and # returns a reasonably formatted set of options. # -# Currently, host, user ('valid-user' only), ldap-user, and +# Currently, host, user ('valid-user' only), ldap-user, and # ldap-group limits are supported. The hash keys for these are # host limit: 'hosts' # user limit: 'users'; only applies for 'valid-user', all others assumed @@ -13,7 +13,6 @@ # to know the GID. # Puppet::Functions.create_function(:'simp_apache::limits') do - # @param limits_hash Hash containing desired Apache limits # @return [String] Formatted Apache limits settings # @@ -94,18 +93,16 @@ def format_limits(limits_hash) limit_collection = {} - limits.keys.sort.each do |key| - begin - send("limit_#{key}",limits[key],limit_collection,limit_defaults) - rescue NoMethodError => e - fail("simp_apache::limits(): Error, '#{key}' not yet supported") - end + limits.keys.sort.each do |key| + send("limit_#{key}", limits[key], limit_collection, limit_defaults) + rescue NoMethodError + raise("simp_apache::limits(): Error, '#{key}' not yet supported") end - return collect_output(limit_collection) + collect_output(limit_collection) end - def limit_hosts(opts,collection,limit_defaults) + def limit_hosts(opts, collection, limit_defaults) opts.keys.sort.each do |k| v = (opts[k] == 'defaults') ? limit_defaults : Array(opts[k]) v.each do |oper| @@ -116,28 +113,28 @@ def limit_hosts(opts,collection,limit_defaults) end end - #FIXME: This is super confusing: + # FIXME: This is super confusing: # 1) The 'users' key is used for LDAP users and a special # wild card. In contrast, the 'ldap_groups' key is # used for LDAP groups. # 2) There is no real support for non-LDAP users. - def limit_users(opts,collection,limit_defaults) + def limit_users(opts, collection, limit_defaults) opts.keys.sort.each do |k| v = (opts[k] == 'defaults') ? limit_defaults : Array(opts[k]) v.each do |oper| collection[oper] ||= [] - if k == 'valid-user' - collection[oper] << 'Require valid-user' - else - collection[oper] << "Require ldap-user #{k}" - end + collection[oper] << if k == 'valid-user' + 'Require valid-user' + else + "Require ldap-user #{k}" + end end end end - def limit_ldap_groups(opts,collection,limit_defaults) + def limit_ldap_groups(opts, collection, limit_defaults) opts.keys.sort.each do |k| v = (opts[k] == 'defaults') ? limit_defaults : Array(opts[k]) diff --git a/lib/puppet/functions/simp_apache/munge_httpd_networks.rb b/lib/puppet/functions/simp_apache/munge_httpd_networks.rb index 3f9168c..0393b15 100644 --- a/lib/puppet/functions/simp_apache/munge_httpd_networks.rb +++ b/lib/puppet/functions/simp_apache/munge_httpd_networks.rb @@ -7,7 +7,6 @@ # The case where a / is # passed is also handled since Apache doesn't care for these at all. Puppet::Functions.create_function(:'simp_apache::munge_httpd_networks') do - # @param networks Array of networks to be converted to Apache format # @return [Array] Array of network s formated appropriately for Apache dispatch :munge_httpd_networks do @@ -22,14 +21,14 @@ def munge_httpd_networks(networks) x = net.strip next if x.empty? - #TODO what about IPv6 addresses? - if x =~ /^0\.0\.0\.0/ - httpd_networks << 'ALL' - elsif x =~ /\/\d{1,3}\./ - httpd_networks << call_function('simplib::nets2cidr', x) - else - httpd_networks << x - end + # TODO: what about IPv6 addresses? + httpd_networks << if %r{^0\.0\.0\.0}.match?(x) + 'ALL' + elsif %r{/\d{1,3}\.}.match?(x) + call_function('simplib::nets2cidr', x) + else + x + end end httpd_networks.flatten diff --git a/lib/puppet/provider/htaccess/htaccess.rb b/lib/puppet/provider/htaccess/htaccess.rb index 89cad90..7f6067f 100644 --- a/lib/puppet/provider/htaccess/htaccess.rb +++ b/lib/puppet/provider/htaccess/htaccess.rb @@ -1,22 +1,22 @@ Puppet::Type.type(:htaccess).provide :htaccess do require 'fileutils' - desc "Htaccess provider" + desc 'Htaccess provider' - HTACCESS_EDIT_MSG = "# This file managed by Puppet. Please do not edit by hand!" + HTACCESS_EDIT_MSG = '# This file managed by Puppet. Please do not edit by hand!'.freeze def create_target target = @resource[:name].split(':').first - username = @resource[:name].split(':').last + @resource[:name].split(':').last FileUtils.touch(target) - FileUtils.chmod(0640,target) - FileUtils.chown('root','root',target) + FileUtils.chmod(0o640, target) + FileUtils.chown('root', 'root', target) end def target_exist? target = @resource[:name].split(':').first - username = @resource[:name].split(':').last + @resource[:name].split(':').last File.exist?(target) end @@ -26,25 +26,25 @@ def mod_target(mod_type) username = @resource[:name].split(':').last begin - self.target_exist? or self.create_target + target_exist? or create_target tmpname = "#{File.dirname(target)}/.#{File.basename(target)}.htpasswd.tmp" - outfile = File.open(tmpname,'w+') - FileUtils.chmod(0600,tmpname) + outfile = File.open(tmpname, 'w+') + FileUtils.chmod(0o600, tmpname) - fh = File.open(target,'r') + fh = File.open(target, 'r') # Check for the edit message and add if necessary. if fh.eof? outfile.puts(HTACCESS_EDIT_MSG) - elsif not fh.readline.chomp.eql?(HTACCESS_EDIT_MSG) + elsif !fh.readline.chomp.eql?(HTACCESS_EDIT_MSG) outfile.puts(HTACCESS_EDIT_MSG) fh.rewind else fh.rewind end - if mod_type.eql?("create") + if mod_type.eql?('create') fh.each do |line| line.chomp! @@ -52,25 +52,25 @@ def mod_target(mod_type) end outfile.puts("#{username}:#{@resource[:password]}") - elsif mod_type.eql?("modify") + elsif mod_type.eql?('modify') fh.rewind fh.each do |line| line.chomp! - (l_uname,l_pass) = line.split(':') + (l_uname,) = line.split(':') - if l_uname.eql?(username) then + if l_uname.eql?(username) outfile.puts("#{username}:#{@resource[:password]}") else outfile.puts(line) end end - elsif mod_type.eql?("delete") + elsif mod_type.eql?('delete') fh.rewind fh.each do |line| line.chomp! - if not line.split(':').first.eql?(username) then + unless line.split(':').first.eql?(username) outfile.puts(line) end end @@ -78,25 +78,24 @@ def mod_target(mod_type) fh.close outfile.close - FileUtils.cp(tmpname,target) + FileUtils.cp(tmpname, target) FileUtils.rm(tmpname) rescue Exception => e - fail Puppet::Error, e + raise Puppet::Error, e end - end def create - mod_target("create") + mod_target('create') end def destroy - mod_target("delete") + mod_target('delete') end def passwd_sync - mod_target("modify") - return nil + mod_target('modify') + nil end def exists? @@ -104,18 +103,17 @@ def exists? username = @resource[:name].split(':').last begin - File.open(target,'r').each do |line| - + File.open(target, 'r').each do |line| line.chomp! - if line.split(':').first.eql?(username) then + if line.split(':').first.eql?(username) return true end end - return false + false rescue Exception => e - fail Puppet::Error, e + raise Puppet::Error, e end end @@ -124,22 +122,20 @@ def passwd_retrieve username = @resource[:name].split(':').last begin - self.target_exist? or return nil + target_exist? or return nil - File.open(target,'r').each do |line| + File.open(target, 'r').each do |line| line.chomp! - (l_uname,l_pass) = line.split(':') + (l_uname, l_pass) = line.split(':') - if l_uname.eql?(username) then + if l_uname.eql?(username) return l_pass end end - rescue Exception => e - fail Puppet::Error, e + raise Puppet::Error, e end - return nil + nil end - end diff --git a/lib/puppet/type/htaccess.rb b/lib/puppet/type/htaccess.rb index dea1ef0..abe12a3 100644 --- a/lib/puppet/type/htaccess.rb +++ b/lib/puppet/type/htaccess.rb @@ -18,9 +18,9 @@ validate do |value| target = value.split(':').first - fail Puppet::Error, "name is missing either the path or the username. Name format must be 'path:username'" if value !~ /.+:.+/ + raise Puppet::Error, "name is missing either the path or the username. Name format must be 'path:username'" unless %r{.+:.+}.match?(value) - fail Puppet::Error, "File paths must be fully qualified, not #{target}" if value !~ /^\// + raise Puppet::Error, "File paths must be fully qualified, not #{target}" unless %r{^/}.match?(value) end end @@ -37,14 +37,14 @@ def sync end def retrieve - return provider.passwd_retrieve + provider.passwd_retrieve end munge do |value| - unless value =~ /^\{SHA\}/ + unless %r{^\{SHA\}}.match?(value) require 'digest/sha1' require 'base64' - value = "{SHA}"+Base64.encode64(Digest::SHA1.digest(value)).chomp! + value = '{SHA}' + Base64.encode64(Digest::SHA1.digest(value)).chomp! end value @@ -54,7 +54,7 @@ def retrieve autorequire(:file) do torequire = self[:name].split(':').first - if catalog.resources.find_all { |r| r.is_a?(Puppet::Type.type(:file)) and r[:name] == torequire }.empty? then + if catalog.resources.none? { |r| r.is_a?(Puppet::Type.type(:file)) && (r[:name] == torequire) } err "You must declare a 'file' object to manage #{torequire}!" end @@ -66,9 +66,8 @@ def retrieve required_fields.each do |req| unless @parameters.include?(req) - fail Puppet::Error, "You must specify #{req}." + raise Puppet::Error, "You must specify #{req}." end end end - end diff --git a/spec/acceptance/suites/default/class_spec.rb b/spec/acceptance/suites/default/class_spec.rb index 16daa48..059f527 100644 --- a/spec/acceptance/suites/default/class_spec.rb +++ b/spec/acceptance/suites/default/class_spec.rb @@ -4,34 +4,35 @@ describe 'apache class' do hosts.each do |host| - context 'basic parameters' do let(:manifest) { "include 'simp_apache'" } let(:host_fqdn) { fact_on(host, 'fqdn') } - let(:hieradata) {{ - 'simp_apache::rsync_web_root' => false, - 'simp_options::pki' => true, - 'simp_options::pki::source' => '/etc/pki/simp-testing/pki/' - }} + let(:hieradata) do + { + 'simp_apache::rsync_web_root' => false, + 'simp_options::pki' => true, + 'simp_options::pki::source' => '/etc/pki/simp-testing/pki/' + } + end - it 'should work with no errors' do + it 'works with no errors' do set_hieradata_on(host, hieradata) - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - it 'should be idempotent' do + it 'is idempotent' do puppet_version = pfact_on(host, 'puppetversion') if Gem::Version.new(puppet_version) < Gem::Version.new('6.23.0') # Additional run to work around PUP-7559 - apply_manifest_on(host, manifest, :catch_failures => true) + apply_manifest_on(host, manifest, catch_failures: true) end - apply_manifest_on(host, manifest, :catch_changes => true) + apply_manifest_on(host, manifest, catch_changes: true) end - it 'should respond to http' do - result = on(host,'curl localhost') - expect(result.output).to match(/You don't have permission to access /) + it 'responds to http' do + result = on(host, 'curl localhost') + expect(result.output).to match(%r{You don't have permission to access }) end end end diff --git a/spec/acceptance/suites/htaccess/htaccess_spec.rb b/spec/acceptance/suites/htaccess/htaccess_spec.rb index d8786d8..61b87ad 100644 --- a/spec/acceptance/suites/htaccess/htaccess_spec.rb +++ b/spec/acceptance/suites/htaccess/htaccess_spec.rb @@ -1,63 +1,65 @@ require 'spec_helper_acceptance' -test_name "htaccess type/provider" +test_name 'htaccess type/provider' hosts.each do |host| describe "htaccess type/provider for #{host}" do - let(:manifest1) { <<~EOM + let(:manifest1) do + <<~EOM htaccess { 'user1': name => '/root/htaccess.txt:user1', password=>"user1's password" } htaccess { 'user2': name => '/root/htaccess.txt:user2', password=>"{SHA}yLo2mwINaPQsTgevY0gyfH9mxk4=" } EOM - } + end - let(:manifest2) { <<~EOM + let(:manifest2) do + <<~EOM file { '/root/htaccess.txt': ensure => present } htaccess { 'user1': name => '/root/htaccess.txt:user1', password=>"user1's password" } htaccess { 'user2': name => '/root/htaccess.txt:user2', password=>"{SHA}yLo2mwINaPQsTgevY0gyfH9mxk4=" } EOM - } + end - let(:manifest3) { <<~EOM + let(:manifest3) do + <<~EOM file { '/root/htaccess.txt': ensure => present } htaccess { 'user1': name => '/root/htaccess.txt:user1', password=>"user1's password", ensure=>absent } htaccess { 'user2': name => '/root/htaccess.txt:user2', password=>"{SHA}yLo2mwINaPQsTgevY0gyfH9mxk4=", ensure=>absent } htaccess { 'user3': name => '/root/htaccess.txt:user3', password=>"user3's password" } EOM - } + end - it 'should require file resource' do - apply_manifest_on(host, manifest1, :expect_failures => true) do - expect(stderr).to match(/You must declare a 'file' object to manage \/root\/htaccess.txt!/m) + it 'requires file resource' do + apply_manifest_on(host, manifest1, expect_failures: true) do + expect(stderr).to match(%r{You must declare a 'file' object to manage /root/htaccess.txt!}m) end end - it 'should work with no errors' do - apply_manifest_on(host, manifest2, :catch_failures => true) + it 'works with no errors' do + apply_manifest_on(host, manifest2, catch_failures: true) - on host, 'cat /root/htaccess.txt', :acceptable_exit_codes => 0 do + on host, 'cat /root/htaccess.txt', acceptable_exit_codes: 0 do lines = stdout.split("\n") expect(lines.size).to eq(3) expect(lines.first).to eq('# This file managed by Puppet. Please do not edit by hand!') # The order of entries is non-deterministic, so test with regex: - expect(stdout).to match(/^user1:{SHA}CLub7iwpjkqz0enKLoRcbiDtUCo=$/) - expect(stdout).to match(/^user2:{SHA}yLo2mwINaPQsTgevY0gyfH9mxk4=$/) + expect(stdout).to match(%r{^user1:{SHA}CLub7iwpjkqz0enKLoRcbiDtUCo=$}) + expect(stdout).to match(%r{^user2:{SHA}yLo2mwINaPQsTgevY0gyfH9mxk4=$}) end - end - it 'should be idempotent' do - apply_manifest_on(host, manifest2, :catch_changes => true) + it 'is idempotent' do + apply_manifest_on(host, manifest2, catch_changes: true) end - it 'should be be ensurable' do - apply_manifest_on(host, manifest3, :catch_failures => true) + it 'is be ensurable' do + apply_manifest_on(host, manifest3, catch_failures: true) expected = <<~EOM # This file managed by Puppet. Please do not edit by hand! user3:{SHA}UJWYsWH31uLIUPa4iazyItrNbys= EOM - on host, 'cat /root/htaccess.txt', :acceptable_exit_codes => 0 do - expect(stdout).to eq(expected) + on host, 'cat /root/htaccess.txt', acceptable_exit_codes: 0 do + expect(stdout).to eq(expected) end end end diff --git a/spec/classes/conf_spec.rb b/spec/classes/conf_spec.rb index cdab2a0..7e8c2d1 100644 --- a/spec/classes/conf_spec.rb +++ b/spec/classes/conf_spec.rb @@ -24,21 +24,22 @@ it { is_expected.to compile.with_all_deps } it { is_expected.to create_class('simp_apache::conf') } it { is_expected.not_to create_iptables__listen__tcp_stateful('allow_http') } - it { is_expected.to_not create_rsyslog__rule__local('XX_apache_error') } - it { is_expected.to_not create_rsyslog__rule__local('YY_apache_access') } + it { is_expected.not_to create_rsyslog__rule__local('XX_apache_error') } + it { is_expected.not_to create_rsyslog__rule__local('YY_apache_access') } it do expected_file = File.join(expected_dir, "httpd.conf_default_el#{facts[:os][:release][:major]}") is_expected.to create_file('/etc/httpd/conf/httpd.conf').with( - :owner => 'root', - :group => 'apache', - :mode => '0640', - :content => IO.read(expected_file) + owner: 'root', + group: 'apache', + mode: '0640', + content: IO.read(expected_file), ) end end context 'firewall = true' do - let(:params){{ 'firewall' => true }} + let(:params) { { 'firewall' => true } } + it { is_expected.to compile.with_all_deps } it { is_expected.to create_class('iptables') } it { is_expected.to create_class('simp_apache::conf') } @@ -46,7 +47,8 @@ end context 'syslog = true' do - let(:params){{ 'syslog' => true }} + let(:params) { { 'syslog' => true } } + it { is_expected.to compile.with_all_deps } it { is_expected.to create_class('simp_apache::conf') } it { is_expected.to create_class('rsyslog') } diff --git a/spec/classes/expected/httpd.conf_default_el9 b/spec/classes/expected/httpd.conf_default_el9 new file mode 100644 index 0000000..33a301c --- /dev/null +++ b/spec/classes/expected/httpd.conf_default_el9 @@ -0,0 +1,332 @@ +TraceEnable off +ServerTokens ProductOnly + +ServerRoot "/etc/httpd" + +PidFile run/httpd.pid + +# Default: 120 +Timeout 120 + +# Default: Off +KeepAlive Off + +# Default: 100 +MaxKeepAliveRequests 100 + +# Default: 15 +KeepAliveTimeout 15 + + +# Default: 8 +StartServers 8 +# Default: 5 +MinSpareServers 5 +# Default: 20 +MaxSpareServers 20 +# Default: 256 +ServerLimit 3000 +# Default: 256 +MaxClients 3000 +# Default: 4000 +MaxRequestsPerChild 4000 + + + +# Default: 2 +StartServers 2 +# Default: 150 +MaxClients 3000 +# Default: 25 +MinSpareThreads 25 +# Default: 75 +MaxSpareThreads 75 +# Default: 25 +ThreadsPerChild 25 +# Default: 0 +MaxRequestsPerChild 0 + + +# Default: 80 +Listen 80 + +Include conf.modules.d/*.conf + +Include conf.d/*.conf + +User apache +Group apache + +# Default: root@localhost +ServerAdmin root@localhost + +UseCanonicalName Off + +DocumentRoot "/var/www/html" + + + Options +FollowSymLinks + AllowOverride None + + + + + Options -Indexes +FollowSymLinks + AllowOverride None + Order allow,deny + Allow from ::1 + Allow from 10.0.2.15 + Allow from 127.0.0.1 + Allow from 127.0.0.1 + Allow from ::1 + + + + + # + # The following directives define some format nicknames for use with + # a CustomLog directive (see below). + # + LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" combined + LogFormat "%h %l %u %t \"%r\" %>s %b" common + + + # You need to enable mod_logio.c to use %I and %O + LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\" %I %O" combinedio + + + # + # The location and format of the access logfile (Common Logfile Format). + # If you do not define any access logfiles within a + # container, they will be logged here. Contrariwise, if you *do* + # define per- access logfiles, transactions will be + # logged therein and *not* in this file. + # + #CustomLog "logs/access_log" common + + # + # If you prefer a logfile with access, agent, and referer information + # (Combined Logfile Format) you can use the following directive. + # + CustomLog "logs/access_log" combined + + + + ScriptAlias /cgi-bin/ "/var/www/cgi-bin/" + + + + UserDir disable + + +DirectoryIndex index.html index.html.var + +AccessFileName .htaccess + + + Order allow,deny + Deny from all + + + + TypesConfig /etc/mime.types + + AddType application/x-compress .Z + AddType application/x-gzip .gz .tgz + + AddType text/html .shtml + AddOutputFilter INCLUDES .shtml + + + + MIMEMagicFile conf/magic + + + +# Default: text/plain +DefaultType text/plain + +HostnameLookups Off + +# Default: on +EnableMMAP On + +# Default: on +EnableSendfile On + +ErrorLog syslog:local6 + +LogLevel warn + +LogFormat "%h %l %u %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-Agent}i\"" custom + +CustomLog "|/bin/logger -thttpd -plocal6.notice" custom + +ServerSignature Off + +Alias /icons/ "/var/www/icons/" + + + Options +Indexes +MultiViews + AllowOverride None + Order allow,deny + Allow from ::1 + Allow from 10.0.2.15 + Allow from 127.0.0.1 + Allow from 127.0.0.1 + Allow from ::1 + + + + AllowOverride None + Options +ExecCGI -FollowSymLinks + Order allow,deny + Allow from ::1 + Allow from 10.0.2.15 + Allow from 127.0.0.1 + Allow from 127.0.0.1 + Allow from ::1 + + +IndexOptions FancyIndexing VersionSort NameWidth=* + +AddIconByEncoding (CMP,/icons/compressed.gif) x-compress x-gzip + +AddIconByType (TXT,/icons/text.gif) text/* +AddIconByType (IMG,/icons/image2.gif) image/* +AddIconByType (SND,/icons/sound2.gif) audio/* +AddIconByType (VID,/icons/movie.gif) video/* + +AddIcon /icons/binary.gif .bin .exe +AddIcon /icons/binhex.gif .hqx +AddIcon /icons/tar.gif .tar +AddIcon /icons/world2.gif .wrl .wrl.gz .vrml .vrm .iv +AddIcon /icons/compressed.gif .Z .z .tgz .gz .zip +AddIcon /icons/a.gif .ps .ai .eps +AddIcon /icons/layout.gif .html .shtml .htm .pdf +AddIcon /icons/text.gif .txt +AddIcon /icons/c.gif .c +AddIcon /icons/p.gif .pl .py +AddIcon /icons/f.gif .for +AddIcon /icons/dvi.gif .dvi +AddIcon /icons/uuencoded.gif .uu +AddIcon /icons/script.gif .conf .sh .shar .csh .ksh .tcl +AddIcon /icons/tex.gif .tex +AddIcon /icons/bomb.gif core + +AddIcon /icons/back.gif .. +AddIcon /icons/hand.right.gif README +AddIcon /icons/folder.gif ^^DIRECTORY^^ +AddIcon /icons/blank.gif ^^BLANKICON^^ + +DefaultIcon /icons/unknown.gif + +AddDescription "GZIP compressed document" .gz +AddDescription "tar archive" .tar +AddDescription "GZIP compressed tar archive" .tgz +AddDescription "ZIP file" .zip +AddDescription "Microsoft Office File" .doc .xls .ppt +AddDescription "Adobe PDF" .pdf + +ReadmeName README.html +HeaderName HEADER.html + +IndexIgnore .??* *~ *# HEADER* README* RCS CVS *,v *,t + +AddLanguage ca .ca +AddLanguage cs .cz .cs +AddLanguage da .dk +AddLanguage de .de +AddLanguage el .el +AddLanguage en .en +AddLanguage eo .eo +AddLanguage es .es +AddLanguage et .et +AddLanguage fr .fr +AddLanguage he .he +AddLanguage hr .hr +AddLanguage it .it +AddLanguage ja .ja +AddLanguage ko .ko +AddLanguage ltz .ltz +AddLanguage nl .nl +AddLanguage nn .nn +AddLanguage no .no +AddLanguage pl .po +AddLanguage pt .pt +AddLanguage pt-BR .pt-br +AddLanguage ru .ru +AddLanguage sv .sv +AddLanguage zh-CN .zh-cn +AddLanguage zh-TW .zh-tw + +LanguagePriority en ca cs da de el eo es et fr he hr it ja ko ltz nl nn no pl pt pt-BR ru sv zh-CN zh-TW + +ForceLanguagePriority Prefer Fallback + +AddDefaultCharset UTF-8 + +AddCharset ISO-8859-1 .iso8859-1 .latin1 +AddCharset ISO-8859-2 .iso8859-2 .latin2 .cen +AddCharset ISO-8859-3 .iso8859-3 .latin3 +AddCharset ISO-8859-4 .iso8859-4 .latin4 +AddCharset ISO-8859-5 .iso8859-5 .latin5 .cyr .iso-ru +AddCharset ISO-8859-6 .iso8859-6 .latin6 .arb +AddCharset ISO-8859-7 .iso8859-7 .latin7 .grk +AddCharset ISO-8859-8 .iso8859-8 .latin8 .heb +AddCharset ISO-8859-9 .iso8859-9 .latin9 .trk +AddCharset ISO-2022-JP .iso2022-jp .jis +AddCharset ISO-2022-KR .iso2022-kr .kis +AddCharset ISO-2022-CN .iso2022-cn .cis +AddCharset Big5 .Big5 .big5 +AddCharset WINDOWS-1251 .cp-1251 .win-1251 +AddCharset CP866 .cp866 +AddCharset KOI8-r .koi8-r .koi8-ru +AddCharset KOI8-ru .koi8-uk .ua +AddCharset ISO-10646-UCS-2 .ucs2 +AddCharset ISO-10646-UCS-4 .ucs4 +AddCharset UTF-8 .utf8 + +AddCharset GB2312 .gb2312 .gb +AddCharset utf-7 .utf7 +AddCharset utf-8 .utf8 +AddCharset big5 .big5 .b5 +AddCharset EUC-TW .euc-tw +AddCharset EUC-JP .euc-jp +AddCharset EUC-KR .euc-kr +AddCharset shift_jis .sjis + +AddHandler imap-file map + +AddHandler type-map var + +Alias /error/ "/var/www/error/" + + + + + AllowOverride None + Options +IncludesNoExec + AddOutputFilter Includes html + AddHandler type-map var + Order allow,deny + Allow from all + LanguagePriority en es de fr + ForceLanguagePriority Prefer Fallback + + + + + +BrowserMatch "Mozilla/2" nokeepalive +BrowserMatch "MSIE 4\.0b2;" nokeepalive downgrade-1.0 force-response-1.0 +BrowserMatch "RealPlayer 4\.0" force-response-1.0 +BrowserMatch "Java/1\.0" force-response-1.0 +BrowserMatch "JDK/1\.0" force-response-1.0 + +BrowserMatch "Microsoft Data Access Internet Publishing Provider" redirect-carefully +BrowserMatch "^WebDrive" redirect-carefully +BrowserMatch "^WebDAVFS/1.[0123]" redirect-carefully +BrowserMatch "^gnome-vfs/1.0" redirect-carefully +BrowserMatch "^XML Spy" redirect-carefully +BrowserMatch "^Dreamweaver-WebDAV-SCM1" redirect-carefully diff --git a/spec/classes/init_spec.rb b/spec/classes/init_spec.rb index b3749dc..66ead61 100644 --- a/spec/classes/init_spec.rb +++ b/spec/classes/init_spec.rb @@ -1,6 +1,6 @@ require 'spec_helper' -shared_examples_for "a simp_apache class" do +shared_examples_for 'a simp_apache class' do it { is_expected.to compile.with_all_deps } it { is_expected.to create_class('simp_apache') } it { is_expected.to create_class('simp_apache::install') } @@ -22,42 +22,46 @@ context 'supported operating systems' do on_supported_os.each do |os, facts| context "on #{os}" do - let(:environment){ 'production' } + let(:environment) { 'production' } let(:facts) do - facts.merge({environment: environment}) + facts.merge({ environment: environment }) end context 'with default parameters' do - it_should_behave_like "a simp_apache class" + it_behaves_like 'a simp_apache class' it { is_expected.to create_class('simp_apache::ssl') } - it { is_expected.to create_rsync('site').with({ - :source => "apache_#{environment}_#{facts[:os][:name]}/www" - }) + it { + is_expected.to create_rsync('site').with({ + source: "apache_#{environment}_#{facts[:os][:name]}/www" + }) } it { is_expected.to create_selboolean('httpd_can_network_connect') } end context 'no_rsync_web_root' do - let(:params){{ :rsync_web_root => false }} - it_should_behave_like "a simp_apache class" + let(:params) { { rsync_web_root: false } } + + it_behaves_like 'a simp_apache class' it { is_expected.to create_class('simp_apache::ssl') } it { is_expected.not_to create_rsync('site') } it { is_expected.to create_selboolean('httpd_can_network_connect') } end context 'no_ssl' do - let(:params){{ :ssl => false }} - it_should_behave_like "a simp_apache class" + let(:params) { { ssl: false } } + + it_behaves_like 'a simp_apache class' it { is_expected.not_to create_class('simp_apache::ssl') } it { is_expected.to create_rsync('site') } it { is_expected.to create_selboolean('httpd_can_network_connect') } end context 'no_manage_service' do - let(:hieradata){'no_manage_service'} - it_should_behave_like "a simp_apache class" - it { is_expected.to_not contain_service('httpd') } + let(:hieradata) { 'no_manage_service' } + + it_behaves_like 'a simp_apache class' + it { is_expected.not_to contain_service('httpd') } end end end diff --git a/spec/classes/ssl_spec.rb b/spec/classes/ssl_spec.rb index 5c8f3a2..9374f6f 100644 --- a/spec/classes/ssl_spec.rb +++ b/spec/classes/ssl_spec.rb @@ -12,40 +12,40 @@ it { is_expected.to compile.with_all_deps } it { is_expected.to create_class('simp_apache') } it { is_expected.to create_class('simp_apache::ssl') } - it { is_expected.to_not create_iptables__listen__tcp_stateful('allow_https') } - it { is_expected.to_not create_class('pki') } - it { is_expected.to_not create_pki__copy('simp_apache') } - it { is_expected.to_not contain_class('haveged') } + it { is_expected.not_to create_iptables__listen__tcp_stateful('allow_https') } + it { is_expected.not_to create_class('pki') } + it { is_expected.not_to create_pki__copy('simp_apache') } + it { is_expected.not_to contain_class('haveged') } end context 'firewall = true' do - let(:params){{ :firewall => true }} + let(:params) { { firewall: true } } it { is_expected.to compile.with_all_deps } it { is_expected.to create_class('simp_apache') } it { is_expected.to create_class('simp_apache::ssl') } it { is_expected.to create_iptables__listen__tcp_stateful('allow_https') } - it { is_expected.to_not create_class('pki') } - it { is_expected.to_not create_pki__copy('simp_apache') } + it { is_expected.not_to create_class('pki') } + it { is_expected.not_to create_pki__copy('simp_apache') } end context 'pki = simp' do - let(:params){{ :pki => 'simp' }} + let(:params) { { pki: 'simp' } } it { is_expected.to compile.with_all_deps } it { is_expected.to create_class('simp_apache') } it { is_expected.to create_class('simp_apache::ssl') } - it { is_expected.to_not create_iptables__listen__tcp_stateful('allow_https') } + it { is_expected.not_to create_iptables__listen__tcp_stateful('allow_https') } it { is_expected.to contain_class('pki') } it { is_expected.to create_pki__copy('simp_apache') } it { is_expected.to create_file('/etc/pki/simp_apps/simp_apache/x509') } end context 'with haveged = false' do - let(:params) {{:haveged => false}} - it { is_expected.to_not contain_class('haveged') } - end + let(:params) { { haveged: false } } + it { is_expected.not_to contain_class('haveged') } + end end end end diff --git a/spec/defines/site_spec.rb b/spec/defines/site_spec.rb index 170415d..fd7359d 100644 --- a/spec/defines/site_spec.rb +++ b/spec/defines/site_spec.rb @@ -9,8 +9,9 @@ end context 'with default parameters' do - let(:title) {'test'} - let(:params) {{ :content => 'test' }} + let(:title) { 'test' } + let(:params) { { content: 'test' } } + it { is_expected.to compile.with_all_deps } it { is_expected.to create_class('simp_apache') } it { is_expected.to contain_file("/etc/httpd/conf.d/#{title}.conf").with_content('test') } diff --git a/spec/functions/simp_apache/auth_spec.rb b/spec/functions/simp_apache/auth_spec.rb index 54184ac..52d51c0 100644 --- a/spec/functions/simp_apache/auth_spec.rb +++ b/spec/functions/simp_apache/auth_spec.rb @@ -1,33 +1,39 @@ require 'spec_helper' describe 'simp_apache::auth' do - let(:file_auth_hash) {{ - 'file' => { - 'enable' => 'true', - 'user_file' => '/etc/httpd/conf.d/test/.htdigest' + let(:file_auth_hash) do + { + 'file' => { + 'enable' => 'true', + 'user_file' => '/etc/httpd/conf.d/test/.htdigest' + } } - }} - - let(:full_ldap_auth_hash) {{ - 'ldap' => { - 'enable' => 'true', - 'url' => ['ldap://server1','ldap://server2'], - 'security' => 'NONE', - 'binddn' => 'cn=happy,ou=People,dc=your,dc=domain', - 'bindpw' => 'birthday', - 'search' => 'ou=People,dc=your,dc=domain', - 'posix_group' => 'true' + end + + let(:full_ldap_auth_hash) do + { + 'ldap' => { + 'enable' => 'true', + 'url' => ['ldap://server1', 'ldap://server2'], + 'security' => 'NONE', + 'binddn' => 'cn=happy,ou=People,dc=your,dc=domain', + 'bindpw' => 'birthday', + 'search' => 'ou=People,dc=your,dc=domain', + 'posix_group' => 'true' + } } - }} - - let(:minimal_ldap_auth_hash) {{ - 'ldap' => { - 'enable' => 'true', - 'url' => ['ldap://server1','ldap://server2'], - 'search' => 'ou=People,dc=your,dc=domain', - 'posix_group' => 'false' + end + + let(:minimal_ldap_auth_hash) do + { + 'ldap' => { + 'enable' => 'true', + 'url' => ['ldap://server1', 'ldap://server2'], + 'search' => 'ou=People,dc=your,dc=domain', + 'posix_group' => 'false' + } } - }} + end context 'with valid input' do it 'generates apache settings for enabled file auth method' do @@ -135,40 +141,39 @@ end context 'with invalid input' do - it 'fails when unsupported auth method is requested' do - input = {'dbm'=> {'enable' => true, 'user_file' => '/some/file'}} - is_expected.to run.with_params(input).and_raise_error(/'dbm' not yet supported/) + it 'fails when unsupported auth method is requested' do + input = { 'dbm' => { 'enable' => true, 'user_file' => '/some/file' } } + is_expected.to run.with_params(input).and_raise_error(%r{'dbm' not yet supported}) end it 'fails when url option for ldap auth method is not present' do input = minimal_ldap_auth_hash.dup input['ldap'].delete('url') - is_expected.to run.with_params(input).and_raise_error(/missing option\(s\) 'url'/) + is_expected.to run.with_params(input).and_raise_error(%r{missing option\(s\) 'url'}) end it 'fails when search option for ldap auth method is not present' do input = minimal_ldap_auth_hash.dup input['ldap'].delete('search') - is_expected.to run.with_params(input).and_raise_error(/missing option\(s\) 'search'/) + is_expected.to run.with_params(input).and_raise_error(%r{missing option\(s\) 'search'}) end it 'fails when posix_group option for ldap auth method is not present' do input = minimal_ldap_auth_hash.dup input['ldap'].delete('posix_group') - is_expected.to run.with_params(input).and_raise_error(/missing option\(s\) 'posix_group'/) + is_expected.to run.with_params(input).and_raise_error(%r{missing option\(s\) 'posix_group'}) end it 'fails when security method for ldap auth method is invalid' do input = full_ldap_auth_hash.dup input['ldap']['security'] = 'OOPS' - is_expected.to run.with_params(input).and_raise_error(/Error, 'security'.* Got: 'OOPS'/) + is_expected.to run.with_params(input).and_raise_error(%r{Error, 'security'.* Got: 'OOPS'}) end it 'fails when not all required options for file auth method are present' do input = file_auth_hash.dup input['file'].delete('user_file') - is_expected.to run.with_params(input).and_raise_error(/missing option\(s\) 'user_file'/) + is_expected.to run.with_params(input).and_raise_error(%r{missing option\(s\) 'user_file'}) end end end - diff --git a/spec/functions/simp_apache/limits_spec.rb b/spec/functions/simp_apache/limits_spec.rb index 952a7a8..bcd9414 100644 --- a/spec/functions/simp_apache/limits_spec.rb +++ b/spec/functions/simp_apache/limits_spec.rb @@ -1,23 +1,25 @@ require 'spec_helper' describe 'simp_apache::limits' do - let(:limits_hash) {{ - 'defaults' => [ 'GET', 'POST', 'PUT' ], - 'hosts' => { - '1.2.3.4' => 'defaults', - '3.4.5.6' => ['GET', 'POST'], - '10.1.2.0/24' => 'defaults' - }, - 'users' => { - 'bob' => 'defaults', - 'alice' => ['GET','POST','PUT','DELETE'] - }, - 'ldap_groups' => { - 'cn=basic_users,ou=Group,dc=your,dc=domain' => 'defaults', - 'cn=admin_users,ou=Group,dc=your,dc=domain' => ['GET','POST','PUT','DELETE'] + let(:limits_hash) do + { + 'defaults' => [ 'GET', 'POST', 'PUT' ], + 'hosts' => { + '1.2.3.4' => 'defaults', + '3.4.5.6' => ['GET', 'POST'], + '10.1.2.0/24' => 'defaults' + }, + 'users' => { + 'bob' => 'defaults', + 'alice' => ['GET', 'POST', 'PUT', 'DELETE'] + }, + 'ldap_groups' => { + 'cn=basic_users,ou=Group,dc=your,dc=domain' => 'defaults', + 'cn=admin_users,ou=Group,dc=your,dc=domain' => ['GET', 'POST', 'PUT', 'DELETE'] + } } - }} - + end + context 'with valid input' do it 'generates apache limits using defaults' do expected_output = < {'valid-user' => 'GET' } } + valid_user_limits_hash = { 'users' => { 'valid-user' => 'GET' } } expected_output = < Order allow,deny @@ -134,9 +136,9 @@ end context 'with invalid input' do - it 'fails when unsupported limit is requested' do - input = {'oops'=> {'user1' => 'defautls'}} - is_expected.to run.with_params(input).and_raise_error(/'oops' not yet supported/) + it 'fails when unsupported limit is requested' do + input = { 'oops' => { 'user1' => 'defautls' } } + is_expected.to run.with_params(input).and_raise_error(%r{'oops' not yet supported}) end end end diff --git a/spec/functions/simp_apache/munge_httpd_networks_spec.rb b/spec/functions/simp_apache/munge_httpd_networks_spec.rb index 9c1eece..a1048f0 100644 --- a/spec/functions/simp_apache/munge_httpd_networks_spec.rb +++ b/spec/functions/simp_apache/munge_httpd_networks_spec.rb @@ -1,7 +1,6 @@ require 'spec_helper' describe 'simp_apache::munge_httpd_networks' do - context 'with valid input' do it 'transforms IPv4 networks to apache settings format' do input = ['0.0.0.0', '0.0.0.0/0', ' 1.2.3.4 ', '1.2.3.0/24', '1.2.0.0/255.255.0.0'] @@ -18,15 +17,15 @@ end context 'with invalid input' do - # FIXME simplib net2cidr needs to be fixed - pending 'fails when transformation of an invalid IPv4 network is requested' do + # FIXME: simplib net2cidr needs to be fixed + pending 'fails when transformation of an invalid IPv4 network is requested' do input = ['1.2.3.4/34', '1.2.3..'] - is_expected.to run.with_params(input).and_raise_error(/is not a valid/) + is_expected.to run.with_params(input).and_raise_error(%r{is not a valid}) end - it 'fails when transformation of an invalid IPv4 network is requested' do + it 'fails when transformation of an invalid IPv4 network is requested' do input = ['1.2.3.4/255.'] - is_expected.to run.with_params(input).and_raise_error(/is not a valid/) + is_expected.to run.with_params(input).and_raise_error(%r{is not a valid}) end pending 'fails when transformation of an invalid IPV6 network is requested' diff --git a/spec/spec_helper.rb b/spec/spec_helper.rb index ef4fe64..acc4013 100644 --- a/spec/spec_helper.rb +++ b/spec/spec_helper.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true + # # ------------------------------------------------------------------------------ # NOTICE: **This file is maintained with puppetsync** @@ -90,7 +91,7 @@ def set_hieradata(hieradata) # If nothing else... c.default_facts = { production: { - #:fqdn => 'production.rspec.test.localdomain', + # :fqdn => 'production.rspec.test.localdomain', path: '/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin', concat_basedir: '/tmp' } @@ -150,9 +151,9 @@ def set_hieradata(hieradata) # sanitize hieradata if defined?(hieradata) - set_hieradata(hieradata.gsub(':', '_')) + set_hieradata(hieradata.tr(':', '_')) elsif defined?(class_name) - set_hieradata(class_name.gsub(':', '_')) + set_hieradata(class_name.tr(':', '_')) end end @@ -164,9 +165,7 @@ def set_hieradata(hieradata) end Dir.glob("#{RSpec.configuration.module_path}/*").each do |dir| - begin - Pathname.new(dir).realpath - rescue StandardError - raise "ERROR: The module '#{dir}' is not installed. Tests cannot continue." - end + Pathname.new(dir).realpath +rescue StandardError + raise "ERROR: The module '#{dir}' is not installed. Tests cannot continue." end diff --git a/spec/spec_helper_acceptance.rb b/spec/spec_helper_acceptance.rb index 8708db2..3ce063d 100644 --- a/spec/spec_helper_acceptance.rb +++ b/spec/spec_helper_acceptance.rb @@ -15,7 +15,6 @@ end end - RSpec.configure do |c| # ensure that environment OS is ready on each host fix_errata_on hosts @@ -29,21 +28,17 @@ # Configure all nodes in nodeset c.before :suite do - begin - # Install modules and dependencies from spec/fixtures/modules - copy_fixture_modules_to( hosts ) + # Install modules and dependencies from spec/fixtures/modules + copy_fixture_modules_to(hosts) - # Generate and install PKI certificates on each SUT - Dir.mktmpdir do |cert_dir| - run_fake_pki_ca_on( default, hosts, cert_dir ) - hosts.each{ |sut| copy_pki_to( sut, cert_dir, '/etc/pki/simp-testing' )} - end - rescue StandardError, ScriptError => e - if ENV['PRY'] - require 'pry'; binding.pry - else - raise e - end + # Generate and install PKI certificates on each SUT + Dir.mktmpdir do |cert_dir| + run_fake_pki_ca_on(default, hosts, cert_dir) + hosts.each { |sut| copy_pki_to(sut, cert_dir, '/etc/pki/simp-testing') } end + rescue StandardError, ScriptError => e + raise e unless ENV['PRY'] + require 'pry' + binding.pry end end diff --git a/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb b/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb index 82f7429..6f6d453 100644 --- a/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb +++ b/spec/unit/compliance_engine/compliance_engine_enforce_spec.rb @@ -7,10 +7,9 @@ # This is the class that needs to be added to the catalog last to make the # reporting work. describe 'compliance_markup', type: :class do - compliance_profiles = [ 'disa_stig', - 'nist_800_53:rev4' + 'nist_800_53:rev4', ] # A list of classes that we expect to be included for compliance @@ -18,53 +17,53 @@ # This needs to be well defined since we can also manipulate defined type # defaults expected_classes = [ - 'simp_apache' + 'simp_apache', ] allowed_failures = { 'documented_missing_parameters' => [ - ] + expected_classes.map{|c| Regexp.new("^(?!#{c}(::.*)?)")}, + ] + expected_classes.map { |c| Regexp.new("^(?!#{c}(::.*)?)") }, 'documented_missing_resources' => [ - ] + expected_classes.map{|c| Regexp.new("^(?!#{c}(::.*)?)")} + ] + expected_classes.map { |c| Regexp.new("^(?!#{c}(::.*)?)") } } on_supported_os.each do |os, os_facts| context "on #{os}" do compliance_profiles.each do |target_profile| context "with compliance profile '#{target_profile}'" do - let(:facts){ + let(:facts) do os_facts.merge({ - :target_compliance_profile => target_profile - }) - } - - let(:pre_condition) {%( - #{expected_classes.map{|c| %{include #{c}}}.join("\n")} - )} - - let(:hieradata){ 'compliance-engine' } - - it { is_expected.to compile } - - let(:compliance_report) { - @compliance_report ||= JSON.load( - catalogue.resource("File[#{facts[:puppet_vardir]}/compliance_report.json]")[:content] + target_compliance_profile: target_profile + }) + end + let(:compliance_report) do + @compliance_report ||= JSON.parse( + catalogue.resource("File[#{facts[:puppet_vardir]}/compliance_report.json]")[:content], ) @compliance_report - } - - let(:compliance_profile_data) { + end + let(:compliance_profile_data) do @compliance_profile_data ||= compliance_report['compliance_profiles'][target_profile] @compliance_profile_data - } + end + + let(:pre_condition) do + %( + #{expected_classes.map { |c| %(include #{c}) }.join("\n")} + ) + end + + let(:hieradata) { 'compliance-engine' } + + it { is_expected.to compile } - it 'should have a compliance profile report' do - expect(compliance_profile_data).to_not be_nil + it 'has a compliance profile report' do + expect(compliance_profile_data).not_to be_nil end - it 'should have a 100% compliant report' do + it 'has a 100% compliant report' do expect(compliance_profile_data['summary']['percent_compliant']).to eq(100) end @@ -84,29 +83,29 @@ # classes included, this report may be useless and is disabled by # default. # - 'documented_missing_resources' + 'documented_missing_resources', ] report_validators.each do |report_section| - it "should have no issues with the '#{report_section}' report" do + it "has no issues with the '#{report_section}' report" do if compliance_profile_data[report_section] # This just gets us a good print out of what went wrong - compliance_profile_data[report_section].delete_if{ |item| - rm = false - - Array(allowed_failures[report_section]).each do |allowed| - if allowed.is_a?(Regexp) - if allowed.match?(item) - rm = true - break - end - else - rm = (allowed == item) + compliance_profile_data[report_section].delete_if do |item| + rm = false + + Array(allowed_failures[report_section]).each do |allowed| + if allowed.is_a?(Regexp) + if allowed.match?(item) + rm = true + break end + else + rm = (allowed == item) end + end - rm - } + rm + end expect(compliance_profile_data[report_section]).to eq([]) end diff --git a/spec/unit/puppet/provider/htaccess/htaccess_spec.rb b/spec/unit/puppet/provider/htaccess/htaccess_spec.rb index 798efc5..d34c8d4 100644 --- a/spec/unit/puppet/provider/htaccess/htaccess_spec.rb +++ b/spec/unit/puppet/provider/htaccess/htaccess_spec.rb @@ -17,21 +17,21 @@ let(:user1) { 'user1' } let :resource do Puppet::Type::Htaccess.new( - {:name => "#{@htaccess_file}:#{user1}", :password => "#{user1}'s password"} + { name: "#{@htaccess_file}:#{user1}", password: "#{user1}'s password" }, ) end - context "when creating htaccess file" do + context 'when creating htaccess file' do let :provider do provider_class.new(resource) end - it 'should not exist' do - expect { provider.exists? }.to raise_error(/No such file or directory .*#{@htaccess_file}/) + it 'does not exist' do + expect { provider.exists? }.to raise_error(%r{No such file or directory .*#{@htaccess_file}}) expect(provider.passwd_retrieve).to be_nil end - it 'should create htaccess file with banner and one user entry' do + it 'creates htaccess file with banner and one user entry' do provider.create expected = < "#{@htaccess_file}:#{user1}", :password => "{SHA}CLub7iwpjkqz0enKLoRcbiDtUCo="} + { name: "#{@htaccess_file}:#{user1}", password: '{SHA}CLub7iwpjkqz0enKLoRcbiDtUCo=' }, ) end @@ -99,7 +99,7 @@ provider_class.new(resource2) end - it 'should add user entry using pre-hashed password to htaccess file' do + it 'adds user entry using pre-hashed password to htaccess file' do provider.create expected = <: for the name param" do + it 'requires : for the name param' do expect { htaccess_type.new( - :name => '/fully/qualified/path:username', - :password => 'badpassword' + name: '/fully/qualified/path:username', + password: 'badpassword', ) - }.to_not raise_error + }.not_to raise_error expect { htaccess_type.new( - :name => 'onefield', - :password => 'badpassword' + name: 'onefield', + password: 'badpassword', ) }.to raise_error(%r{name is missing either the path or the username. Name format must be 'path:username'}) expect { htaccess_type.new( - :name => ':empty_first_field', - :password => 'badpassword' + name: ':empty_first_field', + password: 'badpassword', ) }.to raise_error(%r{name is missing either the path or the username. Name format must be 'path:username'}) expect { htaccess_type.new( - :name => 'empty_second_field:', - :password => 'badpassword' + name: 'empty_second_field:', + password: 'badpassword', ) }.to raise_error(%r{name is missing either the path or the username. Name format must be 'path:username'}) expect { htaccess_type.new( - :name => 'not/fully/qualified/path:username', - :password => 'badpassword' + name: 'not/fully/qualified/path:username', + password: 'badpassword', ) }.to raise_error(%r{File paths must be fully qualified, not not/fully/qualified/path}) end - it "should require the password param" do - expect { htaccess_type.new( :name => '/fully/qualified/path:username' ) }.to raise_error(%r{You must specify password.}) + it 'requires the password param' do + expect { htaccess_type.new(name: '/fully/qualified/path:username') }.to raise_error(%r{You must specify password.}) end - end