How to use rule_id method of Inspec Package

Best Inspec_ruby code snippet using Inspec.rule_id

rule.rb

Source:rule.rb Github

copy

Full Screen

...21 accepts_nested_attributes_for :additional_answers22 has_and_belongs_to_many :satisfied_by,23 class_name: 'Rule',24 join_table: :rule_satisfactions,25 association_foreign_key: :satisfied_by_rule_id26 has_and_belongs_to_many :satisfies,27 class_name: 'Rule',28 join_table: :rule_satisfactions,29 foreign_key: :satisfied_by_rule_id,30 association_foreign_key: :rule_id31 before_validation :set_rule_id32 before_save :apply_audit_comment33 before_save :update_inspec_code34 before_destroy :prevent_destroy_if_under_review_or_locked35 after_destroy :update_component_rules_count36 after_save :update_component_rules_count37 after_save :update_satisfied_by_inspec_code38 validates_with RuleSatisfactionValidator39 validate :cannot_be_locked_and_under_review40 validate :review_fields_cannot_change_with_other_fields, on: :update41 validates :rule_id, allow_blank: false, presence: true, uniqueness: { scope: :component_id }42 default_scope { where(deleted_at: nil) }43 def self.from_mapping(rule_mapping, component_id, idx, srg_rules)44 rule = super(self, rule_mapping)45 rule.audits.build(Audited.audit_class.create_initial_rule_audit_from_mapping(component_id))46 rule.component_id = component_id47 rule.srg_rule_id = srg_rules[rule.rule_id]48 # This is what is appended to the component prefix in the UI49 rule.rule_id = idx&.to_s&.rjust(6, '0')50 rule51 end52 # Overrides for satisfied controls53 def status54 satisfied_by.size.positive? ? 'Applicable - Configurable' : self[:status]55 end56 def status=(value)57 super(value) unless satisfied_by.size.positive?58 end59 ##60 # Override `as_json` to include parent SRG information61 #62 def as_json(options = {})63 result = super(options)64 unless options[:skip_merge].eql?(true)65 result = result.merge(66 {67 reviews: reviews.as_json.map { |c| c.except('user_id', 'rule_id', 'updated_at') },68 srg_rule_attributes: srg_rule.as_json.except('id', 'locked', 'created_at', 'updated_at', 'status',69 'status_justification', 'artifact_description',70 'vendor_comments', 'review_requestor_id',71 'component_id', 'changes_requested', 'srg_rule_id',72 'security_requirements_guide_id'),73 satisfies: satisfies.as_json(only: %i[id rule_id], skip_merge: true),74 satisfied_by: satisfied_by.as_json(only: %i[id fixtext rule_id], skip_merge: true),75 additional_answers_attributes: additional_answers.as_json.map do |c|76 c.except('rule_id', 'created_at', 'updated_at')77 end78 }79 )80 end81 result82 end83 ##84 # Revert a specific field on a rule from an audit85 #86 # Parameters:87 # rule (Rule) - A Rule object to revert a change on88 # audit_id (integer) - A specific ID for an audited record89 # field (string) - A specific field to revert from the audit record90 #91 def self.revert(rule, audit_id, fields, audit_comment)92 audit = rule.own_and_associated_audits.find(audit_id)93 # nil check for audit94 raise(RuleRevertError, 'Could not locate history for this control.') if audit.nil?95 if audit.action == 'update'96 record = audit.auditable97 # nil check for record98 raise(RuleRevertError, 'Could not locate record for this history.') if record.nil?99 fields.each do |field|100 # The only field we can revert on AdditionalAnswers is answer101 field = 'answer' if audit.auditable_type.eql?('AdditionalAnswer')102 unless audit.audited_changes.include?(field)103 raise(RuleRevertError, "Field to revert (#{field.humanize}) does not exist in this history.")104 end105 # The audited change can either be an array `[prev_val, new_val]`106 # or just the `val`107 value = if audit.audited_changes[field].is_a?(Array)108 audit.audited_changes[field][0]109 else110 audit.audited_changes[field]111 end112 # Special case for AdditionalAnswer since it stores in the 'answer' field always113 if audit.auditable_type.eql?('AdditionalAnswer')114 record.answer = value115 else116 record[field] = value117 end118 end119 record.audit_comment = audit_comment if record.changed?120 record.save121 return122 end123 raise(RuleRevertError, 'Cannot revert this history.') unless audit.action == 'destroy'124 auditable_type = case audit.auditable_type125 when 'RuleDescription'126 RuleDescription127 when 'DisaRuleDescription'128 DisaRuleDescription129 when 'Check'130 Check131 else132 raise(RuleRevertError, 'Cannot revert this history type.')133 end134 begin135 auditable_type.create!(audit.audited_changes.merge({ rule_id: rule.id, audit_comment: audit_comment }))136 rescue ActiveRecord::RecordInvalid => e137 raise(RuleRevertError, "Encountered error while reverting this history. #{e.message}")138 end139 end140 def csv_attributes141 [142 nist_control_family,143 ident,144 version,145 "#{component.prefix}-#{rule_id}",146 SEVERITIES_MAP[rule_severity] || rule_severity,147 srg_rule.title, # original srg title148 title,149 srg_rule.disa_rule_descriptions.first.vuln_discussion, # original srg vuln discussion150 disa_rule_descriptions.first.vuln_discussion,151 status,152 srg_rule.checks.first.content, # original SRG check content153 export_checktext,154 srg_rule.fixtext, # original SRG fix text155 export_fixtext,156 status_justification,157 disa_rule_descriptions.first.mitigations,158 artifact_description,159 vendor_comments_with_satisfactions160 ]161 end162 def displayed_name163 "#{component[:prefix]}-#{rule_id}"164 end165 def update_inspec_code166 desc = disa_rule_descriptions.first167 control = Inspec::Object::Control.new168 control.add_header('# -*- encoding : utf-8 -*-')169 control.id = "#{component[:prefix]}-#{rule_id}"170 control.title = title171 control.descriptions[:default] = desc[:vuln_discussion] if desc.present?172 control.descriptions[:rationale] = ''173 control.descriptions[:check] = checks.first&.content174 control.descriptions[:fix] = fixtext175 control.impact = RuleConstants::IMPACTS_MAP[rule_severity]176 control.add_tag(Inspec::Object::Tag.new('severity', rule_severity))177 control.add_tag(Inspec::Object::Tag.new('gtitle', version))178 control.add_tag(Inspec::Object::Tag.new('satisfies', satisfies.pluck(:version).sort)) if satisfies.present?179 control.add_tag(Inspec::Object::Tag.new('gid', nil))180 control.add_tag(Inspec::Object::Tag.new('rid', nil))181 control.add_tag(Inspec::Object::Tag.new('stig_id', "#{component[:prefix]}-#{rule_id}"))182 control.add_tag(Inspec::Object::Tag.new('cci', ([ident] + satisfies.pluck(:ident)).uniq.sort)) if ident.present?183 control.add_tag(Inspec::Object::Tag.new('nist', ([nist_control_family] +184 satisfies.map(&:nist_control_family)).uniq.sort))185 if desc.present?186 %i[false_negatives false_positives documentable mitigations severity_override_guidance potential_impacts187 third_party_tools mitigation_control responsibility ia_controls].each do |field|188 control.add_tag(Inspec::Object::Tag.new(field.to_s, desc[field])) if desc[field].present?189 end190 end191 control.add_post_body(inspec_control_body) if inspec_control_body.present?192 self.inspec_control_file = control.to_ruby193 end194 def update_satisfied_by_inspec_code195 sb = satisfied_by.first196 return if sb.nil?197 # trigger update_inspec_code callback198 sb.save199 end200 def basic_fields201 {202 rule_id: rule_id,203 title: title,204 vuln_discussion: disa_rule_descriptions.first&.vuln_discussion,205 check: export_checktext,206 fix: export_fixtext207 }208 end209 private210 def export_fixtext211 satisfied_by.size.positive? ? satisfied_by.first.fixtext : fixtext212 end213 def export_checktext214 satisfied_by.size.positive? ? satisfied_by.first.checks.first&.content : checks.first&.content215 end216 def vendor_comments_with_satisfactions217 comments = []218 comments << vendor_comments if vendor_comments.present?219 if satisfied_by.present?220 comments << "Satisfied By: #{satisfied_by.map { |r| "#{component.prefix}-#{r.rule_id}" }.join(', ')}."221 end222 if satisfies.present?223 comments << "Satisfies: #{satisfies.map { |r| "#{component.prefix}-#{r.rule_id}" }.join(', ')}."224 end225 comments.join('. ')226 end227 def cannot_be_locked_and_under_review228 return unless locked && review_requestor_id.present?229 errors.add(:base, 'Control cannot be under review and locked at the same time.')230 end231 ##232 # Check to ensure that "review fields" are not changed233 # in the same `.save` action as any "non-review fields"234 def review_fields_cannot_change_with_other_fields235 review_fields = Set.new(%w[review_requestor_id locked changes_requested])236 ignored_fields = %w[updated_at created_at]237 changed_filtered = changed.reject { |f| ignored_fields.include? f }238 any_review_fields_changed = changed_filtered.any? { |field| review_fields.include? field }239 any_non_review_fields_changed = changed_filtered.any? { |field| review_fields.exclude? field }240 # Break early if review and non-review fields have not changed together241 return unless any_review_fields_changed && any_non_review_fields_changed242 errors.add(:base, 'Cannot update review-related attributes with other non-review-related attributes')243 end244 def set_rule_id245 self.rule_id = (component.largest_rule_id + 1).to_s.rjust(6, '0') if rule_id.blank?246 end247 ##248 # Rules should never be deleted if they are under review or locked249 # This checks *_was to cover the case where an attrubute was changed before attempting to destroy250 def prevent_destroy_if_under_review_or_locked251 # Allow deletion if it is due to the parent being deleted252 return if destroyed_by_association.present?253 # Abort if under review and trying to delete254 if review_requestor_id_was.present?255 errors.add(:base, 'Control is under review and cannot be destroyed')256 throw(:abort)257 end258 # Abort if locked and trying to delete259 return unless locked_was...

