Skip to content

Commit

Permalink
Fix rubocop with --auto-correct-all and --regenerate-todo
Browse files Browse the repository at this point in the history
  • Loading branch information
kamils-iRonin committed Feb 1, 2024
1 parent d3e5e27 commit 940b61c
Show file tree
Hide file tree
Showing 17 changed files with 62 additions and 46 deletions.
2 changes: 2 additions & 0 deletions .rubocop.yml
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
inherit_from: .rubocop_todo.yml

AllCops:
TargetRubyVersion: 2.5
TargetRailsVersion: 6.0
Expand Down
22 changes: 22 additions & 0 deletions .rubocop_todo.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
# This configuration was generated by
# `rubocop --auto-gen-config`
# on 2024-02-01 12:37:24 UTC using RuboCop version 1.60.2.
# The point is for the user to remove these configuration records
# one by one as the offenses are removed from the code base.
# Note that changes in the inspected code, or installation of new
# versions of RuboCop, may require this file to be generated again.

# Offense count: 1
# Configuration parameters: Severity, Include.
# Include: **/*.gemspec
Gemspec/RequiredRubyVersion:
Exclude:
- 'foreman_vault.gemspec'

# Offense count: 1
# Configuration parameters: ExpectMatchingDefinition, CheckDefinitionPathHierarchy, CheckDefinitionPathHierarchyRoots, Regex, IgnoreExecutableScripts, AllowedAcronyms.
# CheckDefinitionPathHierarchyRoots: lib, spec, test, src
# AllowedAcronyms: CLI, DSL, ACL, API, ASCII, CPU, CSS, DNS, EOF, GUID, HTML, HTTP, HTTPS, ID, IP, JSON, LHS, QPS, RAM, RHS, RPC, SLA, SMTP, SQL, SSH, TCP, TLS, TTL, UDP, UI, UID, UUID, URI, URL, UTF8, VM, XML, XMPP, XSRF, XSS
Naming/FileName:
Exclude:
- 'db/seeds.d/103-provisioning_templates.rb'
6 changes: 4 additions & 2 deletions Rakefile
100644 → 100755
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
#!/usr/bin/env rake
# frozen_string_literal: true

begin
require 'bundler/setup'
rescue LoadError
Expand All @@ -20,7 +22,7 @@ RDoc::Task.new(:rdoc) do |rdoc|
rdoc.rdoc_files.include('lib/**/*.rb')
end

APP_RAKEFILE = File.expand_path('../test/dummy/Rakefile', __FILE__)
APP_RAKEFILE = File.expand_path('test/dummy/Rakefile', __dir__)

Bundler::GemHelper.install_tasks

Expand All @@ -38,7 +40,7 @@ task default: :test
begin
require 'rubocop/rake_task'
RuboCop::RakeTask.new
rescue => _
rescue StandardError => _e
puts 'Rubocop not loaded.'
end

Expand Down
2 changes: 1 addition & 1 deletion app/controllers/api/v2/vault_connections_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class VaultConnectionsController < V2::BaseController
include Api::Version2
include ForemanVault::Controller::Parameters::VaultConnection

before_action :find_resource, only: [:show, :update, :destroy]
before_action :find_resource, only: %i[show update destroy]

api :GET, '/vault_connections/', N_('List VaultConnections')
param_group :search_and_pagination, ::Api::V2::BaseController
Expand Down
2 changes: 1 addition & 1 deletion app/controllers/vault_connections_controller.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
class VaultConnectionsController < ::ApplicationController
include ForemanVault::Controller::Parameters::VaultConnection

before_action :find_resource, only: [:edit, :update, :destroy]
before_action :find_resource, only: %i[edit update destroy]

def index
@vault_connections = resource_base.all
Expand Down
1 change: 1 addition & 0 deletions app/lib/foreman_vault/macros.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ def vault_secret(vault_connection_name, secret_path)
def vault_issue_certificate(vault_connection_name, secret_path, *options)
vault = VaultConnection.find_by!(name: vault_connection_name)
raise VaultError.new(N_('Invalid token for %s'), vault.name) if vault.with_token? && !vault.token_valid?

vault.issue_certificate(secret_path, *options)
rescue ActiveRecord::RecordNotFound => e
raise VaultError, e.message
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ def queue_vault_destroy
action: [self, :del_vault])
end

# rubocop:disable Metrics/AbcSize
def set_vault
logger.info "Pushing #{name} data to Vault"

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ module ForemanVault
module ProvisioningTemplateExtensions
extend ActiveSupport::Concern

