Bump rubocop, apply new cops and fix deprecations

This commit is contained in:
Benjamin Neff 2021-06-30 03:26:46 +02:00
parent be56dea3fa
commit cb138d6458
No known key found for this signature in database
GPG key ID: 971464C3F1A90194
28 changed files with 97 additions and 69 deletions

View file

@ -2,7 +2,7 @@
engines:
rubocop:
enabled: true
channel: rubocop-0-75
channel: rubocop-1-10-0
bundler-audit:
enabled: true
ratings:

View file

@ -2,6 +2,7 @@ require: rubocop-rails
AllCops:
TargetRubyVersion: 2.5
NewCops: enable
Exclude:
- "bin/**/*"
- "test/dummy/bin/**/*"
@ -46,7 +47,7 @@ Style/SymbolArray:
Enabled: true
# Most readable form.
Layout/AlignHash:
Layout/HashAlignment:
EnforcedHashRocketStyle: table
EnforcedColonStyle: table
@ -95,7 +96,7 @@ Style/SignalException:
# Suppressing exceptions can be perfectly fine, and be it to avoid to
# explicitly type nil into the rescue since that's what you want to return,
# or suppressing LoadError for optional dependencies
Lint/HandleExceptions:
Lint/SuppressedException:
Enabled: false
Layout/SpaceInsideBlockBraces:
@ -182,6 +183,19 @@ Rails/Present:
Exclude:
- "lib/**/*"
# we don't have rails everywhere, so just disable these
Rails/NegateInclude:
Enabled: false
Rails/RakeEnvironment:
Enabled: false
Lint/ConstantDefinitionInBlock:
Exclude:
- "spec/**/*"
Naming/InclusiveLanguage:
Enabled: false
Style/SingleLineMethods:
Exclude:
- "test/dummy/app/models/*"
@ -196,6 +210,10 @@ Style/AccessModifierDeclarations:
Exclude:
- "lib/diaspora_federation/test/factories.rb"
Style/HashAsLastArrayItem:
Exclude:
- "lib/diaspora_federation/validators/*"
# disable this for now, needs to be rechecked later
Style/DateTime:
Exclude:

View file

@ -21,8 +21,8 @@ group :development do
# code style
gem "pronto", "0.11.0", require: false
gem "pronto-rubocop", "0.11.1", require: false
gem "rubocop", "0.75.1", require: false
gem "rubocop-rails", "2.3.2", require: false
gem "rubocop", "1.18.0", require: false
gem "rubocop-rails", "2.11.1", require: false
# debugging
gem "pry"

View file

@ -82,7 +82,6 @@ GEM
multi_xml (>= 0.5.2)
i18n (1.7.0)
concurrent-ruby (~> 1.0)
jaro_winkler (1.5.4)
json (2.2.0)
json-schema (2.8.1)
addressable (>= 2.4)
@ -133,7 +132,7 @@ GEM
byebug (~> 11.0)
pry (~> 0.10)
public_suffix (4.0.6)
rack (2.0.7)
rack (2.2.3)
rack-test (1.1.0)
rack (>= 1.0, < 3)
rails-dom-testing (2.0.3)
@ -152,6 +151,7 @@ GEM
rb-fsevent (0.11.0)
rb-inotify (0.10.1)
ffi (~> 1.0)
regexp_parser (2.1.1)
rexml (3.2.5)
rspec (3.9.0)
rspec-core (~> 3.9.0)
@ -177,16 +177,21 @@ GEM
rspec-mocks (~> 3.9.0)
rspec-support (~> 3.9.0)
rspec-support (3.9.0)
rubocop (0.75.1)
jaro_winkler (~> 1.5.1)
rubocop (1.18.0)
parallel (~> 1.10)
parser (>= 2.6)
parser (>= 3.0.0.0)
rainbow (>= 2.2.2, < 4.0)
regexp_parser (>= 1.8, < 3.0)
rexml
rubocop-ast (>= 1.7.0, < 2.0)
ruby-progressbar (~> 1.7)
unicode-display_width (>= 1.4.0, < 1.7)
rubocop-rails (2.3.2)
unicode-display_width (>= 1.4.0, < 3.0)
rubocop-ast (1.7.0)
parser (>= 3.0.1.1)
rubocop-rails (2.11.1)
activesupport (>= 4.2.0)
rack (>= 1.1)
rubocop (>= 0.72.0)
rubocop (>= 1.7.0, < 2.0)
ruby-progressbar (1.11.0)
ruby2_keywords (0.0.4)
rugged (1.0.1)
@ -210,7 +215,7 @@ GEM
ethon (>= 0.9.0)
tzinfo (1.2.5)
thread_safe (~> 0.1)
unicode-display_width (1.6.1)
unicode-display_width (1.7.0)
uuid (2.3.9)
macaddr (~> 1.0)
valid (1.2.0)
@ -242,8 +247,8 @@ DEPENDENCIES
rspec-collection_matchers (~> 1.2.0)
rspec-json_expectations (~> 2.1)
rspec-rails (~> 3.9.0)
rubocop (= 0.75.1)
rubocop-rails (= 2.3.2)
rubocop (= 1.18.0)
rubocop-rails (= 2.11.1)
simplecov (= 0.17.1)
simplecov-rcov (= 0.2.3)
webmock (~> 3.0)