Full Screen

Full Screen

components_controller.rb

Source:components_controller.rb Github

copy

Full Screen

...142 'components.release, projects.name AS project_name')143 .map(&:attributes)144 end145 def compare146 base = Component.find_by(id: params[:id]).rules.pluck(:rule_id, :inspec_control_file).to_h147 diff = Component.find_by(id: params[:diff_id]).rules.pluck(:rule_id, :inspec_control_file).to_h148 render json: base.keys.union(diff.keys).sort.index_with { |rule_id|149 { base: base[rule_id], diff: diff[rule_id], changed: base[rule_id] != diff[rule_id] }150 }151 end152 def history153 history = []154 components = Project.find_by(id: params[:project_id]).components.where(name: params[:name])155 .where.not(version: nil).where.not(release: nil).order(:version, :release)156 components.each_with_index do |component, idx|157 # nothing to compare first component to158 unless idx.zero?159 prev_component = components[idx - 1]160 base = prev_component.rules.eager_load(:satisfied_by, :checks, :disa_rule_descriptions)161 .map(&:basic_fields).index_by { |r| r[:rule_id] }162 diff = component.rules.eager_load(:satisfied_by, :checks, :disa_rule_descriptions)163 .map(&:basic_fields).index_by { |r| r[:rule_id] }164 changes = {}165 # added166 (diff.keys - base.keys).each do |rule_id|167 changes[rule_id] = { change: 'added', diff: diff[rule_id] }168 end169 # removed170 (base.keys - diff.keys).each do |rule_id|171 changes[rule_id] = { change: 'removed', base: base[rule_id] }172 end173 # updated174 base.keys.intersection(diff.keys)175 .filter { |rule_id| base[rule_id] != diff[rule_id] }176 .each do |rule_id|177 changes[rule_id] = { change: 'updated', base: base[rule_id], diff: diff[rule_id] }178 end179 history << {180 baseComponent: prev_component,181 diffComponent: component,182 changes: changes183 }184 end185 history << { component: component }186 end187 render json: history188 end189 def find190 find = params.require(:find)191 component_id = params.require(:id)192 rules = Component.find_by(id: component_id).rules193 checks = Check.where(base_rule: rules).where('content like ?', "%#{find.downcase}%")194 descriptions = DisaRuleDescription.where(base_rule: rules).where('vuln_discussion like ?', "%#{find.downcase}%")195 rules = rules.where('title like ?', "%#{find.downcase}%").or(196 rules.where('fixtext LIKE ?', "%#{find.downcase}%").or(197 rules.where('vendor_comments LIKE ?', "%#{find.downcase}%").or(198 rules.where(id: checks.pluck(:base_rule_id) | descriptions.pluck(:base_rule_id))199 )200 )201 ).order(:rule_id)202 render json: rules203 end204 private205 def create_or_duplicate206 if component_create_params[:duplicate] || component_create_params[:copy_component]207 Component.find(component_create_params[:id])208 .duplicate(new_name: component_create_params[:name],209 new_prefix: component_create_params[:prefix],210 new_version: component_create_params[:version],211 new_release: component_create_params[:release],212 new_title: component_create_params[:title],213 new_description: component_create_params[:description],214 new_project_id: component_create_params[:project_id],215 new_srg_id: component_create_params[:security_requirements_guide_id])...

