diff options
72 files changed, 494 insertions, 864 deletions
diff --git a/.rubocop.yml b/.rubocop.yml index 652bfba..ac0f4d4 100644 --- a/.rubocop.yml +++ b/.rubocop.yml @@ -1,5 +1,3 @@ -inherit_from: .rubocop_todo.yml - Style/GuardClause: Enabled: false @@ -12,3 +10,6 @@ Lint/DeprecatedClassMethods: # complains about our nested module end; end style Lint/EndAlignment: Enabled: false + +Style/ClassAndModuleChildren: + EnforcedStyle: compact diff --git a/.rubocop_todo.yml b/.rubocop_todo.yml deleted file mode 100644 index e636a8b..0000000 --- a/.rubocop_todo.yml +++ /dev/null @@ -1,393 +0,0 @@ -# This configuration was generated by -# `rubocop --auto-gen-config` -# on 2016-05-25 12:42:07 +0200 using RuboCop version 0.40.0. -# 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 -Lint/AmbiguousRegexpLiteral: - Exclude: - - 'lib/nickserver/daemon.rb' - -# Offense count: 2 -# Configuration parameters: AllowSafeAssignment. -Lint/AssignmentInCondition: - Exclude: - - 'Rakefile' - - 'lib/nickserver/daemon.rb' - -# Offense count: 1 -Lint/Eval: - Exclude: - - 'Rakefile' - -# Offense count: 2 -Lint/HandleExceptions: - Exclude: - - 'Rakefile' - -# Offense count: 3 -Lint/IneffectiveAccessModifier: - Exclude: - - 'lib/nickserver/config.rb' - - 'lib/nickserver/couch/fetch_key.rb' - -# Offense count: 2 -Lint/NonLocalExitFromIterator: - Exclude: - - 'test/unit/hkp_test.rb' - -# Offense count: 2 -Lint/RescueException: - Exclude: - - 'lib/nickserver/config.rb' - - 'lib/nickserver/couch/fetch_key.rb' - -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: AllowUnusedKeywordArguments, IgnoreEmptyMethods. -Lint/UnusedMethodArgument: - Exclude: - - 'lib/nickserver/couch/fetch_key.rb' - - 'lib/nickserver/daemon.rb' - - 'test/unit/hkp_test.rb' - -# Offense count: 1 -Lint/UselessAccessModifier: - Exclude: - - 'lib/nickserver/config.rb' - -# Offense count: 7 -Lint/UselessAssignment: - Exclude: - - 'lib/nickserver/config.rb' - - 'lib/nickserver/daemon.rb' - - 'lib/nickserver/hkp/key_info.rb' - - 'test/unit/hkp_test.rb' - -# Offense count: 7 -Metrics/AbcSize: - Max: 19 - -# Offense count: 3 -# Configuration parameters: CountComments. -Metrics/ClassLength: - Max: 213 - -# Offense count: 2 -Metrics/CyclomaticComplexity: - Max: 10 - -# Offense count: 49 -# Configuration parameters: AllowHeredoc, AllowURI, URISchemes. -# URISchemes: http, https -Metrics/LineLength: - Max: 229 - -# Offense count: 21 -# Configuration parameters: CountComments. -Metrics/MethodLength: - Max: 17 - -# Offense count: 2 -Metrics/PerceivedComplexity: - Max: 8 - -# Offense count: 1 -# Cop supports --auto-correct. -Performance/RedundantBlockCall: - Exclude: - - 'lib/nickserver/daemon.rb' - -# Offense count: 1 -Style/AccessorMethodName: - Exclude: - - 'lib/nickserver/server.rb' - -# Offense count: 18 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles, ProceduralMethods, FunctionalMethods, IgnoredMethods. -# SupportedStyles: line_count_based, semantic, braces_for_chaining -# ProceduralMethods: benchmark, bm, bmbm, create, each_with_object, measure, new, realtime, tap, with_object -# FunctionalMethods: let, let!, subject, watch -# IgnoredMethods: lambda, proc, it -Style/BlockDelimiters: - Exclude: - - 'lib/nickserver/couch/fetch_key.rb' - - 'lib/nickserver/daemon.rb' - - 'lib/nickserver/hkp/fetch_key.rb' - - 'lib/nickserver/hkp/fetch_key_info.rb' - - 'lib/nickserver/server.rb' - - 'test/unit/hkp_test.rb' - - 'test/unit/nickserver_test.rb' - -# Offense count: 8 -# Cop supports --auto-correct. -# Configuration parameters: IndentWhenRelativeTo, SupportedStyles, IndentOneStep, IndentationWidth. -# SupportedStyles: case, end -Style/CaseIndentation: - Enabled: false - -# Offense count: 1 -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: nested, compact -Style/ClassAndModuleChildren: - Exclude: - - 'test/test_helper.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/ColonMethodCall: - Exclude: - - 'test/unit/nickserver_test.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/CommentIndentation: - Exclude: - - 'test/unit/hkp_test.rb' - -# Offense count: 1 -Style/ConstantName: - Exclude: - - 'lib/nickserver/email_address.rb' - -# Offense count: 8 -Style/Documentation: - Exclude: - - 'spec/**/*' - - 'test/**/*' - - 'lib/nickserver/config.rb' - - 'lib/nickserver/couch/fetch_key.rb' - - 'lib/nickserver/daemon.rb' - - 'lib/nickserver/hkp/fetch_key.rb' - - 'lib/nickserver/hkp/fetch_key_info.rb' - - 'lib/nickserver/hkp/key_info.rb' - - 'lib/nickserver/hkp/parse_key_info.rb' - - 'lib/nickserver/server.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/ElseAlignment: - Exclude: - - 'lib/nickserver/server.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: empty, nil, both -Style/EmptyElse: - Exclude: - - 'lib/nickserver/daemon.rb' - -# Offense count: 10 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: empty_lines, no_empty_lines -Style/EmptyLinesAroundClassBody: - Exclude: - - 'lib/nickserver/couch/fetch_key.rb' - - 'lib/nickserver/daemon.rb' - - 'lib/nickserver/hkp/fetch_key_info.rb' - - 'lib/nickserver/hkp/parse_key_info.rb' - - 'test/test_helper.rb' - - 'test/unit/hkp_test.rb' - - 'test/unit/nickserver_test.rb' - -# Offense count: 4 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: empty_lines, no_empty_lines -Style/EmptyLinesAroundModuleBody: - Exclude: - - 'lib/nickserver/hkp/fetch_key.rb' - - 'lib/nickserver/hkp/fetch_key_info.rb' - - 'lib/nickserver/hkp/key_info.rb' - -# Offense count: 1 -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: format, sprintf, percent -Style/FormatString: - Exclude: - - 'test/test_helper.rb' - -# Offense count: 35 -# Configuration parameters: AllowedVariables. -Style/GlobalVars: - Exclude: - - 'Rakefile' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: MaxLineLength. -Style/IfUnlessModifier: - Exclude: - - 'lib/nickserver/daemon.rb' - - 'lib/nickserver/hkp/key_info.rb' - -# Offense count: 6 -# Cop supports --auto-correct. -# Configuration parameters: Width. -Style/IndentationWidth: - Exclude: - - 'lib/nickserver/couch/fetch_key.rb' - - 'lib/nickserver/hkp/fetch_key.rb' - - 'lib/nickserver/hkp/fetch_key_info.rb' - - 'lib/nickserver/hkp/key_info.rb' - - 'lib/nickserver/hkp/parse_key_info.rb' - - 'lib/nickserver/server.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -Style/LeadingCommentSpace: - Exclude: - - 'Rakefile' - - 'test/unit/hkp_test.rb' - -# Offense count: 6 -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: snake_case, camelCase -Style/MethodName: - Enabled: false - -# Offense count: 5 -Style/MultilineBlockChain: - Exclude: - - 'lib/nickserver/couch/fetch_key.rb' - - 'lib/nickserver/hkp/fetch_key.rb' - - 'lib/nickserver/hkp/fetch_key_info.rb' - - 'lib/nickserver/server.rb' - - 'test/unit/nickserver_test.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -Style/MutableConstant: - Exclude: - - 'lib/nickserver/config.rb' - - 'lib/nickserver/couch/fetch_key.rb' - - 'lib/nickserver/version.rb' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/NegatedIf: - Exclude: - - 'bin/nickserver' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: PreferredDelimiters. -Style/PercentLiteralDelimiters: - Exclude: - - 'nickserver.gemspec' - -# Offense count: 2 -# Cop supports --auto-correct. -Style/RedundantBegin: - Exclude: - - 'lib/nickserver/config.rb' - - 'lib/nickserver/daemon.rb' - -# Offense count: 16 -# Cop supports --auto-correct. -Style/RedundantSelf: - Exclude: - - 'lib/nickserver/config.rb' - - 'lib/nickserver/couch/fetch_key.rb' - - 'lib/nickserver/daemon.rb' - - 'lib/nickserver/hkp/fetch_key.rb' - - 'lib/nickserver/hkp/fetch_key_info.rb' - -# Offense count: 7 -# Cop supports --auto-correct. -# Configuration parameters: AllowAsExpressionSeparator. -Style/Semicolon: - Exclude: - - 'lib/nickserver/daemon.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -Style/SpaceAfterComma: - Exclude: - - 'lib/nickserver/hkp/fetch_key.rb' - - 'test/unit/nickserver_test.rb' - -# Offense count: 4 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: space, no_space -Style/SpaceAroundEqualsInParameterDefault: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: AllowForAlignment. -Style/SpaceAroundOperators: - Exclude: - - 'test/test_helper.rb' - -# Offense count: 3 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: space, no_space -Style/SpaceBeforeBlockBraces: - Enabled: false - -# Offense count: 5 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles, EnforcedStyleForEmptyBraces, SpaceBeforeBlockParameters. -# SupportedStyles: space, no_space -Style/SpaceInsideBlockBraces: - Enabled: false - -# Offense count: 46 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, EnforcedStyleForEmptyBraces, SupportedStyles. -# SupportedStyles: space, no_space -Style/SpaceInsideHashLiteralBraces: - Enabled: false - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: use_perl_names, use_english_names -Style/SpecialGlobalVars: - Enabled: false - -# Offense count: 83 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles, ConsistentQuotesInMultiline. -# SupportedStyles: single_quotes, double_quotes -Style/StringLiterals: - Enabled: false - -# Offense count: 4 -# Cop supports --auto-correct. -# Configuration parameters: EnforcedStyle, SupportedStyles. -# SupportedStyles: final_newline, final_blank_line -Style/TrailingBlankLines: - Exclude: - - 'bin/nickserver' - - 'lib/nickserver/couch/fetch_key.rb' - - 'lib/nickserver/hkp/fetch_key.rb' - - 'test/unit/test_helper.rb' - -# Offense count: 2 -# Cop supports --auto-correct. -Style/UnneededPercentQ: - Exclude: - - 'nickserver.gemspec' - -# Offense count: 1 -# Cop supports --auto-correct. -Style/WhileUntilDo: - Exclude: - - 'Rakefile' - -# Offense count: 1 -# Cop supports --auto-correct. -# Configuration parameters: SupportedStyles, MinSize, WordRegex. -# SupportedStyles: percent, brackets -Style/WordArray: - EnforcedStyle: brackets @@ -1,17 +1,17 @@ -#require "bundler/gem_tasks" +# require "bundler/gem_tasks" -require "rubygems" -require "pty" -require "fileutils" -require "rake/testtask" +require 'rubygems' +require 'pty' +require 'fileutils' +require 'rake/testtask' ## ## TESTING ## Rake::TestTask.new do |t| - t.pattern = "test/**/*_test.rb" - t.libs << "test" + t.pattern = 'test/**/*_test.rb' + t.libs << 'test' t.verbose = true end task default: :test @@ -28,9 +28,7 @@ $gem_path = File.join($base_dir, 'pkg', "#{$spec.name}-#{$spec.version}.gem") def run(cmd) PTY.spawn(cmd) do |output, _input, _pid| begin - while line = output.gets do - puts line - end + output.each { |line| puts line } rescue Errno::EIO end end @@ -38,13 +36,14 @@ rescue PTY::ChildExited end def built_gem_path - Dir[File.join($base_dir, "#{$spec.name}-*.gem")].sort_by{|f| File.mtime(f)}.last + Dir[File.join($base_dir, "#{$spec.name}-*.gem")] + .max_by { |f| File.mtime(f) } end desc "Build #{$spec.name}-#{$spec.version}.gem into the pkg directory" task 'build' do FileUtils.mkdir_p(File.join($base_dir, 'pkg')) - FileUtils.rm($gem_path) if File.exists?($gem_path) + FileUtils.rm($gem_path) if File.exist?($gem_path) run "gem build -V '#{$spec_path}'" file_name = File.basename(built_gem_path) FileUtils.mv(built_gem_path, 'pkg') @@ -53,11 +52,11 @@ end desc "Install #{$spec.name}-#{$spec.version}.gem into either system-wide or user gems" task 'install' do - if !File.exists?($gem_path) + if !File.exist?($gem_path) puts("Could not file #{$gem_path}. Try running 'rake build'") else options = '--verbose --conservative --no-rdoc --no-ri' - if ENV["USER"] == "root" + if ENV['USER'] == 'root' run "gem install #{options} '#{$gem_path}'" else home_gem_path = Gem.path.grep(/home/).first @@ -67,7 +66,7 @@ task 'install' do if input =~ /[yY]/ run "gem install #{$gem_path} #{options} --install-dir '#{home_gem_path}' " else - puts "bailing out." + puts 'bailing out.' end end end @@ -75,7 +74,7 @@ end desc "Uninstall #{$spec.name}-#{$spec.version}.gem from either system-wide or user gems" task 'uninstall' do - if ENV["USER"] == "root" + if ENV['USER'] == 'root' puts "Removing #{$spec.name}-#{$spec.version}.gem from system-wide gems" run "gem uninstall '#{$spec.name}' --version #{$spec.version} --verbose -x -I" else diff --git a/bin/nickserver b/bin/nickserver index b77369c..4706d8b 100755 --- a/bin/nickserver +++ b/bin/nickserver @@ -4,9 +4,9 @@ # Nickserver key discovery daemon # -def load_local_gem(dir_path='../..') +def load_local_gem(dir_path = '../..') base_directory = File.expand_path(dir_path, File.symlink?(__FILE__) ? File.readlink(__FILE__) : __FILE__) - if !$LOAD_PATH.include? "#{base_directory}/lib" + unless $LOAD_PATH.include? "#{base_directory}/lib" if File.exist?("#{base_directory}/Gemfile.lock") ENV['BUNDLE_GEMFILE'] ||= "#{base_directory}/Gemfile" require 'bundler' diff --git a/lib/kernel_ext.rb b/lib/kernel_ext.rb index b5b58e0..3b408e3 100644 --- a/lib/kernel_ext.rb +++ b/lib/kernel_ext.rb @@ -20,7 +20,8 @@ module Kernel # Sets $VERBOSE for the duration of the block and back to its original # value afterwards. def with_warnings(flag) - old_verbose, $VERBOSE = $VERBOSE, flag + old_verbose = $VERBOSE + $VERBOSE = flag yield ensure $VERBOSE = old_verbose diff --git a/lib/nickserver/adapters/celluloid_http.rb b/lib/nickserver/adapters/celluloid_http.rb index 62f905f..cdcc493 100644 --- a/lib/nickserver/adapters/celluloid_http.rb +++ b/lib/nickserver/adapters/celluloid_http.rb @@ -4,6 +4,7 @@ silence_warnings do end module Nickserver::Adapters + # HTTP Adapter using Celluloid::IO class CelluloidHttp < Http silence_warnings do include Celluloid::IO @@ -14,6 +15,5 @@ module Nickserver::Adapters def default_options super.merge ssl_socket_class: Celluloid::IO::SSLSocket end - end end diff --git a/lib/nickserver/adapters/http.rb b/lib/nickserver/adapters/http.rb index eb77cc6..a759e53 100644 --- a/lib/nickserver/adapters/http.rb +++ b/lib/nickserver/adapters/http.rb @@ -2,22 +2,20 @@ require 'nickserver/adapters' require 'nickserver/config' require 'http' -# Nickserver::Adapters::Http -# -# Basic http adapter with ssl and minimal error handling. -# Only implemented get requests so far. -# -# Error Handling: -# -# Pass a string as the 'rescue' option. If a ConnectionError occures -# which includes the string passed it will be rescued and the request -# will return nil. This allows handling the error inside the adapter so -# that for the derived CelluloidHttp Adapter the actor does not get -# killed. - module Nickserver::Adapters + # Nickserver::Adapters::Http + # + # Basic http adapter with ssl and minimal error handling. + # Only implemented get requests so far. + # + # Error Handling: + # + # Pass a string as the 'rescue' option. If a ConnectionError occures + # which includes the string passed it will be rescued and the request + # will return nil. This allows handling the error inside the adapter so + # that for the derived CelluloidHttp Adapter the actor does not get + # killed. class Http - def get(url, options = {}) url = HTTP::URI.parse url.to_s response = get_with_auth url, params: options[:query] diff --git a/lib/nickserver/config.rb b/lib/nickserver/config.rb index b1def7c..62623c1 100644 --- a/lib/nickserver/config.rb +++ b/lib/nickserver/config.rb @@ -5,7 +5,7 @@ module Nickserver PATHS = [ File.expand_path('../../../config/default.yml', __FILE__), '/etc/nickserver.yml' - ] + ].freeze class << self attr_accessor :hkp_url @@ -29,22 +29,21 @@ module Nickserver def self.load self.loaded ||= begin PATHS.each do |file_path| - self.load_config(file_path) + load_config(file_path) end true end - self.validate + validate end def self.couch_url - [ 'http://', - couch_auth, - couch_host, - ':', - couch_port, - '/', - couch_database - ].join + ['http://', + couch_auth, + couch_host, + ':', + couch_port, + '/', + couch_database].join end def self.couch_auth @@ -70,22 +69,20 @@ module Nickserver end def self.load_config(file_path) - begin - YAML.load(File.read(file_path)).each do |key, value| - begin - self.send("#{key}=", value) - rescue NoMethodError - STDERR.puts "ERROR in file #{file_path}, '#{key}' is not a valid option" - exit(1) - end + YAML.safe_load(File.read(file_path)).each do |key, value| + begin + send("#{key}=", value) + rescue NoMethodError + STDERR.puts "ERROR in file #{file_path}, '#{key}' is not a valid option" + exit(1) end - puts "Loaded #{file_path}" if Config.verbose - rescue Errno::ENOENT => exc - puts "Skipping #{file_path}" if Config.verbose - rescue Exception => exc - STDERR.puts exc.inspect - exit(1) end + puts "Loaded #{file_path}" if Config.verbose + rescue Errno::ENOENT => exc + puts "Skipping #{file_path}" if Config.verbose + rescue Exception => exc + STDERR.puts exc.inspect + exit(1) end end end diff --git a/lib/nickserver/couch_db/response.rb b/lib/nickserver/couch_db/response.rb index fe482a8..eae5cc1 100644 --- a/lib/nickserver/couch_db/response.rb +++ b/lib/nickserver/couch_db/response.rb @@ -3,7 +3,6 @@ require 'json' module Nickserver::CouchDB class Response - def initialize(nick, couch_response = {}) @nick = nick @couch_status = couch_response[:status] @@ -39,7 +38,7 @@ module Nickserver::CouchDB end def key - rows.first["value"] + rows.first['value'] end def ok? @@ -51,7 +50,7 @@ module Nickserver::CouchDB end def rows - json["rows"] + json['rows'] end attr_reader :couch_status, :json, :nick diff --git a/lib/nickserver/couch_db/source.rb b/lib/nickserver/couch_db/source.rb index dd29c2a..b7531e4 100644 --- a/lib/nickserver/couch_db/source.rb +++ b/lib/nickserver/couch_db/source.rb @@ -9,9 +9,8 @@ module Nickserver::CouchDB class Error < StandardError; end class Source < Nickserver::Source - - VIEW = '/_design/Identity/_view/pgp_key_by_email' - UNEXPECTED_RESPONSE_CODES = [401, 500] + VIEW = '/_design/Identity/_view/pgp_key_by_email'.freeze + UNEXPECTED_RESPONSE_CODES = [401, 500].freeze def query(nick) status, body = adapter.get url, query: query_for(nick) @@ -23,7 +22,7 @@ module Nickserver::CouchDB def handle_unexpected_responses(status, body) if UNEXPECTED_RESPONSE_CODES.include? status - raise Error.new("Couch responded with #{status}: #{body}") + raise Error, "Couch responded with #{status}: #{body}" end end @@ -32,7 +31,7 @@ module Nickserver::CouchDB end def query_for(nick) - { reduce: "false", key: "\"#{nick}\"" } + { reduce: 'false', key: "\"#{nick}\"" } end attr_reader :config diff --git a/lib/nickserver/daemon.rb b/lib/nickserver/daemon.rb index 12ed30e..06e0720 100644 --- a/lib/nickserver/daemon.rb +++ b/lib/nickserver/daemon.rb @@ -1,5 +1,5 @@ -require "nickserver/version" -require "nickserver/config" +require 'nickserver/version' +require 'nickserver/config' require 'etc' require 'fileutils' @@ -10,9 +10,8 @@ require 'fileutils' module Nickserver class Daemon - def self.run(name, &block) - self.new.run(name, &block) + new.run(name, &block) end def run(name, &block) @@ -38,9 +37,7 @@ module Nickserver if username != 'root' if Process::Sys.getuid == 0 Process::Sys.setuid(Etc.getpwnam(username).uid) - if root? - bail "failed to drop permissions" - end + bail 'failed to drop permissions' if root? else bail "cannot change process uid to #{username}" end @@ -48,13 +45,11 @@ module Nickserver end def root? - begin - Process::Sys.setuid(0) - rescue Errno::EPERM - false - else - true - end + Process::Sys.setuid(0) + rescue Errno::EPERM + false + else + true end # @@ -62,7 +57,7 @@ module Nickserver # def daemonize - return bail("Process is already started") if daemon_running? + return bail('Process is already started') if daemon_running? _pid = fork do exit if fork Process.setsid @@ -71,7 +66,7 @@ module Nickserver catch_signals redirect_output drop_permissions_to(Config.user) if Config.user - File.umask 0000 + File.umask 0o000 yield end end @@ -99,11 +94,7 @@ module Nickserver def pid_from_file(file) pid = IO.read(file).chomp - if pid != "" - pid.to_i - else - nil - end + pid.to_i if pid != '' end def kill_pid @@ -134,10 +125,10 @@ module Nickserver # stop when we should # def catch_signals - ["SIGTERM", "SIGINT", "SIGHUP"].each do |signal| - Signal.trap(signal) { + %w[SIGTERM SIGINT SIGHUP].each do |signal| + Signal.trap(signal) do exit - } + end end end @@ -149,15 +140,15 @@ module Nickserver puts msg puts puts "Usage: #{@name} [OPTION] COMMAND" - puts "COMMAND is one of: start, stop, restart, status, version, foreground" - puts "OPTION is one of: --verbose" + puts 'COMMAND is one of: start, stop, restart, status, version, foreground' + puts 'OPTION is one of: --verbose' puts exit 1 end def bail(msg) puts "#{@name.capitalize} ERROR: #{msg}." - puts "Bailing out." + puts 'Bailing out.' exit(1) end @@ -167,9 +158,9 @@ module Nickserver # def redirect_output if log_path = Config.log_file - FileUtils.mkdir_p File.dirname(log_path), mode: 0755 + FileUtils.mkdir_p File.dirname(log_path), mode: 0o755 FileUtils.touch log_path - File.chmod(0600, log_path) + File.chmod(0o600, log_path) if Config.user && Process::Sys.getuid == 0 FileUtils.chown(Config.user, nil, log_path) end @@ -195,10 +186,10 @@ module Nickserver # Runs until the block condition is met or the timeout_seconds is exceeded # until_true(10) { ...return_condition... } # - def until_true(timeout_seconds=MAX_WAIT, &block) + def until_true(timeout_seconds = MAX_WAIT) elapsed_seconds = 0 interval = 0.5 - while elapsed_seconds < timeout_seconds && block.call != true + while elapsed_seconds < timeout_seconds && yield != true elapsed_seconds += interval sleep(interval) end @@ -208,18 +199,18 @@ module Nickserver def parse_options loop do case ARGV[0] - when 'start' then ARGV.shift; @command = :start - when 'stop' then ARGV.shift; @command = :stop - when 'restart' then ARGV.shift; @command = :restart - when 'status' then ARGV.shift; @command = :status - when 'version' then ARGV.shift; @command = :version - when 'foreground' then ARGV.shift; @command = :foreground - when '--verbose' then ARGV.shift; Config.verbose = true - when /^-/ then override_default_config(ARGV.shift, ARGV.shift) - else break + when 'start' then ARGV.shift; @command = :start + when 'stop' then ARGV.shift; @command = :stop + when 'restart' then ARGV.shift; @command = :restart + when 'status' then ARGV.shift; @command = :status + when 'version' then ARGV.shift; @command = :version + when 'foreground' then ARGV.shift; @command = :foreground + when '--verbose' then ARGV.shift; Config.verbose = true + when /^-/ then override_default_config(ARGV.shift, ARGV.shift) + else break end end - usage("Missing command") unless @command + usage('Missing command') unless @command end def override_default_config(flag, value) @@ -251,8 +242,8 @@ module Nickserver end end - def command_foreground(&block) - trap("INT") do + def command_foreground + trap('INT') do puts "\nShutting down..." exit(0) end @@ -285,6 +276,5 @@ module Nickserver exit(1) # must exit non-zero if not running end end - end end diff --git a/lib/nickserver/dispatcher.rb b/lib/nickserver/dispatcher.rb index dfd53e5..99f06c3 100644 --- a/lib/nickserver/dispatcher.rb +++ b/lib/nickserver/dispatcher.rb @@ -23,7 +23,6 @@ require 'nickserver/request_handlers/fingerprint_handler' module Nickserver class Dispatcher - def initialize(responder, adapter = nil) @responder = responder @adapter = adapter @@ -49,23 +48,22 @@ module Nickserver def init_handler_chain chain = HandlerChain.new RequestHandlers::InvalidEmailHandler, - RequestHandlers::LocalEmailHandler, - RequestHandlers::LeapEmailHandler, - RequestHandlers::HkpEmailHandler, - RequestHandlers::FingerprintHandler, - Proc.new { proxy_error_response }, - Proc.new { Nickserver::Response.new(404, "404 Not Found\n") } + RequestHandlers::LocalEmailHandler, + RequestHandlers::LeapEmailHandler, + RequestHandlers::HkpEmailHandler, + RequestHandlers::FingerprintHandler, + proc { proxy_error_response }, + proc { Nickserver::Response.new(404, "404 Not Found\n") } chain.continue_on HTTP::ConnectionError - return chain + chain end def proxy_error_response exc = handler_chain.rescued_exceptions.first if exc Nickserver::Response.new 502, - JSON.dump(error: exc.to_s) + JSON.dump(error: exc.to_s) end end - end end diff --git a/lib/nickserver/email_address.rb b/lib/nickserver/email_address.rb index 20f642c..5dfd931 100644 --- a/lib/nickserver/email_address.rb +++ b/lib/nickserver/email_address.rb @@ -1,6 +1,5 @@ module Nickserver class EmailAddress - REGEXP = begin qtext = '[^\\x0d\\x22\\x5c\\x80-\\xff]' dtext = '[^\\x0d\\x5b-\\x5d\\x80-\\xff]' @@ -48,6 +47,5 @@ module Nickserver protected attr_reader :address - end end diff --git a/lib/nickserver/handler_chain.rb b/lib/nickserver/handler_chain.rb index afc24a5..f685a2e 100644 --- a/lib/nickserver/handler_chain.rb +++ b/lib/nickserver/handler_chain.rb @@ -1,3 +1,5 @@ +require 'English' + # # Handler Chain # @@ -14,7 +16,6 @@ module Nickserver class HandlerChain - def initialize(*handlers) @handlers = handlers @exceptions_to_rescue = [] @@ -27,7 +28,7 @@ module Nickserver def handle(*args) result = nil - _handled_by = @handlers.find{|h| result = try_handler(h, *args)} + _handled_by = @handlers.find { |h| result = try_handler(h, *args) } result end @@ -41,7 +42,7 @@ module Nickserver def try_handler(handler, *args) result = handler.call(*args) rescue *exceptions_to_rescue - self.rescued_exceptions << $! + rescued_exceptions << $ERROR_INFO result = false end end diff --git a/lib/nickserver/hkp/client.rb b/lib/nickserver/hkp/client.rb index d53daad..d632a36 100644 --- a/lib/nickserver/hkp/client.rb +++ b/lib/nickserver/hkp/client.rb @@ -1,18 +1,16 @@ require 'nickserver/hkp' - -# -# Client for the HKP protocol. -# -# This is not a complete implementation - only the parts we need. -# Instantiate with an adapter that will take care of the http requests. -# -# For each request we yield http_status and the response content just -# like the adapter does. - - -module Nickserver; module Hkp +require 'nickserver/config' + +module Nickserver::Hkp + # + # Client for the HKP protocol. + # + # This is not a complete implementation - only the parts we need. + # Instantiate with an adapter that will take care of the http requests. + # + # For each request we yield http_status and the response content just + # like the adapter does. class Client - def initialize(adapter) @adapter = adapter end @@ -20,7 +18,7 @@ module Nickserver; module Hkp # # used to fetch an array of KeyInfo objects that match the given email # - def get_key_infos_by_email(email, &block) + def get_key_infos_by_email(email) get op: 'vindex', search: email.to_s, fingerprint: 'on' end @@ -28,7 +26,7 @@ module Nickserver; module Hkp # fetches ascii armored OpenPGP public key from the keyserver # def get_key_by_fingerprint(fingerprint) - get op: 'get', search: "0x" + fingerprint + get op: 'get', search: '0x' + fingerprint end protected @@ -37,9 +35,9 @@ module Nickserver; module Hkp def get(query) # in practice, exact=on seems to have no effect - query = {exact: 'on', options: 'mr'}.merge query - response = adapter.get Config.hkp_url, query: query - return response + query = { exact: 'on', options: 'mr' }.merge query + response = adapter.get Nickserver::Config.hkp_url, query: query + response end end -end; end +end diff --git a/lib/nickserver/hkp/key_info.rb b/lib/nickserver/hkp/key_info.rb index d4ecf10..e1a9500 100644 --- a/lib/nickserver/hkp/key_info.rb +++ b/lib/nickserver/hkp/key_info.rb @@ -1,70 +1,102 @@ require 'cgi' require 'nickserver/hkp' -# -# Class to represent the key information result from a query to a key server -# (but not the key itself). -# -# The initialize method parses the hkp 'machine readable' output. -# -# format definition of machine readable index output is here: -# http://tools.ietf.org/html/draft-shaw-openpgp-hkp-00#section-5.2 -# module Nickserver::Hkp + # + # Class to represent the key information result from a query to a key server + # (but not the key itself). + # + # The initialize method parses the hkp 'machine readable' output. + # + # format definition of machine readable index output is here: + # http://tools.ietf.org/html/draft-shaw-openpgp-hkp-00#section-5.2 + # class KeyInfo - attr_accessor :uids, :keyid, :algo, :flags + attr_accessor :uids def initialize(hkp_record) uid_lines = hkp_record.split("\n") pub_line = uid_lines.shift - @keyid, @algo, @keylen_s, @creationdate_s, @expirationdate_s, @flags = pub_line.split(':')[1..-1] - @uids = [] - uid_lines.each do |uid_line| - uid, _creationdate, _expirationdate, _flags = uid_line.split(':')[1..-1] - # for now, ignore the expirationdate and flags of uids. sks does return them anyway - @uids << CGI.unescape(uid.sub(/.*<(.+)>.*/, '\1')) + @properties = pub_line.split(':')[1..-1] + @uids = extract_uids(uid_lines) + end + + CHECKS = %i[too_short? expired? revoked? disabled? outdated?].freeze + + def error + CHECKS.find do |check| + msg = check.to_s.chop.tr('_', ' ') + "key is #{msg}." if send(check) end end + def keyid + properties.first + end + + def algo + properties.second + end + def keylen - @keylen ||= @keylen_s.to_i + properties[2].to_i end def creationdate - @creationdate ||= begin - if @creationdate_s - Time.at(@creationdate_s.to_i) - end - end + created = properties[3] + Time.at(created.to_i) end def expirationdate - @expirationdate ||= begin - if @expirationdate_s - Time.at(@expirationdate_s.to_i) - end - end + expires = properties[4] + Time.at(expires.to_i) + end + + def flags + properties.last end def rsa? - @algo == "1" + algo == '1' end def dsa? - @algo == "17" + algo == '17' + end + + protected + + attr_reader :properties + + def extract_uids(uid_lines) + uid_lines.map do |uid_line| + # for now, ignore the expirationdate and flags of uids. + # sks does return them anyway + uid, _creationdate, _expirationdate, _flags = uid_line.split(':')[1..-1] + CGI.unescape(uid.sub(/.*<(.+)>.*/, '\1')) + end + end + + # CHECKS + + def too_short? + keylen < 2048 + end + + def expired? + flags =~ /e/ end def revoked? - @flags =~ /r/ + flags =~ /r/ end def disabled? - @flags =~ /d/ + flags =~ /d/ end - def expired? - @flags =~ /e/ + def outdated? + expirationdate && expirationdate < Time.now end end - end diff --git a/lib/nickserver/hkp/parse_key_info.rb b/lib/nickserver/hkp/parse_key_info.rb index 2f928a0..a6f170c 100644 --- a/lib/nickserver/hkp/parse_key_info.rb +++ b/lib/nickserver/hkp/parse_key_info.rb @@ -1,13 +1,12 @@ -# -# Simple parser for Hkp KeyInfo responses. -# -# Focus is on simple here. Trying to avoid state and sideeffects. -# Parsing a response with 12 keys and validating them takes 2ms. -# So no need for memoization and making things more complex. -# -module Nickserver; module Hkp +module Nickserver::Hkp + # + # Simple parser for Hkp KeyInfo responses. + # + # Focus is on simple here. Trying to avoid state and sideeffects. + # Parsing a response with 12 keys and validating them takes 2ms. + # So no need for memoization and making things more complex. + # class ParseKeyInfo - # for this regexp to work, the source text must end in a trailing "\n", # which the output of sks does. MATCH_PUB_KEY = /(^pub:.+?\n(^uid:.+?\n)+)/m @@ -40,14 +39,14 @@ module Nickserver; module Hkp protected def keys(uid) - key_infos(uid).reject { |key| error_for_key(key) } + key_infos(uid).reject(&:error) end def msg(uid) if errors(uid).any? error_messages(uid).join "\n" else - "Could not fetch keyinfo." + 'Could not fetch keyinfo.' end end @@ -63,13 +62,12 @@ module Nickserver; module Hkp end def errors(uid) - key_infos(uid).map{|key| error_for_key(key) }.compact + key_infos(uid).map(&:error).compact end def error_messages(uid) key_infos(uid).map do |key| - err = error_for_key(key) - error_message(uid, key, err) + error_message(uid, key) end.compact end @@ -91,22 +89,8 @@ module Nickserver; module Hkp status == 200 end - def error_message(uid, key, err) - "Ignoring key #{key.keyid} for #{uid}: #{err}" if err - end - - def error_for_key(key) - if key.keylen < 2048 - "key length is too short." - elsif key.expired? - "key expired." - elsif key.revoked? - "key revoked." - elsif key.disabled? - "key disabled." - elsif key.expirationdate && key.expirationdate < Time.now - "key expired" - end + def error_message(uid, key) + "Ignoring key #{key.keyid} for #{uid}: #{key.error}" if key.error end end -end; end +end diff --git a/lib/nickserver/hkp/response.rb b/lib/nickserver/hkp/response.rb index c52e25f..2cc69d3 100644 --- a/lib/nickserver/hkp/response.rb +++ b/lib/nickserver/hkp/response.rb @@ -1,6 +1,5 @@ module Nickserver::Hkp class Response - attr_reader :status, :content def initialize(uid, key) @@ -13,6 +12,5 @@ module Nickserver::Hkp def format_response(map) map.to_json end - end end diff --git a/lib/nickserver/hkp/source.rb b/lib/nickserver/hkp/source.rb index 82c94a0..d7c86a3 100644 --- a/lib/nickserver/hkp/source.rb +++ b/lib/nickserver/hkp/source.rb @@ -2,24 +2,21 @@ require 'nickserver/source' require 'nickserver/response' require 'nickserver/hkp/response' require 'nickserver/hkp/client' -require "nickserver/hkp/parse_key_info" -require "nickserver/hkp/key_info" - - -# -# Fetch keys via HKP -# http://tools.ietf.org/html/draft-shaw-openpgp-hkp-00 -# - -module Nickserver; module Hkp +require 'nickserver/hkp/parse_key_info' +require 'nickserver/hkp/key_info' + +module Nickserver::Hkp + # + # Fetch keys via HKP + # http://tools.ietf.org/html/draft-shaw-openpgp-hkp-00 + # class Source < Nickserver::Source - def query(nick) status, response = search(nick) if status == 200 best = pick_best_key(response) get_key_by_fingerprint(best.keyid, nick) - elsif status != 404 # 404 means no key found and we proceed + elsif status != 404 # 404 means no key found and we proceed Nickserver::Response.new(status, response) end end @@ -27,7 +24,7 @@ module Nickserver; module Hkp def search(nick) status, response = client.get_key_infos_by_email(nick) parser = ParseKeyInfo.new status, response - return parser.status_for(nick), parser.response_for(nick) + [parser.status_for(nick), parser.response_for(nick)] end def get_key_by_fingerprint(fingerprint, nick = nil) @@ -35,7 +32,7 @@ module Nickserver; module Hkp if status == 200 Response.new nick, response else - Nickserver::Response.new status, "HKP Request failed" + Nickserver::Response.new status, 'HKP Request failed' end end @@ -48,11 +45,11 @@ module Nickserver; module Hkp # that is signed by the oldest key. # def pick_best_key(key_info_list) - key_info_list.sort {|a,b| a.creationdate <=> b.creationdate}.last + key_info_list.sort_by(&:creationdate).last end def client @client ||= Client.new(adapter) end end -end; end +end diff --git a/lib/nickserver/hkp/v_index_response.rb b/lib/nickserver/hkp/v_index_response.rb index 865d476..a44af51 100644 --- a/lib/nickserver/hkp/v_index_response.rb +++ b/lib/nickserver/hkp/v_index_response.rb @@ -9,7 +9,6 @@ require 'nickserver/hkp/key_info' # So no need for memoization and making things more complex. module Nickserver::Hkp class VIndexResponse - # for this regexp to work, the source text must end in a trailing "\n", # which the output of sks does. MATCH_PUB_KEY = /(^pub:.+?\n(^uid:.+?\n)+)/m @@ -29,14 +28,14 @@ module Nickserver::Hkp end def keys - key_infos.reject { |key| error_for_key(key) } + key_infos.reject &:error end def msg if errors.any? error_messages.join "\n" else - "Could not fetch keyinfo." + 'Could not fetch keyinfo.' end end @@ -53,13 +52,12 @@ module Nickserver::Hkp end def errors - key_infos.map{|key| error_for_key(key) }.compact + key_infos.map { |key| error_for_key(key) }.compact end def error_messages key_infos.map do |key| - err = error_for_key(key) - error_message(key, err) + error_message(key) end.compact end @@ -75,22 +73,8 @@ module Nickserver::Hkp end end - def error_message(key, err) - "Ignoring key #{key.keyid} for #{nick}: #{err}" if err - end - - def error_for_key(key) - if key.keylen < 2048 - "key length is too short." - elsif key.expired? - "key expired." - elsif key.revoked? - "key revoked." - elsif key.disabled? - "key disabled." - elsif key.expirationdate && key.expirationdate < Time.now - "key expired" - end + def error_message(key) + "Ignoring key #{key.keyid} for #{nick}: #{key.error}" if key.error end end end diff --git a/lib/nickserver/logging_responder.rb b/lib/nickserver/logging_responder.rb index 6eb756f..08a9ce7 100644 --- a/lib/nickserver/logging_responder.rb +++ b/lib/nickserver/logging_responder.rb @@ -1,6 +1,5 @@ module Nickserver class LoggingResponder - def initialize(responder, logger) @responder = responder @logger = logger diff --git a/lib/nickserver/nicknym/source.rb b/lib/nickserver/nicknym/source.rb index f49547e..9c2d8c4 100644 --- a/lib/nickserver/nicknym/source.rb +++ b/lib/nickserver/nicknym/source.rb @@ -9,13 +9,13 @@ module Nickserver def available_for?(domain) status, body = adapter.get "https://#{domain}/provider.json", - rescue: 'failed to connect: getaddrinfo' + rescue: 'failed to connect: getaddrinfo' status == 200 && provider_with_mx?(body) end def query(email) status, body = nicknym_get email.domain, address: email.to_s - return Nickserver::Response.new(status, body) + Nickserver::Response.new(status, body) end protected diff --git a/lib/nickserver/reel_server.rb b/lib/nickserver/reel_server.rb index db38e50..f7cc3b0 100644 --- a/lib/nickserver/reel_server.rb +++ b/lib/nickserver/reel_server.rb @@ -9,14 +9,13 @@ require 'nickserver/logging_responder' module Nickserver class ReelServer < Reel::Server::HTTP - DEFAULT_ADAPTER_CLASS = Nickserver::Adapters::CelluloidHttp def self.start(options = {}) new(options[:host], options[:port]) end - def initialize(host = "127.0.0.1", port = 3000) + def initialize(host = '127.0.0.1', port = 3000) Celluloid.logger = logger super(host, port, &method(:on_connection)) end @@ -33,7 +32,6 @@ module Nickserver end end - protected def handle_request(request) @@ -44,7 +42,7 @@ module Nickserver end end rescue StandardError - request.respond 500, "{}" + request.respond 500, '{}' end def logging_request(request) diff --git a/lib/nickserver/request.rb b/lib/nickserver/request.rb index c21c280..0d6dab6 100644 --- a/lib/nickserver/request.rb +++ b/lib/nickserver/request.rb @@ -6,11 +6,11 @@ module Nickserver end def email - param("address") + param('address') end def fingerprint - param("fingerprint") + param('fingerprint') end def domain diff --git a/lib/nickserver/request_handlers/base.rb b/lib/nickserver/request_handlers/base.rb index 495a6da..a33e772 100644 --- a/lib/nickserver/request_handlers/base.rb +++ b/lib/nickserver/request_handlers/base.rb @@ -1,7 +1,6 @@ module Nickserver module RequestHandlers class Base - def self.call(request, adapter = nil) new(request, adapter).handle end @@ -12,8 +11,8 @@ module Nickserver end protected + attr_reader :request, :adapter end end end - diff --git a/lib/nickserver/request_handlers/fingerprint_handler.rb b/lib/nickserver/request_handlers/fingerprint_handler.rb index ac3c3c8..4917338 100644 --- a/lib/nickserver/request_handlers/fingerprint_handler.rb +++ b/lib/nickserver/request_handlers/fingerprint_handler.rb @@ -5,7 +5,6 @@ require 'nickserver/error_response' module Nickserver module RequestHandlers class FingerprintHandler < Base - def handle return unless fingerprint if fingerprint.length == 40 && !fingerprint[/\H/] @@ -24,7 +23,6 @@ module Nickserver def source Nickserver::Hkp::Source.new adapter end - end end end diff --git a/lib/nickserver/request_handlers/hkp_email_handler.rb b/lib/nickserver/request_handlers/hkp_email_handler.rb index 393ef87..3d39a4e 100644 --- a/lib/nickserver/request_handlers/hkp_email_handler.rb +++ b/lib/nickserver/request_handlers/hkp_email_handler.rb @@ -4,7 +4,6 @@ require 'nickserver/hkp/source' module Nickserver module RequestHandlers class HkpEmailHandler < Base - def handle source.query(email) if request.email end @@ -18,7 +17,6 @@ module Nickserver def source Nickserver::Hkp::Source.new adapter end - end end end diff --git a/lib/nickserver/request_handlers/invalid_email_handler.rb b/lib/nickserver/request_handlers/invalid_email_handler.rb index bb98f65..3a6cfa0 100644 --- a/lib/nickserver/request_handlers/invalid_email_handler.rb +++ b/lib/nickserver/request_handlers/invalid_email_handler.rb @@ -5,10 +5,9 @@ require 'nickserver/error_response' module Nickserver module RequestHandlers class InvalidEmailHandler < Base - def handle return unless request.email - ErrorResponse.new("Not a valid address") if email.invalid? + ErrorResponse.new('Not a valid address') if email.invalid? end protected diff --git a/lib/nickserver/request_handlers/leap_email_handler.rb b/lib/nickserver/request_handlers/leap_email_handler.rb index bc3ddef..d202e15 100644 --- a/lib/nickserver/request_handlers/leap_email_handler.rb +++ b/lib/nickserver/request_handlers/leap_email_handler.rb @@ -5,7 +5,6 @@ require 'nickserver/nicknym/source' module Nickserver module RequestHandlers class LeapEmailHandler < Base - def handle source.query(email) if request.email && remote_email? && nicknym_email? end @@ -31,7 +30,6 @@ module Nickserver def domain Config.domain || request.domain end - end end end diff --git a/lib/nickserver/request_handlers/local_email_handler.rb b/lib/nickserver/request_handlers/local_email_handler.rb index 08147a0..bed26bd 100644 --- a/lib/nickserver/request_handlers/local_email_handler.rb +++ b/lib/nickserver/request_handlers/local_email_handler.rb @@ -5,7 +5,6 @@ require 'nickserver/couch_db/source' module Nickserver module RequestHandlers class LocalEmailHandler < Base - def handle source.query(email) if request.email && email.domain?(domain) end @@ -23,7 +22,6 @@ module Nickserver def source Nickserver::CouchDB::Source.new adapter end - end end end diff --git a/lib/nickserver/response.rb b/lib/nickserver/response.rb index 372da36..9aef3af 100644 --- a/lib/nickserver/response.rb +++ b/lib/nickserver/response.rb @@ -1,6 +1,5 @@ module Nickserver class Response - attr_reader :status, :body def initialize(status, body) diff --git a/lib/nickserver/server.rb b/lib/nickserver/server.rb index 2139029..ff1d362 100644 --- a/lib/nickserver/server.rb +++ b/lib/nickserver/server.rb @@ -10,7 +10,6 @@ require 'nickserver/reel_server' # module Nickserver class Server - # # Starts the Nickserver. # @@ -19,7 +18,7 @@ module Nickserver # * :port (default Nickserver::Config.port) # * :host (default 127.0.0.1) # - def self.start(opts={}) + def self.start(opts = {}) Nickserver::Config.load options = { host: '127.0.0.1', @@ -32,7 +31,5 @@ module Nickserver Nickserver::ReelServer.start(options) end - - end end diff --git a/lib/nickserver/source.rb b/lib/nickserver/source.rb index 934407a..d7f4d12 100644 --- a/lib/nickserver/source.rb +++ b/lib/nickserver/source.rb @@ -1,6 +1,5 @@ module Nickserver class Source - def initialize(adapter = nil) @adapter = adapter end diff --git a/lib/nickserver/version.rb b/lib/nickserver/version.rb index 9811fb5..67f2b2a 100644 --- a/lib/nickserver/version.rb +++ b/lib/nickserver/version.rb @@ -1,3 +1,3 @@ module Nickserver - VERSION = "0.10.0" + VERSION = '0.10.0'.freeze end diff --git a/lib/nickserver/wkd/source.rb b/lib/nickserver/wkd/source.rb index 01f376e..43f0b2e 100644 --- a/lib/nickserver/wkd/source.rb +++ b/lib/nickserver/wkd/source.rb @@ -1,16 +1,35 @@ require 'nickserver/source' require 'nickserver/response' +require 'nickserver/wkd/url' +require 'nickserver/hkp/response' -module Nickserver - module Wkd - class Source < Nickserver::Source - - def query(email) - url = Url.new(email) - status, body = adapter.get url - return Nickserver::Response.new(status, body) +module Nickserver::Wkd + # Query the web key directory for a given email address + class Source < Nickserver::Source + def query(email) + url = Url.new(email) + status, blob = adapter.get url + if status == 200 + Nickserver::Hkp::Response.new(email.to_s, armor_key(blob)) end + end + + protected + + def armor_key(blob) + header + encode(blob) + footer + end + + def encode(blob) + Base64.strict_encode64(blob).scan(/.{1,64}/).join "\n" + end + + def header + "-----BEGIN PGP PUBLIC KEY BLOCK-----\n\n" + end + def footer + "\n-----END PGP PUBLIC KEY BLOCK-----\n" end end end diff --git a/lib/nickserver/wkd/url.rb b/lib/nickserver/wkd/url.rb index 965e7ec..0ccff38 100644 --- a/lib/nickserver/wkd/url.rb +++ b/lib/nickserver/wkd/url.rb @@ -1,31 +1,28 @@ require 'digest/sha1' require 'zbase32' -module Nickserver - module Wkd - class Url - - def initialize(email) - @domain = email.domain.downcase - @local_part = email.local_part.downcase - end +module Nickserver::Wkd + # The url to lookup the given email address in the web key directory. + class Url + def initialize(email) + @domain = email.domain.downcase + @local_part = email.local_part.downcase + end - def to_s - "https://#{domain}/.well-known/openpgpkey" + - "/hu/#{domain}/#{encoded_digest}" - end + def to_s + "https://#{domain}/.well-known/openpgpkey/hu/#{encoded_digest}" + end - protected + protected - attr_reader :domain, :local_part + attr_reader :domain, :local_part - def encoded_digest - ZBase32.encode32(digest.to_i(16).to_s(2)) - end + def encoded_digest + ZBase32.encode32(digest.to_i(16).to_s(2)) + end - def digest - Digest::SHA1.hexdigest local_part - end + def digest + Digest::SHA1.hexdigest local_part end end end diff --git a/lib/zbase32.rb b/lib/zbase32.rb index 754213d..3f61477 100644 --- a/lib/zbase32.rb +++ b/lib/zbase32.rb @@ -1,5 +1,4 @@ module ZBase32 - ALPHABET = 'ybndrfg8ejkmcpqxot1uwisza345h769'.split('').freeze def self.encode32(bin_string) @@ -13,7 +12,6 @@ module ZBase32 ALPHABET.index(char).to_s(2).rjust(5, '0') end.join bin[0, (8 * (bin.length / 8))] - # .sub /10*$/ ,'1' + # .sub /10*$/ ,'1' end - end diff --git a/nickserver.gemspec b/nickserver.gemspec index af1ef97..aa4b3b8 100644 --- a/nickserver.gemspec +++ b/nickserver.gemspec @@ -1,21 +1,28 @@ # -*- encoding: utf-8 -*- + +require 'English' + lib = File.expand_path('../lib', __FILE__) $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib) require 'nickserver/version' Gem::Specification.new do |gem| - gem.name = "nickserver" + gem.name = 'nickserver' gem.version = Nickserver::VERSION - gem.authors = ["elijah"] - gem.email = ["elijah@riseup.net"] - gem.description = %q{Provides a directory service to map uid to public key.} - gem.summary = %q{Nickserver provides the ability to map a uid (user@domain.org) to a public key. This is the opposite of a key server, whose job it is to map public key to uid. Nickserver is lightweight and asynchronous.} - gem.homepage = "https://leap.se" + gem.authors = ['elijah'] + gem.email = ['elijah@riseup.net'] + gem.description = 'Provides a directory service to map uid to public key.' + gem.homepage = 'https://leap.se' + gem.summary = <<-EOSUM +Nickserver provides the ability to map a uid (user@domain.org) to a public key. +This is the opposite of a key server, whose job it is to map public key to uid. +Nickserver is lightweight and asynchronous. + EOSUM - gem.files = `git ls-files`.split($/) - gem.executables = gem.files.grep(%r{^bin/}).map{ |f| File.basename(f) } + gem.files = `git ls-files`.split($INPUT_RECORD_SEPARATOR) + gem.executables = gem.files.grep(%r{^bin/}).map { |f| File.basename(f) } gem.test_files = gem.files.grep(%r{^(test|spec|features)/}) - gem.require_paths = ["lib"] + gem.require_paths = ['lib'] gem.required_ruby_version = '~> 2.1' gem.add_development_dependency 'rake' diff --git a/test/file_content.rb b/test/file_content.rb index 0d0ac21..abc0fd8 100644 --- a/test/file_content.rb +++ b/test/file_content.rb @@ -1,11 +1,9 @@ module FileContent - def file_content(filename) (@file_contents ||= {})[filename] ||= File.read(file_path(filename)) end def file_path(filename) - "%s/files/%s" % [File.dirname(__FILE__), filename] + format('%s/files/%s', File.dirname(__FILE__), filename) end - end diff --git a/test/files/dewey.pgp.asc b/test/files/dewey.pgp.asc new file mode 100644 index 0000000..a5306bd --- /dev/null +++ b/test/files/dewey.pgp.asc @@ -0,0 +1,11 @@ +-----BEGIN PGP PUBLIC KEY BLOCK----- + +mDMEV3IffxYJKwYBBAHaRw8BAQdA0exktohYX2Qglxscg720r5ztQNXO8EP9sOE7 +HDy0V+W0FGRld2V5QHRlc3QuZ251cGcub3JniHkEExYIACEFAldyH38CGwMFCwkI +BwIGFQgJCgsCBBYCAwECHgECF4AACgkQ0Z0isG7nhmgbcwEA3rsFpACV7/rrzyAs +0d3s0ArpjjClmOldD9/si8rSkt8A/04ykHUX1lOQpKdQrT3FtxNnhyOlfF5Y5X1Y +HICUAAsGuDgEV3IffxIKKwYBBAGXVQEFAQEHQN/mRvG5CEKhvuvYdLmjWqUoROwV +D6+6+OdkKFIwjrpuAwEIB4hhBBgWCAAJBQJXch9/AhsMAAoJENGdIrBu54ZoFDEB +AIqlLFB7nxsrMDhmG8il8yUQ6ufvnXSkxkXUjWqqxH8uAP42Y30G+odkMcGHeUzg +4k5B+xPXFVetOsZAD5LILZ1QDw== +-----END PGP PUBLIC KEY BLOCK----- diff --git a/test/functional/bin_test.rb b/test/functional/bin_test.rb index 3e2774c..3a4e6c7 100644 --- a/test/functional/bin_test.rb +++ b/test/functional/bin_test.rb @@ -2,13 +2,12 @@ require 'minitest/autorun' require 'minitest/pride' class BinTest < Minitest::Test - def teardown - run_command "stop" + run_command 'stop' end def test_bin_loading - assert_command_runs("version") + assert_command_runs('version') end def test_not_running_by_default @@ -16,26 +15,26 @@ class BinTest < Minitest::Test end def test_start - run_command "start" + run_command 'start' assert_running end protected def assert_running - status = run_command "status" - assert_includes status, "Nickserver running" + status = run_command 'status' + assert_includes status, 'Nickserver running' end def assert_stopped - status = run_command "status" - assert_includes status, "No nickserver processes are running." + status = run_command 'status' + assert_includes status, 'No nickserver processes are running.' end def assert_command_runs(command) out = run_command command - assert ($?.exitstatus == 0), - "failed to run 'nickserver #{command}':\n #{out}" + assert ($CHILD_STATUS.exitstatus == 0), + "failed to run 'nickserver #{command}':\n #{out}" end def run_command(command) @@ -45,5 +44,4 @@ class BinTest < Minitest::Test def path_to_executable File.expand_path(File.dirname(__FILE__) + '/../../bin/nickserver') end - end diff --git a/test/functional/sample_test.rb b/test/functional/sample_test.rb index 2b49527..412555e 100644 --- a/test/functional/sample_test.rb +++ b/test/functional/sample_test.rb @@ -1,3 +1,4 @@ +require 'English' require 'support/functional_test' class SampleTest < FunctionalTest @@ -49,7 +50,7 @@ class SampleTest < FunctionalTest end def lookup(address) - run_command %Q(curl localhost:6425 #{curl_opts} -d "address=#{address}") + run_command %(curl localhost:6425 #{curl_opts} -d "address=#{address}") end def curl_opts @@ -57,13 +58,13 @@ class SampleTest < FunctionalTest end def open_files_count - run_command(%Q(lsof | grep " #{nickserver_pid} " | wc -l)).to_i + run_command(%(lsof | grep " #{nickserver_pid} " | wc -l)).to_i end def run_command(command) `#{command} 2>&1`.tap do |out| - assert ($?.exitstatus == 0), - "failed to run '#{command}':\n #{out}" + assert ($CHILD_STATUS.exitstatus == 0), + "failed to run '#{command}':\n #{out}" end end end diff --git a/test/integration/couch_db/source_test.rb b/test/integration/couch_db/source_test.rb index cb1153e..ac237c6 100644 --- a/test/integration/couch_db/source_test.rb +++ b/test/integration/couch_db/source_test.rb @@ -4,7 +4,7 @@ require 'nickserver/couch_db/source' module Nickserver::CouchDB class SourceTest < Minitest::Test - include FileContent + include FileContent def test_couch_query_and_response adapter = adapter_returns 200, file_content(:blue_couchdb_result) diff --git a/test/integration/dispatcher_test.rb b/test/integration/dispatcher_test.rb index b551e87..58aa972 100644 --- a/test/integration/dispatcher_test.rb +++ b/test/integration/dispatcher_test.rb @@ -13,7 +13,6 @@ require 'nickserver/dispatcher' # class Nickserver::DispatcherTest < Minitest::Test - def test_empty_query handle assert_response not_found @@ -26,12 +25,12 @@ class Nickserver::DispatcherTest < Minitest::Test def test_fingerprint_to_short handle fingerprint: ['44F2F455E28'] - assert_response error("Fingerprint invalid: 44F2F455E28") + assert_response error('Fingerprint invalid: 44F2F455E28') end def test_fingerprint_is_not_hex handle fingerprint: ['X36E738D69173C13Z709E44F2F455E2824D18DDX'] - assert_response error("Fingerprint invalid: X36E738D69173C13Z709E44F2F455E2824D18DDX") + assert_response error('Fingerprint invalid: X36E738D69173C13Z709E44F2F455E2824D18DDX') end def test_missing_domain @@ -42,28 +41,28 @@ class Nickserver::DispatcherTest < Minitest::Test end def test_email_via_hkp - handle address: ['valid@email.tld'], headers: { "Host" => "http://nickserver.me" } + handle address: ['valid@email.tld'], headers: { 'Host' => 'http://nickserver.me' } stub_nicknym_not_available hkp_source.expect :query, success, [Nickserver::EmailAddress] assert_response success end def test_email_via_hkp_nicknym_unreachable - handle address: ['valid@email.tld'], headers: { "Host" => "http://nickserver.me" } + handle address: ['valid@email.tld'], headers: { 'Host' => 'http://nickserver.me' } stub_nicknym_raises hkp_source.expect :query, success, [Nickserver::EmailAddress] assert_response success end def test_email_not_found_hkp_nicknym_unreachable - handle address: ['valid@email.tld'], headers: { "Host" => "http://nickserver.me" } + handle address: ['valid@email.tld'], headers: { 'Host' => 'http://nickserver.me' } stub_nicknym_raises hkp_source.expect :query, nil, [Nickserver::EmailAddress] assert_response http_connection_error end def test_email_via_nicknym - handle address: ['valid@email.tld'], headers: { "Host" => "http://nickserver.me" } + handle address: ['valid@email.tld'], headers: { 'Host' => 'http://nickserver.me' } nicknym_source.expect :available_for?, true, [String] nicknym_source.expect :query, success, [Nickserver::EmailAddress] assert_response success @@ -73,7 +72,7 @@ class Nickserver::DispatcherTest < Minitest::Test handle fingerprint: ['E36E738D69173C13D709E44F2F455E2824D18DDF'] stub_nicknym_not_available hkp_source.expect :get_key_by_fingerprint, success, - ['E36E738D69173C13D709E44F2F455E2824D18DDF'] + ['E36E738D69173C13D709E44F2F455E2824D18DDF'] assert_response success end @@ -81,7 +80,7 @@ class Nickserver::DispatcherTest < Minitest::Test def handle(params = {}) @headers = params.delete(:headers) || {} - @params = Hash[ params.map{ |k,v| [k.to_s, v] } ] + @params = Hash[params.map { |k, v| [k.to_s, v] }] end def assert_response(response) @@ -115,7 +114,7 @@ class Nickserver::DispatcherTest < Minitest::Test end def success - response status: 200, content: "fake content" + response status: 200, content: 'fake content' end def not_found @@ -128,7 +127,7 @@ class Nickserver::DispatcherTest < Minitest::Test def http_connection_error response status: 502, - content: JSON.dump(error: "HTTP::ConnectionError") + content: JSON.dump(error: 'HTTP::ConnectionError') end def response(options) @@ -142,5 +141,4 @@ class Nickserver::DispatcherTest < Minitest::Test def responder @responder ||= Minitest::Mock.new end - end diff --git a/test/integration/hkp_test.rb b/test/integration/hkp_test.rb index da128c2..c12588c 100644 --- a/test/integration/hkp_test.rb +++ b/test/integration/hkp_test.rb @@ -70,7 +70,7 @@ class HkpTest < Minitest::Test end def test_fetch_key_too_short - uid = 'chiiph@leap.se' + uid = 'chiiph@leap.se' stubbing_http do stub_sks_vindex_reponse(uid, body: file_content(:short_key_vindex_result)) @@ -86,13 +86,13 @@ class HkpTest < Minitest::Test end end - def assert_response_for_uid(uid, &block) + def assert_response_for_uid(uid) Nickserver::Hkp::Source.new(adapter).query uid do |response| yield response end end - def assert_key_info_for_uid(uid, &block) + def assert_key_info_for_uid(uid) Nickserver::Hkp::Source.new(adapter).search uid do |status, keys| assert_equal 200, status yield keys @@ -105,5 +105,4 @@ class HkpTest < Minitest::Test assert_key_info_for_uid(uid, &block) end end - end diff --git a/test/integration/nickserver_test.rb b/test/integration/nickserver_test.rb index 5dffcd2..fb9b952 100644 --- a/test/integration/nickserver_test.rb +++ b/test/integration/nickserver_test.rb @@ -33,9 +33,9 @@ class NickserverTest < CelluloidTest stub_sks_get_reponse(key_id, body: file_content(:leap_public_key)) start do - params = {query: {"address" => uid}} + params = { query: { 'address' => uid } } get(params) do |response| - assert_equal file_content(:leap_public_key), JSON.parse(response.to_s)["openpgp"] + assert_equal file_content(:leap_public_key), JSON.parse(response.to_s)['openpgp'] end end end @@ -45,19 +45,19 @@ class NickserverTest < CelluloidTest stub_sks_get_reponse(fingerprint, body: file_content(:leap_public_key)) start do - params = {query: {"fingerprint" => fingerprint}} + params = { query: { 'fingerprint' => fingerprint } } get(params) do |response| - assert_equal file_content(:leap_public_key), JSON.parse(response.to_s)["openpgp"] + assert_equal file_content(:leap_public_key), JSON.parse(response.to_s)['openpgp'] end end end def test_GET_served_via_couch_not_found - domain = "example.org" - uid = "bananas@" + domain + domain = 'example.org' + uid = 'bananas@' + domain stub_couch_response(uid, status: 404) do start do - params = {query: {"address" => uid}, head: {"Host" => domain}} + params = { query: { 'address' => uid }, head: { 'Host' => domain } } get(params) do |response| assert_equal 404, response.code end @@ -66,11 +66,11 @@ class NickserverTest < CelluloidTest end def test_GET_served_via_couch_empty_results - domain = "example.org" - uid = "stompy@" + domain + domain = 'example.org' + uid = 'stompy@' + domain stub_couch_response(uid, body: file_content(:empty_couchdb_result)) do start do - params = {query: {"address" => uid}, head: {host: domain}} + params = { query: { 'address' => uid }, head: { host: domain } } get(params) do |response| assert_equal 404, response.code end @@ -79,11 +79,11 @@ class NickserverTest < CelluloidTest end def test_GET_served_via_couch_success - domain = "example.org" - uid = "blue@" + domain + domain = 'example.org' + uid = 'blue@' + domain stub_couch_response(uid, body: file_content(:blue_couchdb_result)) do start do - params = {query: {"address" => uid}, head: {"Host" => domain}} + params = { query: { 'address' => uid }, head: { 'Host' => domain } } get(params) do |response| assert_equal file_content(:blue_nickserver_result), response.to_s end @@ -104,7 +104,7 @@ class NickserverTest < CelluloidTest # # start nickserver # - def start(timeout = 1) + def start(_timeout = 1) server = Nickserver::ReelServer.new '127.0.0.1', config.port stubbing_http do yield server @@ -133,10 +133,9 @@ class NickserverTest < CelluloidTest # this works because http requests to 127.0.0.1 are not stubbed, but requests to other domains are. # def request(method, options = {}) - response = HTTP. - headers(options.delete(:head)). - request method, "http://127.0.0.1:#{config.port}/", options + response = HTTP + .headers(options.delete(:head)) + .request method, "http://127.0.0.1:#{config.port}/", options yield response end - end diff --git a/test/remote/celluloid_http_test.rb b/test/remote/celluloid_http_test.rb index da5f5d7..b315c6b 100644 --- a/test/remote/celluloid_http_test.rb +++ b/test/remote/celluloid_http_test.rb @@ -3,7 +3,6 @@ require 'support/celluloid_test' require 'nickserver/adapters/celluloid_http' class Nickserver::Adapters::CelluloidHttpTest < CelluloidTest - def test_https_for_hkp url = Nickserver::Config.hkp_url status, _body = adapter.get url diff --git a/test/remote/hkp_source_test.rb b/test/remote/hkp_source_test.rb index ff61513..8232dce 100644 --- a/test/remote/hkp_source_test.rb +++ b/test/remote/hkp_source_test.rb @@ -19,8 +19,8 @@ class RemoteHkpSourceTest < CelluloidTest ca_file = file_path('mayfirst-ca.pem') config.stub(:hkp_url, hkp_url) do + # config.stub(:hkp_ca_file, file_path('autistici-ca.pem')) do config.stub(:hkp_ca_file, ca_file) do - #config.stub(:hkp_ca_file, file_path('autistici-ca.pem')) do assert File.exist?(Nickserver::Config.hkp_ca_file) uid = 'elijah@riseup.net' assert_key_info_for_uid uid do |keys| @@ -34,10 +34,9 @@ class RemoteHkpSourceTest < CelluloidTest protected def assert_key_info_for_uid(uid) - source.search uid do |status, keys| - assert_equal 200, status - yield keys - end + status, keys = source.search uid + assert_equal 200, status + yield keys rescue HTTP::ConnectionError => e skip "could not talk to hkp server: #{e}" end @@ -45,5 +44,4 @@ class RemoteHkpSourceTest < CelluloidTest def source Nickserver::Hkp::Source.new adapter end - end diff --git a/test/remote/nicknym_source_test.rb b/test/remote/nicknym_source_test.rb index b97f2b2..6fff1f6 100644 --- a/test/remote/nicknym_source_test.rb +++ b/test/remote/nicknym_source_test.rb @@ -48,8 +48,8 @@ class RemoteNicknymSourceTest < CelluloidTest def assert_pgp_key_in(response) json = JSON.parse response.content - assert_equal email_with_key.to_s, json["address"] - refute_empty json["openpgp"] + assert_equal email_with_key.to_s, json['address'] + refute_empty json['openpgp'] rescue JSON::ParserError skip "invalid json response: #{response.content}" end @@ -65,5 +65,4 @@ class RemoteNicknymSourceTest < CelluloidTest def email_without_key Nickserver::EmailAddress.new('pleaseneverusethisemailweuseittotest@mail.bitmask.net') end - end diff --git a/test/remote/wkd_source_test.rb b/test/remote/wkd_source_test.rb new file mode 100644 index 0000000..1ed7ea5 --- /dev/null +++ b/test/remote/wkd_source_test.rb @@ -0,0 +1,43 @@ +require 'test_helper' +require 'file_content' +require 'support/celluloid_test' +require 'support/http_adapter_helper' +require 'nickserver/wkd/source' +require 'nickserver/email_address' + +class RemoteWkdSourceTest < CelluloidTest + include HttpAdapterHelper + include FileContent + + def test_existing_key + response = source.query email_with_key + assert_equal 200, response.status + assert_pgp_key_in response + end + + def test_missing_key + uid = 'thisemaildoesnotexist@test.gnupg.org' + email = Nickserver::EmailAddress.new uid + status, body = source.query email + assert_nil status + assert_nil body + end + + protected + + def assert_pgp_key_in(response) + json = JSON.parse response.content + assert_equal email_with_key.to_s, json["address"] + refute_empty json["openpgp"] + assert_equal file_content('dewey.pgp.asc'), json['openpgp'] + end + + def email_with_key + uid = 'dewey@test.gnupg.org' + Nickserver::EmailAddress.new uid + end + + def source + Nickserver::Wkd::Source.new adapter + end +end diff --git a/test/support/celluloid_test.rb b/test/support/celluloid_test.rb index ddcfcbb..a00edff 100644 --- a/test/support/celluloid_test.rb +++ b/test/support/celluloid_test.rb @@ -1,5 +1,4 @@ class CelluloidTest < Minitest::Test - def setup super Celluloid.boot @@ -10,5 +9,4 @@ class CelluloidTest < Minitest::Test Celluloid.shutdown super end - end diff --git a/test/support/functional_test.rb b/test/support/functional_test.rb index 4ebc40a..ceabfea 100644 --- a/test/support/functional_test.rb +++ b/test/support/functional_test.rb @@ -2,28 +2,27 @@ require 'minitest/autorun' require 'minitest/pride' class FunctionalTest < Minitest::Test - protected def nickserver_pid - status = nickserver "status" + status = nickserver 'status' /process id (\d*)\./.match(status)[1] end def assert_running - status = nickserver "status" - assert_includes status, "Nickserver running" + status = nickserver 'status' + assert_includes status, 'Nickserver running' end def assert_stopped - status = nickserver "status" - assert_includes status, "No nickserver processes are running." + status = nickserver 'status' + assert_includes status, 'No nickserver processes are running.' end def assert_command_runs(command) out = nickserver command - assert ($?.exitstatus == 0), - "failed to run 'nickserver #{command}':\n #{out}" + assert ($CHILD_STATUS.exitstatus == 0), + "failed to run 'nickserver #{command}':\n #{out}" end def nickserver(command) @@ -37,5 +36,4 @@ class FunctionalTest < Minitest::Test def self.path_to_executable File.expand_path(File.dirname(__FILE__) + '/../../bin/nickserver') end - end diff --git a/test/support/http_adapter_helper.rb b/test/support/http_adapter_helper.rb index 6817e1e..a22b696 100644 --- a/test/support/http_adapter_helper.rb +++ b/test/support/http_adapter_helper.rb @@ -1,7 +1,6 @@ require 'nickserver/adapters/celluloid_http' module HttpAdapterHelper - def setup super @adapter = Nickserver::Adapters::CelluloidHttp.new @@ -15,5 +14,4 @@ module HttpAdapterHelper protected attr_reader :adapter - end diff --git a/test/support/http_stub_helper.rb b/test/support/http_stub_helper.rb index cc9196e..b0ec069 100644 --- a/test/support/http_stub_helper.rb +++ b/test/support/http_stub_helper.rb @@ -1,6 +1,7 @@ require 'nickserver/reel_server' module HttpStubHelper + protected def stubbing_http Nickserver::ReelServer::DEFAULT_ADAPTER_CLASS.stub :new, adapter do @@ -11,18 +12,35 @@ module HttpStubHelper def stub_nicknym_available_response(domain, response = {}) stub_http_get "https://#{domain}/provider.json", - response, - Hash + response, + Hash end def stub_sks_vindex_reponse(uid, response = {}) - stub_http_get config.hkp_url, response, - query: {op: 'vindex', search: uid, exact: 'on', options: 'mr', fingerprint: 'on'} + stub_http_get config.hkp_url, + response, + query: vindex_query(uid) + end + + def vindex_query(uid) + { op: 'vindex', + search: uid, + exact: 'on', + options: 'mr', + fingerprint: 'on' } end def stub_sks_get_reponse(key_id, response = {}) - stub_http_get config.hkp_url, response, - query: {op: 'get', search: "0x"+key_id, exact: 'on', options: 'mr'} + stub_http_get config.hkp_url, + response, + query: sks_get_query(key_id) + end + + def sks_get_query(key_id) + { op: 'get', + search: '0x' + key_id, + exact: 'on', + options: 'mr' } end def stub_couch_response(uid, response = {}) @@ -30,12 +48,10 @@ module HttpStubHelper stub_http_get(/#{Regexp.escape(config.couch_url)}.*#{query}/, response) end - private - def stub_http_get(url, response, options = nil) - response = {status: 200, body: ""}.merge(response || {}) + response = { status: 200, body: '' }.merge(response || {}) adapter.expect :get, [response[:status], response[:body]], - [url, options].compact + [url, options].compact end def adapter diff --git a/test/support/request_handler_test_helper.rb b/test/support/request_handler_test_helper.rb index c063108..292f99c 100644 --- a/test/support/request_handler_test_helper.rb +++ b/test/support/request_handler_test_helper.rb @@ -1,7 +1,6 @@ require 'nickserver/request' module RequestHandlerTestHelper - protected def assert_refuses(opts = {}) @@ -33,9 +32,8 @@ module RequestHandlerTestHelper end def request(opts = {}) - params = {'address' => [opts[:email]]} - headers = {'Host' => opts[:domain]} + params = { 'address' => [opts[:email]] } + headers = { 'Host' => opts[:domain] } Nickserver::Request.new params, headers end - end diff --git a/test/test_helper.rb b/test/test_helper.rb index 06e8e78..1d48c63 100644 --- a/test/test_helper.rb +++ b/test/test_helper.rb @@ -23,7 +23,7 @@ class Minitest::Test end def file_path(filename) - "%s/files/%s" % [File.dirname(__FILE__), filename] + format('%s/files/%s', File.dirname(__FILE__), filename) end def config diff --git a/test/unit/adapters/http_test.rb b/test/unit/adapters/http_test.rb index f6768df..5bf3468 100644 --- a/test/unit/adapters/http_test.rb +++ b/test/unit/adapters/http_test.rb @@ -3,7 +3,6 @@ require 'http' require 'nickserver/adapters/http' class HttpAdapterTest < Minitest::Test - def test_normal_raise stub_http_to_raise do assert_raises HTTP::ConnectionError do @@ -29,7 +28,7 @@ class HttpAdapterTest < Minitest::Test protected def stub_http_to_raise(&block) - raises_exception = -> (*_args) { + raises_exception = lambda { |*_args| raise HTTP::ConnectionError, 'for some reason' } HTTP.stub :get, raises_exception, &block diff --git a/test/unit/couch_db/response_test.rb b/test/unit/couch_db/response_test.rb index d44760d..3003307 100644 --- a/test/unit/couch_db/response_test.rb +++ b/test/unit/couch_db/response_test.rb @@ -6,20 +6,20 @@ class Nickserver::CouchDB::ResponseTest < Minitest::Test include FileContent def test_404 - response = response_for "bananas@example.org", - status: 404, body: "{}" + response = response_for 'bananas@example.org', + status: 404, body: '{}' assert_equal 404, response.status end def test_200_with_empty_response - response = response_for "stompy@example.org", - status: 200, body: file_content(:empty_couchdb_result) + response = response_for 'stompy@example.org', + status: 200, body: file_content(:empty_couchdb_result) assert_equal 404, response.status end def test_200_with_success - response = response_for "blue@example.org", - status: 200, body: file_content(:blue_couchdb_result) + response = response_for 'blue@example.org', + status: 200, body: file_content(:blue_couchdb_result) assert_equal 200, response.status assert_equal file_content(:blue_nickserver_result), response.content end diff --git a/test/unit/couch_db/source_unit_test.rb b/test/unit/couch_db/source_unit_test.rb index e5a4f43..d14ff2f 100644 --- a/test/unit/couch_db/source_unit_test.rb +++ b/test/unit/couch_db/source_unit_test.rb @@ -3,21 +3,20 @@ require 'nickserver/couch_db/source' module Nickserver::CouchDB class SourceUnitTest < Minitest::Test - def test_query - address = "nick@domain.tl" + address = 'nick@domain.tl' adapter = Minitest::Mock.new adapter.expect :get, [200, nil], - [String, {query: { reduce: "false", key: "\"#{address}\"" }}] + [String, { query: { reduce: 'false', key: "\"#{address}\"" } }] Source.new(adapter).query address adapter.verify end def test_401 - address = "nick@domain.tl" + address = 'nick@domain.tl' adapter = Minitest::Mock.new adapter.expect :get, [401, nil], - [String, {query: { reduce: "false", key: "\"#{address}\"" }}] + [String, { query: { reduce: 'false', key: "\"#{address}\"" } }] assert_raises Error do Source.new(adapter).query address end diff --git a/test/unit/email_address_test.rb b/test/unit/email_address_test.rb index 2fea65d..983e979 100644 --- a/test/unit/email_address_test.rb +++ b/test/unit/email_address_test.rb @@ -2,7 +2,6 @@ require 'test_helper' require 'nickserver/email_address' class EmailAddressTest < Minitest::Test - def test_domain nick = Nickserver::EmailAddress.new 'nick@test.me' assert_equal 'test.me', nick.domain @@ -24,5 +23,4 @@ class EmailAddressTest < Minitest::Test nick = Nickserver::EmailAddress.new 'asdf' assert nick.invalid? end - end diff --git a/test/unit/error_response_test.rb b/test/unit/error_response_test.rb index 7242b38..5b81e46 100644 --- a/test/unit/error_response_test.rb +++ b/test/unit/error_response_test.rb @@ -2,11 +2,9 @@ require 'test_helper' require 'nickserver/error_response' class ErrorResponseTest < Minitest::Test - def test_content - response = Nickserver::ErrorResponse.new "Not a valid address" + response = Nickserver::ErrorResponse.new 'Not a valid address' assert_equal "500 Not a valid address\n", response.content assert_equal 500, response.status end - end diff --git a/test/unit/handler_chain_test.rb b/test/unit/handler_chain_test.rb index fae0418..1d79f18 100644 --- a/test/unit/handler_chain_test.rb +++ b/test/unit/handler_chain_test.rb @@ -2,7 +2,6 @@ require 'test_helper' require 'nickserver/handler_chain' class HandlerChainTest < Minitest::Test - def test_initialization assert chain end @@ -12,14 +11,14 @@ class HandlerChainTest < Minitest::Test end def test_triggering_handlers - handler_mock.expect :call, nil, [:a, :b] + handler_mock.expect :call, nil, %i[a b] chain handler_mock chain.handle :a, :b handler_mock.verify end def test_returns_handler_result - chain handler_with_nil, handler_with_result + chain handler_with_nil, handler_with_result assert_equal :result, chain.handle end @@ -55,14 +54,14 @@ class HandlerChainTest < Minitest::Test end def handler_with_nil - Proc.new {} + proc {} end def handler_with_result - Proc.new { :result } + proc { :result } end def handler_raising(exception = RuntimeError) - Proc.new { raise exception } + proc { raise exception } end end diff --git a/test/unit/hkp/client_test.rb b/test/unit/hkp/client_test.rb index 9784d0a..8941c5e 100644 --- a/test/unit/hkp/client_test.rb +++ b/test/unit/hkp/client_test.rb @@ -3,22 +3,21 @@ require 'nickserver/hkp/client' module Nickserver::Hkp class ClientTest < Minitest::Test - def test_get_key_infos_by_email - adapter_expects_query op: "vindex", - search: email, - options: "mr", - fingerprint: "on", - exact: "on" + adapter_expects_query op: 'vindex', + search: email, + options: 'mr', + fingerprint: 'on', + exact: 'on' client.get_key_infos_by_email(email) @adapter.verify end def test_key_by_fingerprint - adapter_expects_query op: "get", - search: "0x#{fingerprint}", - options: "mr", - exact: "on" + adapter_expects_query op: 'get', + search: "0x#{fingerprint}", + options: 'mr', + exact: 'on' client.get_key_by_fingerprint(fingerprint) @adapter.verify end @@ -34,7 +33,7 @@ module Nickserver::Hkp def adapter_expects(*args) @adapter = Minitest::Mock.new @adapter.expect :get, dummy_response, - args + args end def email @@ -48,6 +47,5 @@ module Nickserver::Hkp def dummy_response [200, 'dummy_response'] end - end end diff --git a/test/unit/hkp/v_index_response_test.rb b/test/unit/hkp/v_index_response_test.rb index d909520..270409a 100644 --- a/test/unit/hkp/v_index_response_test.rb +++ b/test/unit/hkp/v_index_response_test.rb @@ -7,7 +7,7 @@ class Nickserver::Hkp::VIndexResponseTest < Minitest::Test def test_leap_public_key response = response_for 'cloudadmin@leap.se', - body: file_content(:leap_vindex_result) + body: file_content(:leap_vindex_result) assert_equal 'E818C478D3141282F7590D29D041EB11B1647490', response.keys.first.keyid end diff --git a/test/unit/logging_responder_test.rb b/test/unit/logging_responder_test.rb index bb6c4a0..9053860 100644 --- a/test/unit/logging_responder_test.rb +++ b/test/unit/logging_responder_test.rb @@ -3,10 +3,9 @@ require 'nickserver/logging_responder' module Nickserver class LoggingResponderTest < Minitest::Test - def test_responds_and_logs - logger.expect :info, nil, [" -> 200"] - respond_to 200, "body" + logger.expect :info, nil, [' -> 200'] + respond_to 200, 'body' logger.verify end @@ -26,6 +25,5 @@ module Nickserver def logger @logger ||= Minitest::Mock.new end - end end diff --git a/test/unit/nicknym/source_test.rb b/test/unit/nicknym/source_test.rb index b17f22b..040e0eb 100644 --- a/test/unit/nicknym/source_test.rb +++ b/test/unit/nicknym/source_test.rb @@ -5,7 +5,6 @@ require 'nickserver/nicknym/source' require 'nickserver/email_address' class NicknymSourceTest < Minitest::Test - def test_initialization assert source end @@ -39,7 +38,7 @@ class NicknymSourceTest < Minitest::Test def proxies_query_response?(status = 0, body = nil) adapter.expect :get, [status, body], - ['https://nicknym.leap_powered.tld:6425', query: {address: email_stub.to_s}] + ['https://nicknym.leap_powered.tld:6425', query: { address: email_stub.to_s }] response = source.query(email_stub) assert_equal status, response.status assert_equal body, response.content @@ -48,10 +47,10 @@ class NicknymSourceTest < Minitest::Test def available_on?(*args) adapter.expect :get, args, - ['https://remote.tld/provider.json', Hash] + ['https://remote.tld/provider.json', Hash] available = source.available_for?('remote.tld') adapter.verify - return available + available end def source diff --git a/test/unit/request_handlers/local_email_handler_test.rb b/test/unit/request_handlers/local_email_handler_test.rb index 1645451..badf3d6 100644 --- a/test/unit/request_handlers/local_email_handler_test.rb +++ b/test/unit/request_handlers/local_email_handler_test.rb @@ -32,5 +32,4 @@ class LocalEmailHandlerTest < MiniTest::Test def source_class Nickserver::CouchDB::Source end - end diff --git a/test/unit/request_test.rb b/test/unit/request_test.rb index eee01c3..7010d9c 100644 --- a/test/unit/request_test.rb +++ b/test/unit/request_test.rb @@ -2,7 +2,6 @@ require 'test_helper' require 'nickserver/request' class Nickserver::RequestTest < Minitest::Test - def test_email request = request_with_params address: fake_email assert_equal fake_email, request.email @@ -19,8 +18,7 @@ class Nickserver::RequestTest < Minitest::Test end def test_domain - request = Nickserver::Request.new Hash.new, - 'Host' => ' nicknym.my.domain.tld:123' + request = Nickserver::Request.new({}, 'Host' => ' nicknym.my.domain.tld:123') assert_equal 'my.domain.tld', request.domain end @@ -29,7 +27,7 @@ class Nickserver::RequestTest < Minitest::Test # params are encoded with strings as keys and arrays with the # given value(s) def request_with_params(params = {}) - params = params.collect{|k,v| [k.to_s, Array(v)]}.to_h + params = params.collect { |k, v| [k.to_s, Array(v)] }.to_h Nickserver::Request.new params, {} end @@ -40,5 +38,4 @@ class Nickserver::RequestTest < Minitest::Test def fake_fingerprint 'F' * 40 end - end diff --git a/test/unit/response_test.rb b/test/unit/response_test.rb index ac7a3a8..401f8ee 100644 --- a/test/unit/response_test.rb +++ b/test/unit/response_test.rb @@ -2,11 +2,9 @@ require 'test_helper' require 'nickserver/response' class ResponseTest < Minitest::Test - def test_ok_response - response = Nickserver::Response.new 200, "content" - assert_equal "content", response.content + response = Nickserver::Response.new 200, 'content' + assert_equal 'content', response.content assert_equal 200, response.status end - end diff --git a/test/unit/test_helper.rb b/test/unit/test_helper.rb deleted file mode 100644 index ade21a0..0000000 --- a/test/unit/test_helper.rb +++ /dev/null @@ -1 +0,0 @@ -require File.dirname(File.dirname(__FILE__)) + '/test_helper'
\ No newline at end of file diff --git a/test/unit/wkd/url_test.rb b/test/unit/wkd/url_test.rb index 9bf8f64..d4e0e28 100644 --- a/test/unit/wkd/url_test.rb +++ b/test/unit/wkd/url_test.rb @@ -12,15 +12,30 @@ module Nickserver::Wkd assert_equal sample_url, url.to_s end + # we can be pretty sure this works for the person who proposed it + def test_gnupg_testuser_email + url = Url.new test_user_email + assert_equal test_user_url, url.to_s + end + protected + def test_user_email + Nickserver::EmailAddress.new 'dewey@test.gnupg.org' + end + + def test_user_url + 'https://test.gnupg.org/.well-known/openpgpkey/hu/' \ + '1g8totoxbt4zf6na1sukczp5fiewr1oe' + end + def sample_email Nickserver::EmailAddress.new 'Joe.Doe@Example.ORG' end def sample_url - 'https://example.org/.well-known/openpgpkey/' + - 'hu/example.org/iy9q119eutrkn8s1mk4r39qejnbu3n5q' + 'https://example.org/.well-known/openpgpkey/hu/' \ + 'iy9q119eutrkn8s1mk4r39qejnbu3n5q' end end end diff --git a/test/unit/zbase_test.rb b/test/unit/zbase_test.rb index 97f0fc5..e2997a3 100644 --- a/test/unit/zbase_test.rb +++ b/test/unit/zbase_test.rb @@ -3,9 +3,8 @@ require 'minitest/autorun' require 'zbase32' class Zbase32Test < Minitest::Test - def test_samples - samples.each do |k,v| + samples.each do |k, v| assert_equal k, decode(v) assert_equal v, encode(k) end |