View file

@ -18,4 +18,6 @@ Gem::Specification.new do |s|
s.license = "AGPL-3.0"
s.files = Dir["lib/diaspora_federation/schemas.rb", "lib/diaspora_federation/schemas/*.json"]
s.required_ruby_version = "~> 2.5"
end

View file

@ -46,7 +46,7 @@ module DiasporaFederation
diaspora_id.strip.sub("acct:", "").to_s.downcase
end
def get(url, http_fallback=false)
def get(url, http_fallback: false)
logger.info "Fetching #{url} for #{diaspora_id}"
response = HttpClient.get(url)
raise "Failed to fetch #{url}: #{response.status}" unless response.success?
@ -69,7 +69,7 @@ module DiasporaFederation
def legacy_webfinger_url_from_host_meta
# This tries the xrd url with https first, then falls back to http.
host_meta = HostMeta.from_xml(get("https://#{domain}/.well-known/host-meta", true))
host_meta = HostMeta.from_xml(get("https://#{domain}/.well-known/host-meta", http_fallback: true))
host_meta.webfinger_template_url.gsub("{uri}", acct_parameter)
end
@ -79,7 +79,7 @@ module DiasporaFederation
webfinger_url = "https://#{domain}/.well-known/webfinger?resource=#{acct_parameter}"
# This tries the WebFinger URL with https first, then falls back to http if webfinger_http_fallback is enabled.
@webfinger = WebFinger.from_json(get(webfinger_url, DiasporaFederation.webfinger_http_fallback))
@webfinger = WebFinger.from_json(get(webfinger_url, http_fallback: DiasporaFederation.webfinger_http_fallback))
rescue => e # rubocop:disable Style/RescueStandardError
logger.warn "WebFinger failed, retrying with legacy WebFinger for #{diaspora_id}: #{e.class}: #{e.message}"
@webfinger = WebFinger.from_xml(get(legacy_webfinger_url_from_host_meta))

View file

@ -77,7 +77,7 @@ module DiasporaFederation
# @param [String] url validation subject
# @return [Boolean] validation result
private_class_method def self.webfinger_url_valid?(url)
!url.nil? && url.instance_of?(String) && url =~ %r{\Ahttps?:\/\/.*\/.*\{uri\}.*}i
!url.nil? && url.instance_of?(String) && url =~ %r{\Ahttps?://.*/.*\{uri\}.*}i
end
# Gets the webfinger url from an XRD data structure

View file

@ -89,7 +89,7 @@ module DiasporaFederation
aliases: (aliases if aliases.any?),
properties: (properties if properties.any?),
links: (links if links.any?)
}.reject {|_, v| v.nil? }
}.compact
end
# Parse the XRD document from the given string and create a hash containing
@ -132,7 +132,7 @@ module DiasporaFederation
aliases: json_hash["aliases"],
properties: json_hash["properties"],
links: symbolize_keys_for_links(json_hash["links"])
}.reject {|_, v| v.nil? }
}.compact
rescue JSON::JSONError => e
raise InvalidDocument,
"Not a JRD document: #{e.class}: #{e.message[0..255].encode(Encoding.default_external, undef: :replace)}"
@ -140,8 +140,10 @@ module DiasporaFederation
private
# rubocop:disable Layout/EmptyLinesAroundAttributeAccessor Style/AccessorGrouping
attr_reader :expires
attr_reader :subject
# rubocop:enable Layout/EmptyLinesAroundAttributeAccessor Style/AccessorGrouping
NS = {xrd: XMLNS}.freeze

View file

@ -7,7 +7,7 @@ module DiasporaFederation
include Logging
# Digest instance used for signing
DIGEST = OpenSSL::Digest::SHA256.new
DIGEST = OpenSSL::Digest.new("SHA256")
# Sign the data with the key
#

View file

@ -321,7 +321,7 @@ module DiasporaFederation
# Generates a hash with entity properties which is put to the "entity_data"
# field of a JSON serialized object.
# @return [Hash] object properties in JSON format
def json_data
def json_data # rubocop:disable Metrics/PerceivedComplexity
enriched_properties.map {|key, value|
type = self.class.class_props[key]
next if optional_nil_value?(key, value)
@ -330,7 +330,7 @@ module DiasporaFederation
entity_data = value.to_json
[key, entity_data] unless entity_data.nil?
elsif type.instance_of?(Array)
entity_data = value.nil? ? nil : value.map(&:to_json)
entity_data = value&.map(&:to_json)
[key, entity_data] unless entity_data.nil?
else
[key, value]

View file

@ -17,15 +17,15 @@ module DiasporaFederation
#
# Use the logging-gem if available, else use a default logger.
def logger
@logger ||= begin
@logger ||= if defined?(::Logging::Logger)
# Use logging-gem if available
return ::Logging::Logger[self] if defined?(::Logging::Logger)
::Logging::Logger[self]
elsif defined?(::Rails)
# Use rails logger if running in rails and no logging-gem is available
return ::Rails.logger if defined?(::Rails)
::Rails.logger
else
# fallback logger
@logger = Logger.new(STDOUT)
@logger = Logger.new($stdout)
@logger.level = Logger::INFO
@logger
end

View file

@ -57,9 +57,9 @@ module DiasporaFederation
# resolved on each call
# @return [Hash] default values
def default_values
optional_props.map {|name| [name, nil] }.to_h.merge(default_props).map {|name, prop|
[name, prop.respond_to?(:call) ? prop.call : prop]
}.to_h
optional_props.map {|name| [name, nil] }.to_h.merge(default_props).transform_values {|prop|
prop.respond_to?(:call) ? prop.call : prop
}
end
# @param [Hash] data entity data

View file

@ -21,7 +21,7 @@ module DiasporaFederation
# @param [String] iv AES initialization vector
# @return [String] base64 encoded ciphertext
# @raise [ArgumentError] if any of the arguments is missing or not the correct type
def self.encrypt(data, key, iv) # rubocop:disable Naming/UncommunicativeMethodParamName
def self.encrypt(data, key, iv) # rubocop:disable Naming/MethodParameterName
raise ArgumentError unless data.instance_of?(String) &&
key.instance_of?(String) &&
iv.instance_of?(String)
@ -43,7 +43,7 @@ module DiasporaFederation
# @param [String] iv AES initialization vector
# @return [String] decrypted plain message
# @raise [ArgumentError] if any of the arguments is missing or not the correct type
def self.decrypt(ciphertext, key, iv) # rubocop:disable Naming/UncommunicativeMethodParamName
def self.decrypt(ciphertext, key, iv) # rubocop:disable Naming/MethodParameterName
raise ArgumentError unless ciphertext.instance_of?(String) &&
key.instance_of?(String) &&
iv.instance_of?(String)

View file

@ -38,7 +38,7 @@ module DiasporaFederation
key = AES.generate_key_and_iv
encrypted_env = AES.encrypt(magic_env.to_xml, key[:key], key[:iv])
encoded_key = key.map {|k, v| [k, Base64.strict_encode64(v)] }.to_h
encoded_key = key.transform_values {|v| Base64.strict_encode64(v) }
encrypted_key = Base64.strict_encode64(pubkey.public_encrypt(JSON.generate(encoded_key)))
JSON.generate(aes_key: encrypted_key, encrypted_magic_envelope: encrypted_env)
@ -53,7 +53,7 @@ module DiasporaFederation
encrypted_json = JSON.parse(encrypted_env)
encoded_key = JSON.parse(privkey.private_decrypt(Base64.decode64(encrypted_json["aes_key"])))
key = encoded_key.map {|k, v| [k, Base64.decode64(v)] }.to_h
key = encoded_key.transform_values {|v| Base64.decode64(v) }
xml = AES.decrypt(encrypted_json["encrypted_magic_envelope"], key["key"], key["iv"])
Nokogiri::XML(xml).root

View file

@ -35,7 +35,7 @@ module DiasporaFederation
DATA_TYPE = "application/xml"
# Digest instance used for signing
DIGEST = OpenSSL::Digest::SHA256.new
DIGEST = OpenSSL::Digest.new("SHA256")
# XML namespace url
XMLNS = "http://salmon-protocol.org/ns/magic-env"
@ -137,10 +137,8 @@ module DiasporaFederation
# @yield [xml] Invokes the block with the
# {http://www.rubydoc.info/gems/nokogiri/Nokogiri/XML/Builder Nokogiri::XML::Builder}
# @return [Nokogiri::XML::Element] XML root node
def build_xml
Nokogiri::XML::Builder.new(encoding: "UTF-8") {|xml|
yield xml
}.doc
def build_xml(&block)
Nokogiri::XML::Builder.new(encoding: "UTF-8", &block).doc
end
# Creates the signature for all fields according to specification

View file

@ -14,9 +14,7 @@ module DiasporaFederation
def to_hash(attributes=[], _callbacks=[])
process_attributes(attributes)
_attributes.each_with_object({}) do |(name, value), hash|
hash[name.to_sym] = value
end
_attributes.transform_keys(&:to_sym)
end
end

View file

@ -22,7 +22,7 @@ module Validation
return true if value.nil? || (value.is_a?(String) && value.empty?)
return true if value.is_a? Date
if value.is_a?(String) && value.match?(/[0-9]{4}\-[0-9]{2}\-[0-9]{2}/)
if value.is_a?(String) && value.match?(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)
date_field = value.split("-").map(&:to_i)
return Date.valid_civil?(date_field[0], date_field[1], date_field[2])
end

View file

@ -19,14 +19,13 @@ module Validation
def valid_value?(value)
return false if value.nil?
if value.is_a?(String)
case value
when String
true if value =~ /\A(true|false|t|f|yes|no|y|n|1|0)\z/i
elsif value.is_a?(Integer)
when Integer
true if [1, 0].include?(value)
elsif [true, false].include?(value)
true
else
false
[true, false].include?(value)
end
end

View file

@ -1,5 +1,6 @@
# frozen_string_literal: true
# rubocop:disable Lint/EmptyBlock
module DiasporaFederation
describe Callbacks do
subject(:callbacks) { Callbacks.new %i[some_event another_event] }
@ -74,3 +75,4 @@ module DiasporaFederation
end
end
end
# rubocop:enable Lint/EmptyBlock

View file

@ -30,7 +30,7 @@ module DiasporaFederation
json = JSON.parse(encrypted)
aes_key = JSON.parse(privkey.private_decrypt(Base64.decode64(json["aes_key"])))
key = aes_key.map {|k, v| [k, Base64.decode64(v)] }.to_h
key = aes_key.transform_values {|v| Base64.decode64(v) }
xml = Salmon::AES.decrypt(json["encrypted_magic_envelope"], key["key"], key["iv"])

View file

@ -86,7 +86,7 @@ module DiasporaFederation
subj = sig_subj(env_xml)
sig = Base64.urlsafe_decode64(env_xml.at_xpath("me:env/me:sig").content)
expect(privkey.public_key.verify(OpenSSL::Digest::SHA256.new, sig, subj)).to be_truthy
expect(privkey.public_key.verify(OpenSSL::Digest.new("SHA256"), sig, subj)).to be_truthy
end
end

View file

@ -19,7 +19,7 @@ dummy_app_path = File.join(File.dirname(__FILE__), "..", "test", "dummy")
begin
require "rails" # try to load rails
rescue LoadError
Dir["#{File.join(dummy_app_path, 'app', 'models')}/*.rb"].each {|f| require f }
Dir["#{File.join(dummy_app_path, 'app', 'models')}/*.rb"].sort.each {|f| require f }
require File.join(dummy_app_path, "config", "initializers", "diaspora_federation")
else
ENV["RAILS_ENV"] ||= "test"
@ -42,7 +42,7 @@ require "entities"
# Requires supporting files with custom matchers and macros, etc,
# in ./support/ and its subdirectories.
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].each {|f| require f }
Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].sort.each {|f| require f }
RSpec.configure do |config|
config.include JSON::SchemaMatchers

View file

@ -21,11 +21,11 @@ def add_signatures(hash, klass=described_class)
end
def sign_with_key(privkey, signature_data)
Base64.strict_encode64(privkey.sign(OpenSSL::Digest::SHA256.new, signature_data))
Base64.strict_encode64(privkey.sign(OpenSSL::Digest.new("SHA256"), signature_data))
end
def verify_signature(pubkey, signature, signed_string)
pubkey.verify(OpenSSL::Digest::SHA256.new, Base64.decode64(signature), signed_string)
pubkey.verify(OpenSSL::Digest.new("SHA256"), Base64.decode64(signature), signed_string)
end
# time helper

View file

@ -1,17 +1,17 @@
# frozen_string_literal: true
def entity_hash_from(hash)
hash.map {|key, value|
hash.transform_values {|value|
if [String, TrueClass, FalseClass, Integer, NilClass].any? {|c| value.is_a? c }
[key, value]
value
elsif value.is_a? Time
[key, value.iso8601]
value.iso8601
elsif value.instance_of?(Array)
[key, value.map(&:to_h)]
value.map(&:to_h)
else
[key, value.to_h]
value.to_h
end
}.to_h
}
end
shared_examples "an Entity subclass" do
@ -104,7 +104,7 @@ shared_examples "a relayable Entity" do
context "signatures generation" do
def verify_signature(pubkey, signature, signed_string)
pubkey.verify(OpenSSL::Digest::SHA256.new, Base64.decode64(signature), signed_string)
pubkey.verify(OpenSSL::Digest.new("SHA256"), Base64.decode64(signature), signed_string)
end
it "computes correct author_signature for the entity" do
@ -135,7 +135,7 @@ shared_examples "a JSON Entity" do
entity_data.delete(:parent)
nested_elements, simple_props = entity_data.partition {|_key, value| value.is_a?(Array) || value.is_a?(Hash) }
expect(to_json_output).to include_json(entity_data: simple_props.reject {|_key, value| value.nil? }.to_h)
expect(to_json_output).to include_json(entity_data: simple_props.to_h.compact)
nested_elements.each {|key, value|
type = described_class.class_props[key]

View file

@ -2,5 +2,5 @@
# This file is used by Rack-based servers to start the application.
require ::File.expand_path("../config/environment", __FILE__)
require ::File.expand_path("config/environment", __dir__)
run Rails.application

View file

@ -16,7 +16,7 @@ Rails.application.configure do
# Enable/disable caching. By default caching is disabled.
# Run rails dev:cache to toggle caching.
if Rails.root.join("tmp", "caching-dev.txt").exist?
if Rails.root.join("tmp/caching-dev.txt").exist?
config.action_controller.perform_caching = true
config.action_controller.enable_fragment_cache_logging = true

View file

@ -69,7 +69,7 @@ Rails.application.configure do
# config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name')
if ENV["RAILS_LOG_TO_STDOUT"].present?
logger = ActiveSupport::Logger.new(STDOUT)
logger = ActiveSupport::Logger.new($stdout)
logger.formatter = config.log_formatter
config.logger = ActiveSupport::TaggedLogging.new(logger)
end

View file

@ -56,6 +56,7 @@ DiasporaFederation.configure do |config|
end
on :save_person_after_webfinger do
# ignore
end
on :fetch_private_key do |diaspora_id|
@ -80,9 +81,11 @@ DiasporaFederation.configure do |config|
end
on :queue_public_receive do
# ignore
end
on :queue_private_receive do
# ignore
true
end
@ -100,6 +103,7 @@ DiasporaFederation.configure do |config|
end
on :update_pod do
# ignore
end
end
end