# rubocop:disable Metrics/ParameterLists
def render(renderer: Foreman::Renderer, host: nil, params: {}, variables: {}, mode: Foreman::Renderer::REAL_MODE, template_input_values: {}, source_klass: nil)
source_klass = Foreman::Renderer::Source::Database if template_kind == TemplateKind.find_by(name: 'VaultPolicy')

Expand Down
6 changes: 2 additions & 4 deletions app/models/vault_connection.rb
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ class VaultConnection < ApplicationRecord
validates :name, presence: true, uniqueness: true
validates :name, inclusion: { in: ->(i) { [i.name_was] }, message: _('cannot be changed after creation') }, on: :update
validates :url, presence: true
validates :url, format: URI.regexp(['http', 'https'])
validates :url, format: URI::DEFAULT_PARSER.make_regexp(%w[http https])

validates :token, presence: true, if: -> { role_id.nil? || secret_id.nil? }
validates :token, inclusion: { in: [nil], message: _('AppRole or token must be blank') }, unless: -> { role_id.nil? || secret_id.nil? }
Expand Down Expand Up @@ -48,9 +48,7 @@ def renew_token!
client.renew_token
save!
rescue StandardError => e
# rubocop:disable Rails/SkipsModelValidations
update_column(:vault_error, e.message)
# rubocop:enable Rails/SkipsModelValidations
end

def perform_renew_token
Expand All @@ -76,7 +74,7 @@ def update_expire_time
end

def normalize_blank_values
attributes.each do |column, _value|
attributes.each_key do |column|
self[column].present? || self[column] = nil
end
end
Expand Down
1 change: 1 addition & 0 deletions app/services/foreman_vault/vault_auth_method.rb
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ def delete
private

attr_reader :host

delegate :vault_policy, :vault_connection, :fqdn, to: :host
delegate :name, to: :vault_policy, prefix: true
delegate :set_certificate, :delete_certificate, to: :vault_connection
Expand Down
1 change: 1 addition & 0 deletions app/services/foreman_vault/vault_client.rb
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ def fetch_secret(secret_path)
def issue_certificate(secret_path, *options)
response = client.logical.write(secret_path, *options)
raise NoDataError.new(N_('Could not issue certificate: %s'), secret_path) unless response

response.data
end

Expand Down
1 change: 1 addition & 0 deletions app/services/foreman_vault/vault_policy.rb
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,7 @@ def delete
private

attr_reader :host

delegate :params, :render_template, :vault_connection, to: :host
delegate :policy, :policies, :put_policy, :delete_policy, to: :vault_connection

Expand Down
2 changes: 1 addition & 1 deletion config/routes.rb
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

namespace :api, defaults: { format: 'json' } do
scope '(:apiv)', module: :v2, defaults: { apiv: 'v2' }, apiv: /v1|v2/, constraints: ApiConstraints.new(version: 2, default: true) do
resources :vault_connections, only: [:index, :show, :create, :update, :destroy]
resources :vault_connections, only: %i[index show create update destroy]
end
end
end
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@

class FixVaultSettingsCategoryToDsl < ActiveRecord::Migration[6.0]
def up
# rubocop:disable Rails/SkipsModelValidations
Setting.where(category: 'Setting::Vault').update_all(category: 'Setting') if column_exists?(:settings, :category)
# rubocop:enable Rails/SkipsModelValidations
end
end
22 changes: 10 additions & 12 deletions lib/foreman_vault/engine.rb
Original file line number Diff line number Diff line change
Expand Up @@ -27,11 +27,11 @@ class Engine < ::Rails::Engine

# Add permissions
security_block :foreman_vault do
permission :view_vault_connections, { vault_connections: [:index, :show],
'api/v2/vault_connections': [:index, :show] }, resource_type: 'VaultConnection'
permission :create_vault_connections, { vault_connections: [:new, :create],
permission :view_vault_connections, { vault_connections: %i[index show],
'api/v2/vault_connections': %i[index show] }, resource_type: 'VaultConnection'
permission :create_vault_connections, { vault_connections: %i[new create],
'api/v2/vault_connections': [:create] }, resource_type: 'VaultConnection'
permission :edit_vault_connections, { vault_connections: [:edit, :update],
permission :edit_vault_connections, { vault_connections: %i[edit update],
'api/v2/vault_connections': [:update] }, resource_type: 'VaultConnection'
permission :destroy_vault_connections, { vault_connections: [:destroy],
'api/v2/vault_connections': [:destroy] }, resource_type: 'VaultConnection'
Expand Down Expand Up @@ -69,14 +69,12 @@ class Engine < ::Rails::Engine
end

config.to_prepare do
begin
::Host::Managed.include(ForemanVault::HostExtensions)
::ProvisioningTemplate.include(ForemanVault::ProvisioningTemplateExtensions)
::Foreman::Renderer::Scope::Base.include(ForemanVault::Macros)
::Foreman::Renderer.configure { |c| c.allowed_generic_helpers += [:vault_secret, :vault_issue_certificate] }
rescue StandardError => e
Rails.logger.warn "ForemanVault: skipping engine hook (#{e})"
end
::Host::Managed.include(ForemanVault::HostExtensions)
::ProvisioningTemplate.include(ForemanVault::ProvisioningTemplateExtensions)
::Foreman::Renderer::Scope::Base.include(ForemanVault::Macros)
::Foreman::Renderer.configure { |c| c.allowed_generic_helpers += %i[vault_secret vault_issue_certificate] }
rescue StandardError => e
Rails.logger.warn "ForemanVault: skipping engine hook (#{e})"
end

initializer 'foreman_vault.register_gettext', after: :load_config_initializers do |_app|
Expand Down
34 changes: 15 additions & 19 deletions lib/tasks/foreman_vault_tasks.rake
Original file line number Diff line number Diff line change
Expand Up @@ -3,24 +3,22 @@
require 'rake/testtask'

# Tasks
namespace :foreman_vault do # rubocop:disable Metrics/BlockLength
namespace :foreman_vault do
namespace :auth_methods do
desc 'Push auth methods for all hosts to Vault'
task push: :environment do
User.as_anonymous_admin do
hosts = Host::Managed.where(managed: true)

hosts.each_with_index do |host, index|
begin
result = host.reload.vault_auth_method.save
if result
puts "[#{index + 1}/#{hosts.count}] Auth-Method of \"#{host.name}\" pushed to Vault server \"#{host.vault_connection.url}\""
else
puts "[#{index + 1}/#{hosts.count}] Failed to push \"#{host.name}\": #{result}"
end
rescue StandardError => err
puts "[#{index + 1}/#{hosts.count}] Failed to push \"#{host.name}\": #{err}"
result = host.reload.vault_auth_method.save
if result
puts "[#{index + 1}/#{hosts.count}] Auth-Method of \"#{host.name}\" pushed to Vault server \"#{host.vault_connection.url}\""
else
puts "[#{index + 1}/#{hosts.count}] Failed to push \"#{host.name}\": #{result}"
end
rescue StandardError => e
puts "[#{index + 1}/#{hosts.count}] Failed to push \"#{host.name}\": #{e}"
end
end
end
Expand All @@ -33,16 +31,14 @@ namespace :foreman_vault do # rubocop:disable Metrics/BlockLength
hosts = Host::Managed.where(managed: true)

hosts.each_with_index do |host, index|
begin
result = host.reload.vault_policy.save
if result
puts "[#{index + 1}/#{hosts.count}] Policy of \"#{host.name}\" pushed to Vault server \"#{host.vault_connection.url}\""
else
puts "[#{index + 1}/#{hosts.count}] Failed to push \"#{host.name}\": #{result}"
end
rescue StandardError => err
puts "[#{index + 1}/#{hosts.count}] Failed to push \"#{host.name}\": #{err}"
result = host.reload.vault_policy.save
if result
puts "[#{index + 1}/#{hosts.count}] Policy of \"#{host.name}\" pushed to Vault server \"#{host.vault_connection.url}\""
else
puts "[#{index + 1}/#{hosts.count}] Failed to push \"#{host.name}\": #{result}"
end
rescue StandardError => e
puts "[#{index + 1}/#{hosts.count}] Failed to push \"#{host.name}\": #{e}"
end
end
end
Expand Down
2 changes: 0 additions & 2 deletions test/models/foreman_vault/orchestration/vault_policy_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -115,9 +115,7 @@ class VaultPolicyTest < ActiveSupport::TestCase
let(:new_policy_name) { "#{new_owner}-#{host.name}".parameterize }
let(:put_policy_request) do
url = "#{vault_connection.url}/v1/sys/policy/#{new_policy_name}"
# rubocop:disable Metrics/LineLength
rules = "# allow access to secrets from puppet hosts from <foreman_owner>-<hostname>\npath \"secrets/data/MyOwner/#{host.name}/*\" {\n capabilities = [\"create\", \"read\", \"update\"]\n}\n"
# rubocop:enable Metrics/LineLength
stub_request(:put, url).with(body: JSON.fast_generate(rules: rules)).to_return(status: 200)
end

Expand Down

0 comments on commit 940b61c

Please sign in to comment.