Full Screen

Full Screen

runner.rb

Source:runner.rb Github

copy

Full Screen

...90 # evaluate the test content91 tests = [tests] unless tests.is_a? Array92 tests.each { |t| add_test_to_context(t, ctx) }93 # process the resulting rules94 filter_controls(ctx.rules, options[:controls]).each do |rule_id, rule|95 register_rule(rule_id, rule)96 end97 end98 def_delegator :@test_collector, :run99 def_delegator :@test_collector, :report100 private101 def add_test_to_context(test, ctx)102 content = test[:content]103 return if content.nil? || content.empty?104 ctx.load(content, test[:ref], test[:line])105 end106 def filter_controls(controls_map, include_list)107 return controls_map if include_list.nil? || include_list.empty?108 controls_map.select do |_, c|109 id = ::Inspec::Rule.rule_id(c)110 include_list.include?(id)111 end112 end113 def block_source_info(block)114 return {} if block.nil? || !block.respond_to?(:source_location)115 opts = {}116 file_path, line = block.source_location117 opts['file_path'] = file_path118 opts['line_number'] = line119 opts120 end121 def get_check_example(method_name, arg, block)122 opts = block_source_info(block)123 if !arg.empty? &&124 arg[0].respond_to?(:resource_skipped) &&125 !arg[0].resource_skipped.nil?126 return @test_collector.example_group(*arg, opts) do127 it arg[0].resource_skipped128 end129 else130 # add the resource131 case method_name132 when 'describe'133 return @test_collector.example_group(*arg, opts, &block)134 when 'expect'135 return block.example_group136 when 'describe.one'137 tests = arg.map do |x|138 @test_collector.example_group(x[1][0], block_source_info(x[2]), &x[2])139 end140 return nil if tests.empty?141 ok_tests = tests.find_all(&:run)142 # return all tests if none succeeds; we will just report full failure143 return tests if ok_tests.empty?144 # otherwise return all working tests145 return ok_tests146 else147 fail "A rule was registered with #{method_name.inspect}, "\148 "which isn't understood and cannot be processed."149 end150 end151 nil152 end153 def register_rule(rule_id, rule)154 @rules[rule_id] = rule155 checks = ::Inspec::Rule.prepare_checks(rule)156 examples = checks.map do |m, a, b|157 get_check_example(m, a, b)158 end.flatten.compact159 examples.each do |example|160 # TODO: Remove this!! It is very dangerous to do this here.161 # The goal of this is to make the audit DSL available to all162 # describe blocks. Right now, these blocks are executed outside163 # the scope of this run, thus not gaining ony of the DSL pieces.164 # To circumvent this, the full DSL is attached to the example's165 # scope.166 dsl = Inspec::Resource.create_dsl(backend)167 example.send(:include, dsl)168 @test_collector.add_test(example, rule)...

Full Screen

Full Screen

rule_id

Using AI Code Generation

copy

Full Screen

1Inspec::Rule.send(:include, InspecPlugins::RuleID::Rule)2Inspec::Resources::Send.send(:include, InspecPlugins::RuleID::Send)3Inspec::Resources::SendFile.send(:include, InspecPlugins::RuleID::SendFile)4Inspec::Resources::SendDirectory.send(:include, InspecPlugins::RuleID::SendDirectory)5Inspec::Resources::SendCommand.send(:include, InspecPlugins::RuleID::SendCommand)6class InspecPlugins::RuleID::Plugin < Inspec.plugin(2)

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Inspec_ruby automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful