repo
stringlengths
5
92
file_url
stringlengths
80
287
file_path
stringlengths
5
197
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:37:27
2026-01-04 17:58:21
truncated
bool
2 classes
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/initializers/session_store.rb
test/dummy/config/initializers/session_store.rb
# Be sure to restart your server when you modify this file. Rails.application.config.session_store :cookie_store, key: '_dummy_session'
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/initializers/wrap_parameters.rb
test/dummy/config/initializers/wrap_parameters.rb
# Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] if respond_to?(:wrap_parameters) end # To enable root element in JSON for ActiveRecord objects. # ActiveSupport.on_load(:active_record) do # self.include_root_in_json = true # end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/initializers/inflections.rb
test/dummy/config/initializers/inflections.rb
# Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym 'RESTful' # end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/initializers/cookies_serializer.rb
test/dummy/config/initializers/cookies_serializer.rb
# Be sure to restart your server when you modify this file. Rails.application.config.action_dispatch.cookies_serializer = :json
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/initializers/assets.rb
test/dummy/config/initializers/assets.rb
# Be sure to restart your server when you modify this file. # Version of your assets, change this if you want to expire all your assets. Rails.application.config.assets.version = '1.0' # Add additional assets to the asset load path # Rails.application.config.assets.paths << Emoji.images_path # Precompile additional assets. # application.js, application.css, and all non-JS/CSS in app/assets folder are already added. # Rails.application.config.assets.precompile += %w( search.js )
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/initializers/backtrace_silencers.rb
test/dummy/config/initializers/backtrace_silencers.rb
# Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/initializers/mime_types.rb
test/dummy/config/initializers/mime_types.rb
# Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/environments/test.rb
test/dummy/config/environments/test.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure static file server for tests with Cache-Control for performance. config.serve_static_files = true config.static_cache_control = 'public, max-age=3600' # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Tell Action Mailer not to deliver emails to the real world. # The :test delivery method accumulates sent emails in the # ActionMailer::Base.deliveries array. config.action_mailer.delivery_method = :test # Randomize the order test cases are executed. config.active_support.test_order = :random # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/environments/development.rb
test/dummy/config/environments/development.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Don't care if the mailer can't send. config.action_mailer.raise_delivery_errors = false # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raise an error on page load if there are pending migrations. config.active_record.migration_error = :page_load # Debug mode disables concatenation and preprocessing of assets. # This option may cause significant delays in view rendering with a large # number of complex assets. config.assets.debug = true # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # Adds additional error checking when serving assets at runtime. # Checks for improperly declared sprockets dependencies. # Raises helpful error messages. config.assets.raise_runtime_errors = true # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/test/dummy/config/environments/production.rb
test/dummy/config/environments/production.rb
Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Enable Rack::Cache to put a simple HTTP cache in front of your application # Add `rack-cache` to your Gemfile before enabling this. # For large-scale production use, consider using a caching reverse proxy like # NGINX, varnish or squid. # config.action_dispatch.rack_cache = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.serve_static_files = ENV['RAILS_SERVE_STATIC_FILES'].present? # Compress JavaScripts and CSS. config.assets.js_compressor = :uglifier # config.assets.css_compressor = :sass # Do not fallback to assets pipeline if a precompiled asset is missed. config.assets.compile = false # Asset digests allow you to set far-future HTTP expiration dates on all assets, # yet still be able to expire them through the digest params. config.assets.digest = true # `config.assets.precompile` and `config.assets.version` have moved to config/initializers/assets.rb # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. # config.log_tags = [ :subdomain, :uuid ] # Use a different logger for distributed setups. # config.logger = ActiveSupport::TaggedLogging.new(SyslogLogger.new) # Use a different cache store in production. # config.cache_store = :mem_cache_store # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Ignore bad email addresses and do not raise email delivery errors. # Set this to true and configure the email server for immediate delivery to raise delivery errors. # config.action_mailer.raise_delivery_errors = false # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Do not dump schema after migrations. config.active_record.dump_schema_after_migration = false end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/lib/simple_recommender.rb
lib/simple_recommender.rb
require 'simple_recommender/version' require 'simple_recommender/recommendable' module SimpleRecommender end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/lib/simple_recommender/version.rb
lib/simple_recommender/version.rb
module SimpleRecommender VERSION = "0.0.3" end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
geoffreylitt/simple_recommender
https://github.com/geoffreylitt/simple_recommender/blob/4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b/lib/simple_recommender/recommendable.rb
lib/simple_recommender/recommendable.rb
module SimpleRecommender module Recommendable extend ActiveSupport::Concern DEFAULT_N_RESULTS = 10 SIMILARITY_KEY = "similarity" # todo: allow renaming to avoid conflicts AssociationMetadata = Struct.new(:join_table, :foreign_key, :association_foreign_key) module ClassMethods def similar_by(association_name) define_method :similar_items do |n_results: DEFAULT_N_RESULTS| query = similar_query( association_name: association_name, n_results: n_results ) self.class.find_by_sql(query) end end end included do private # Returns database metadata about an association based on its type, # used in constructing a similarity query based on that association def association_metadata(reflection) case reflection when ActiveRecord::Reflection::HasAndBelongsToManyReflection AssociationMetadata.new( reflection.join_table, reflection.foreign_key, reflection.association_foreign_key ) when ActiveRecord::Reflection::ThroughReflection AssociationMetadata.new( reflection.through_reflection.table_name, reflection.through_reflection.foreign_key, reflection.association_foreign_key ) else raise ArgumentError, "Association '#{reflection.name}' is not a supported type" end end # Returns a Postgres query that can be executed to return similar items. # Reflects on the association to get relevant table names, and then # uses Postgres's integer array intersection/union operators to # efficiently compute a Jaccard similarity metric between this item # and all other items in the table. def similar_query(association_name:, n_results:) reflection = self.class.reflect_on_association(association_name) if reflection.nil? raise ArgumentError, "Could not find association #{association_name}" end metadata = association_metadata(reflection) join_table = metadata[:join_table] fkey = metadata[:foreign_key] assoc_fkey = metadata[:association_foreign_key] this_table = self.class.table_name <<-SQL WITH similar_items AS ( SELECT t2.#{fkey}, (# (array_agg(DISTINCT t1.#{assoc_fkey}) & array_agg(DISTINCT t2.#{assoc_fkey})))::float/ (# (array_agg(DISTINCT t1.#{assoc_fkey}) | array_agg(DISTINCT t2.#{assoc_fkey})))::float as similarity FROM #{join_table} AS t1, #{join_table} AS t2 WHERE t1.#{fkey} = #{id} and t2.#{fkey} != #{id} GROUP BY t2.#{fkey} ORDER BY similarity DESC LIMIT #{n_results} ) SELECT #{this_table}.*, similarity FROM similar_items JOIN #{this_table} ON #{this_table}.id = similar_items.#{fkey} ORDER BY similarity DESC; SQL end end end end
ruby
MIT
4f65be3fdadce3566d2e1bcc5ca8b71c9d2f921b
2026-01-04T17:51:59.199045Z
false
samuelkadolph/unicorn-rails
https://github.com/samuelkadolph/unicorn-rails/blob/cb99f633c41de21277627207f72cc19d4e11f0d4/.gemspec.rb
.gemspec.rb
class Readme < String attr_reader :path def initialize(path) @path = path super(File.read(self.path)) end def summary if self =~ /^# (?:\S+)\s+(.+?)\s{2,}/m scrub $1 else raise "could not find summary in #{path}" end end def description if self =~ /^## Description\s+(.+?)\s{2,}/m scrub $1 else raise "could not find description in #{path}" end end private def scrub(string) string.delete("\\`").gsub(/\[([^\]]+)\]\([^)]*\)/, "\\1").tr("\n", " ").to_s end end def readme(path = File.expand_path("./README.md")) (@readmes ||= {})[path] ||= Readme.new(path) end
ruby
MIT
cb99f633c41de21277627207f72cc19d4e11f0d4
2026-01-04T17:51:58.572480Z
false
samuelkadolph/unicorn-rails
https://github.com/samuelkadolph/unicorn-rails/blob/cb99f633c41de21277627207f72cc19d4e11f0d4/lib/unicorn_rails.rb
lib/unicorn_rails.rb
require "unicorn" require "unicorn/launcher" module UnicornRails require "unicorn_rails/version" end module Rack module Handler class Unicorn class << self def run(app, options = {}) unicorn_options = { :listeners => ["#{options[:Host]}:#{options[:Port]}"] } if ::File.exist?("config/unicorn/#{environment}.rb") unicorn_options[:config_file] = "config/unicorn/#{environment}.rb" elsif ::File.exist?("config/unicorn.rb") unicorn_options[:config_file] = "config/unicorn.rb" else unicorn_options[:timeout] = 31 * 24 * 60 * 60 unicorn_options[:worker_processes] = (ENV["UNICORN_WORKERS"] || "1").to_i end if unicorn_options[:config_file] if ::File.read(unicorn_options[:config_file]) =~ /^(\s*)listen\s/ unicorn_options.delete(:listeners) end end ::Unicorn::Launcher.daemonize!(unicorn_options) if options[:daemonize] ::Unicorn::HttpServer.new(app, unicorn_options).start.join end def environment ENV["RACK_ENV"] || ENV["RAILS_ENV"] end end end register "unicorn", "Rack::Handler::Unicorn" def self.default(options = {}) Rack::Handler::Unicorn end end end
ruby
MIT
cb99f633c41de21277627207f72cc19d4e11f0d4
2026-01-04T17:51:58.572480Z
false
samuelkadolph/unicorn-rails
https://github.com/samuelkadolph/unicorn-rails/blob/cb99f633c41de21277627207f72cc19d4e11f0d4/lib/unicorn-rails.rb
lib/unicorn-rails.rb
require "unicorn_rails"
ruby
MIT
cb99f633c41de21277627207f72cc19d4e11f0d4
2026-01-04T17:51:58.572480Z
false
samuelkadolph/unicorn-rails
https://github.com/samuelkadolph/unicorn-rails/blob/cb99f633c41de21277627207f72cc19d4e11f0d4/lib/unicorn_rails/version.rb
lib/unicorn_rails/version.rb
module UnicornRails VERSION = "2.2.1" end
ruby
MIT
cb99f633c41de21277627207f72cc19d4e11f0d4
2026-01-04T17:51:58.572480Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/spec/spec_helper.rb
spec/spec_helper.rb
if ENV['TRAVIS'] require 'simplecov' require 'coveralls' SimpleCov.formatter = Coveralls::SimpleCov::Formatter SimpleCov.start do add_filter "spec/" end end require 'tempfile' require 'miam' Aws.config.update( access_key_id: ENV['MIAM_TEST_ACCESS_KEY_ID'] || 'scott', secret_access_key: ENV['MIAM_TEST_SECRET_ACCESS_KEY'] || 'tiger' ) MIAM_TEST_ACCOUNT_ID = Aws::IAM::Client.new.get_user.user.user_id RSpec.configure do |config| config.before(:each) do apply { '' } end config.after(:all) do apply { '' } end end def client(user_options = {}) options = { logger: Logger.new('/dev/null'), no_progress: true } options[:password_manager] = Miam::PasswordManager.new('/dev/null', options) if_debug do logger = Miam::Logger.instance logger.set_debug(true) options.update( debug: true, logger: logger, aws_config: { http_wire_trace: true, logger: logger } ) end options = options.merge(user_options) Miam::Client.new(options) end def tempfile(content, options = {}) basename = "#{File.basename __FILE__}.#{$$}" basename = [basename, options[:ext]] if options[:ext] Tempfile.open(basename) do |f| f.puts(content) f.flush f.rewind yield(f) end end def apply(cli = client) result = tempfile(yield) do |f| begin cli.apply(f.path) rescue Aws::IAM::Errors::EntityTemporarilyUnmodifiable, Aws::IAM::Errors::Throttling, Aws::IAM::Errors::NoSuchEntity sleep 3 retry end end sleep ENV['APPLY_WAIT'].to_i result end def export(options = {}) options = {no_progress: true}.merge(options) cli = options.delete(:client) || Aws::IAM::Client.new Miam::Exporter.export(cli, options)[0] end def if_debug yield if ENV['DEBUG'] == '1' end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/spec/miam/target_spec.rb
spec/miam/target_spec.rb
describe 'target option' do let(:dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end before(:each) do apply { dsl } end context 'when target a user' do let(:target_bob) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end RUBY end subject { client(target: [/bob/]) } it do updated = apply(subject) { target_bob } expect(updated).to be_falsey end end context 'when target a group, a role and an instance profile' do let(:target_admin_and_my) do <<-RUBY group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client(target: [/Admin/, /^my-/]) } it do updated = apply(subject) { target_admin_and_my } expect(updated).to be_falsey end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/spec/miam/update_spec.rb
spec/miam/update_spec.rb
describe 'update' do let(:dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end let(:expected) do {:users=> {"bob"=> {:path=>"/developer/", :groups=>["Admin", "SES"], :attached_managed_policies=>[], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}, :login_profile=>{:password_reset_required=>true}}, "mary"=> {:path=>"/staff/", :groups=>[], :attached_managed_policies=>[], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}}}, :groups=> {"Admin"=> {:path=>"/admin/", :attached_managed_policies=>[], :policies=> {"Admin"=> {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]}}}, "SES"=> {:path=>"/ses/", :attached_managed_policies=>[], :policies=> {"ses-policy"=> {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]}}}}, :policies=>{}, :roles=> {"my-role"=> {:path=>"/any/", :assume_role_policy_document=> {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]}, :instance_profiles=>["my-instance-profile"], :max_session_duration=>3600, :attached_managed_policies=>[], :policies=> {"role-policy"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}}}, :instance_profiles=>{"my-instance-profile"=>{:path=>"/profile/"}}} end before(:each) do apply { dsl } end context 'when no change' do subject { client } it do updated = apply(subject) { dsl } expect(updated).to be_falsey expect(export).to eq expected end end context 'when update policy' do let(:update_policy_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:Put*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:Put*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { update_policy_dsl } expect(updated).to be_truthy expected[:users]["mary"][:policies]["S3"]["Statement"][0]["Action"] = ["s3:Get*", "s3:List*", "s3:Put*"] expected[:groups]["SES"][:policies]["ses-policy"]["Statement"][0]["Action"] = "*" expected[:roles]["my-role"][:policies]["role-policy"]["Statement"][0]["Action"] = ["s3:Get*", "s3:List*", "s3:Put*"] expect(export).to eq expected end end context 'when update path' do let(:update_path_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/xstaff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { update_path_dsl } expect(updated).to be_truthy expected[:users]["mary"][:path] = "/xstaff/" expected[:groups]["SES"][:path] = "/ses/ses/" expect(export).to eq expected end end context 'when update path (role, instance_profile)' do let(:cannot_update_path_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/xxx/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/xxx/" RUBY end let(:logger) do logger = Logger.new('/dev/null') expect(logger).to receive(:warn).with("[WARN] Role `my-role`: 'path' cannot be updated") expect(logger).to receive(:warn).with("[WARN] InstanceProfile `my-instance-profile`: 'path' cannot be updated") logger end subject { client(logger: logger) } it do updated = apply(subject) { cannot_update_path_dsl } expect(updated).to be_falsey expect(export).to eq expected end end context 'when update assume_role_policy' do let(:update_assume_role_policy_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"SID", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { update_assume_role_policy_dsl } expect(updated).to be_truthy expected[:roles]["my-role"][:assume_role_policy_document]["Statement"][0]["Sid"] = "SID" expect(export).to eq expected end end context 'when update groups' do let(:update_groups_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { update_groups_dsl } expect(updated).to be_truthy expected[:users]["bob"][:groups] = ["Admin"] expected[:users]["mary"][:groups] = ["Admin", "SES"] expect(export).to eq expected end end context 'when update login_profile' do let(:update_login_profile_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>false groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { update_login_profile_dsl } expect(updated).to be_truthy expected[:users]["bob"][:login_profile][:password_reset_required] = false expect(export).to eq expected end end context 'when delete login_profile' do let(:delete_login_profile_dsl) do <<-RUBY user "bob", :path=>"/developer/" do groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { delete_login_profile_dsl } expect(updated).to be_truthy expected[:users]["bob"].delete(:login_profile) expect(export).to eq expected end end context 'when delete policy' do let(:delete_policy_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { delete_policy_dsl } expect(updated).to be_truthy expected[:users]["bob"][:policies].delete("S3") expected[:groups]["SES"][:policies].delete("ses-policy") expected[:roles]["my-role"][:policies].delete("role-policy") expect(export).to eq expected end end context 'when update instance_profiles' do let(:update_instance_profiles_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile2" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" instance_profile "my-instance-profile2", :path=>"/profile2/" RUBY end subject { client } it do updated = apply(subject) { update_instance_profiles_dsl } expect(updated).to be_truthy expected[:roles]["my-role"][:instance_profiles] = ["my-instance-profile2"] expected[:instance_profiles]["my-instance-profile2"] = {:path=>"/profile2/"} expect(export).to eq expected end end context 'when update role max_session_duration' do let(:update_instance_profiles_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) max_session_policy 43200 assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { update_instance_profiles_dsl } expect(updated).to be_truthy expected[:roles]["my-role"][:max_session_duration] = 43200 expect(export).to eq expected end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/spec/miam/attach_detach_policy_spec.rb
spec/miam/attach_detach_policy_spec.rb
describe 'attach/detach policy' do let(:dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end let(:expected) do {:users=> {"bob"=> {:path=>"/developer/", :groups=>["Admin", "SES"], :attached_managed_policies=>[ "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess"], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}, :login_profile=>{:password_reset_required=>true}}, "mary"=> {:path=>"/staff/", :groups=>[], :attached_managed_policies=>[ "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess"], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}}}, :groups=> {"Admin"=> {:path=>"/admin/", :attached_managed_policies=>[ "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess"], :policies=> {"Admin"=> {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]}}}, "SES"=> {:path=>"/ses/", :attached_managed_policies=>[ "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess"], :policies=> {"ses-policy"=> {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]}}}}, :policies=>{}, :roles=> {"my-role"=> {:path=>"/any/", :assume_role_policy_document=> {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]}, :instance_profiles=>["my-instance-profile"], :attached_managed_policies=>[ "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess"], :policies=> {"role-policy"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}}}, :instance_profiles=>{"my-instance-profile"=>{:path=>"/profile/"}}} end before(:each) do apply { dsl } end context 'when no change' do subject { client } it do updated = apply(subject) { dsl } expect(updated).to be_falsey expect(export).to eq expected end end context 'when attach policy' do let(:update_policy_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess", "arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess" ) end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess", "arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess" ) end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess", "arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess" ) end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { update_policy_dsl } expect(updated).to be_truthy expected[:users]["mary"][:attached_managed_policies] << "arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess" expected[:groups]["SES"][:attached_managed_policies] << "arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess" expected[:roles]["my-role"][:attached_managed_policies] << "arn:aws:iam::aws:policy/AmazonRDSReadOnlyAccess" expect(export).to eq expected end end context 'when detach policy' do let(:update_policy_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( ) end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end attached_managed_policies( ) end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( ) end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { update_policy_dsl } expect(updated).to be_truthy expected[:users]["mary"][:attached_managed_policies].clear expected[:groups]["SES"][:attached_managed_policies].clear expected[:roles]["my-role"][:attached_managed_policies].clear expect(export).to eq expected end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/spec/miam/delete_spec.rb
spec/miam/delete_spec.rb
describe 'delete' do let(:dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end let(:expected) do {:users=> {"bob"=> {:path=>"/developer/", :groups=>["Admin", "SES"], :attached_managed_policies=>[], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}, :login_profile=>{:password_reset_required=>true}}, "mary"=> {:path=>"/staff/", :groups=>[], :attached_managed_policies=>[], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}}}, :groups=> {"Admin"=> {:path=>"/admin/", :attached_managed_policies=>[], :policies=> {"Admin"=> {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]}}}, "SES"=> {:path=>"/ses/", :attached_managed_policies=>[], :policies=> {"ses-policy"=> {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]}}}}, :policies => {}, :roles=> {"my-role"=> {:path=>"/any/", :assume_role_policy_document=> {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]}, :instance_profiles=>["my-instance-profile"], :attached_managed_policies=>[], :policies=> {"role-policy"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}}}, :instance_profiles=>{"my-instance-profile"=>{:path=>"/profile/"}}} end before(:each) do apply { dsl } end context 'when delete group' do let(:delete_group_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { delete_group_dsl } expect(updated).to be_truthy expected[:users]["bob"][:groups] = ["Admin"] expected[:groups].delete("SES") expect(export).to eq expected end end context 'when delete user' do let(:delete_user_dsl) do <<-RUBY user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { delete_user_dsl } expect(updated).to be_truthy expected[:users].delete("bob") expect(export).to eq expected end end context 'when delete user_and_group' do let(:delete_user_and_group_dsl) do <<-RUBY user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end context 'when apply' do subject { client } it do updated = apply(subject) { delete_user_and_group_dsl } expect(updated).to be_truthy expected[:users].delete("bob") expected[:groups].delete("SES") expect(export).to eq expected end end context 'when dry-run' do subject { client(dry_run: true) } it do updated = apply(subject) { delete_user_and_group_dsl } expect(updated).to be_falsey expect(export).to eq expected end end end context 'when delete instance_profile' do let(:delete_instance_profiles_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end RUBY end subject { client } it do updated = apply(subject) { delete_instance_profiles_dsl } expect(updated).to be_truthy expected[:roles]["my-role"][:instance_profiles] = [] expected[:instance_profiles].delete("my-instance-profile") expect(export).to eq expected end end context 'when delete role' do let(:delete_role_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { delete_role_dsl } expect(updated).to be_truthy expected[:roles].delete("my-role") expect(export).to eq expected end end context 'when delete role and instance_profile' do let(:delete_role_and_instance_profile_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end RUBY end subject { client } it do updated = apply(subject) { delete_role_and_instance_profile_dsl } expect(updated).to be_truthy expected[:roles].delete("my-role") expected[:instance_profiles].delete("my-instance-profile") expect(export).to eq expected end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/spec/miam/ignore_login_profile_spec.rb
spec/miam/ignore_login_profile_spec.rb
describe 'ignore login profile' do let(:dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end RUBY end let(:update_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>false policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*", "s3:Put*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end RUBY end let(:expected) do {:users=> {"bob"=> {:path=>"/developer/", :groups=>[], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*", "s3:Put*"], "Effect"=>"Allow", "Resource"=>"*"}]}}, :attached_managed_policies=>[], :login_profile=>{:password_reset_required=>true}}}, :groups=>{}, :policies=>{}, :roles=>{}, :instance_profiles=>{}} end before(:each) do apply { dsl } end context 'when no change' do subject { client(ignore_login_profile: true) } it do updated = apply(subject) { update_dsl } expect(updated).to be_truthy expect(export).to eq expected end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/spec/miam/create_spec.rb
spec/miam/create_spec.rb
describe 'create' do context 'when empty' do subject { client } it do updated = apply(subject) { '' } expect(updated).to be_falsey expect(export).to eq({:users=>{}, :groups=>{}, :roles=>{}, :instance_profiles=>{}, :policies => {}}) end end context 'when create user and group' do let(:dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end context 'when apply' do subject { client } let(:expected) do {:users=> {"bob"=> {:path=>"/developer/", :groups=>["Admin", "SES"], :attached_managed_policies=>[], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}, :login_profile=>{:password_reset_required=>true}}, "mary"=> {:path=>"/staff/", :groups=>[], :attached_managed_policies=>[], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}}}, :groups=> {"Admin"=> {:path=>"/admin/", :attached_managed_policies=>[], :policies=> {"Admin"=> {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]}}}, "SES"=> {:path=>"/ses/", :attached_managed_policies=>[], :policies=> {"ses-policy"=> {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]}}}}, :policies => {}, :roles=> {"my-role"=> {:path=>"/any/", :assume_role_policy_document=> {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]}, :instance_profiles=>["my-instance-profile"], :attached_managed_policies=>[], :policies=> {"role-policy"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}}}, :instance_profiles=>{"my-instance-profile"=>{:path=>"/profile/"}}} end it do updated = apply(subject) { dsl } expect(updated).to be_truthy expect(export).to eq expected end context 'when using template' do let(:dsl) do <<-RUBY template "bob" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end template "mary" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "bob", :path=>"/developer/" do include_template context.user_name end user "mary", :path=>"/staff/" do include_template context.user_name end template "Admin" do policy context.policy_name do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end template "SES" do policy context.policy_name do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do include_template context.group_name, policy_name: "Admin" end group "SES", :path=>"/ses/" do context.policy_name = "ses-policy" include_template context.group_name end template "my-role" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do include_template context.role_name end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end it do updated = apply(subject) { dsl } expect(updated).to be_truthy expect(export).to eq expected end end end context 'when dry-run' do subject { client(dry_run: true) } it do updated = apply(subject) { dsl } expect(updated).to be_falsey expect(export).to eq({:users=>{}, :groups=>{}, :roles=>{}, :instance_profiles=>{}, :policies => {}}) end end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/spec/miam/rename_spec.rb
spec/miam/rename_spec.rb
describe 'update' do let(:dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end let(:expected) do {:users=> {"bob"=> {:path=>"/developer/", :groups=>["Admin", "SES"], :attached_managed_policies=>[], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}, :login_profile=>{:password_reset_required=>true}}, "mary"=> {:path=>"/staff/", :groups=>[], :attached_managed_policies=>[], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}}}, :groups=> {"Admin"=> {:path=>"/admin/", :attached_managed_policies=>[], :policies=> {"Admin"=> {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]}}}, "SES"=> {:path=>"/ses/", :attached_managed_policies=>[], :policies=> {"ses-policy"=> {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]}}}}, :policies => {}, :roles=> {"my-role"=> {:path=>"/any/", :assume_role_policy_document=> {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]}, :instance_profiles=>["my-instance-profile"], :attached_managed_policies=>[], :policies=> {"role-policy"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}}}, :instance_profiles=>{"my-instance-profile"=>{:path=>"/profile/"}}} end before(:each) do apply { dsl } end context 'when rename user' do let(:rename_user_dsl) do <<-RUBY user "bob2", :path=>"/developer/", :renamed_from=>"bob" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { rename_user_dsl } expect(updated).to be_truthy expected[:users]["bob2"] = expected[:users].delete("bob") expect(export).to eq expected end end context 'when rename group' do let(:rename_group_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES2" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES2", :path=>"/ses/", :renamed_from=>"SES2" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { rename_group_dsl } expect(updated).to be_truthy expected[:users]["bob"][:groups] = ["Admin", "SES2"] expected[:groups]["SES2"] = expected[:groups].delete("SES") expect(export).to eq expected end end context 'when rename without renamed_from' do let(:rename_without_renamed_from_dsl) do <<-RUBY user "bob2", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES2" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES2", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { rename_without_renamed_from_dsl } expect(updated).to be_truthy expected[:users]["bob"][:groups] = ["Admin", "SES2"] expected[:users]["bob2"] = expected[:users].delete("bob") expected[:groups]["SES2"] = expected[:groups].delete("SES") expect(export).to eq expected end end context 'when rename role and instance_profile' do let(:rename_role_and_instance_profile_dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end end role "my-role2", :path=>"/any/" do instance_profiles( "my-instance-profile2" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end end instance_profile "my-instance-profile2", :path=>"/profile/" RUBY end subject { client } it do updated = apply(subject) { rename_role_and_instance_profile_dsl } expect(updated).to be_truthy expected[:roles]["my-role"][:instance_profiles] = ["my-instance-profile2"] expected[:roles]["my-role2"] = expected[:roles].delete("my-role") expected[:instance_profiles]["my-instance-profile2"] = expected[:instance_profiles].delete("my-instance-profile") expect(export).to eq expected end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/spec/miam/hash_ext_spec.rb
spec/miam/hash_ext_spec.rb
describe 'Hash#sort_array!' do let(:hash) do {:users=> {"bob"=> {:path=>"/developer/", :groups=>[], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Put*", "s3:List*", "s3:Get*"], "Effect"=>"Allow", "Resource"=>"*"}]}}, :attached_managed_policies=>[ "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess", "arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess"], :login_profile=>{:password_reset_required=>true}}}} end let(:expected_hash) do {:users=> {"bob"=> {:path=>"/developer/", :groups=>[], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*", "s3:Put*"], "Effect"=>"Allow", "Resource"=>"*"}]}}, :attached_managed_policies=>[ "arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess", "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess"], :login_profile=>{:password_reset_required=>true}}}} end subject { hash.sort_array! } it { is_expected.to eq expected_hash } context 'on trust policy' do let(:expected_trust_policy) do { 'Version' => '2012-10-17', 'Statement' => [ { 'Action' => 'sts:AssumeRole', 'Effect' => 'Allow', 'Principal' => { 'AWS' => 'arn:aws:iam::111122223333:role/Role1', }, 'Sid' => 'sid1', }, { 'Effect' => 'Allow', 'Principal' => { 'Federated' => 'arn:aws:iam::111122223333:oidc-provider/oidc.eks.ap-northeast-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE', }, 'Action' => 'sts:AssumeRoleWithWebIdentity', 'Condition' => { 'StringEquals' => { 'oidc.eks.ap-northeast-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:sub' => 'system:serviceaccount:default:miam', 'oidc.eks.ap-northeast-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:aud' => 'sts.amazonaws.com', }, }, }, ], } end let(:actual_trust_policy) do { 'Version' => '2012-10-17', 'Statement' => [ { # Only the order of key-value pairs below are different 'Sid' => 'sid1', 'Effect' => 'Allow', 'Principal' => { 'AWS' => 'arn:aws:iam::111122223333:role/Role1', }, 'Action' => 'sts:AssumeRole', }, { 'Effect' => 'Allow', 'Principal' => { 'Federated' => 'arn:aws:iam::111122223333:oidc-provider/oidc.eks.ap-northeast-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE', }, 'Action' => 'sts:AssumeRoleWithWebIdentity', 'Condition' => { 'StringEquals' => { 'oidc.eks.ap-northeast-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:sub' => 'system:serviceaccount:default:miam', 'oidc.eks.ap-northeast-1.amazonaws.com/id/EXAMPLED539D4633E53DE1B71EXAMPLE:aud' => 'sts.amazonaws.com', }, }, }, ], } end it 'ignores the order of Hash entries' do expected_trust_policy.sort_array! actual_trust_policy.sort_array! expect(expected_trust_policy).to eq(actual_trust_policy) end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/spec/miam/exclude_spec.rb
spec/miam/exclude_spec.rb
describe 'exclude option' do let(:dsl) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end before(:each) do apply { dsl } end context 'when exclude a user' do let(:exclude_bob) do <<-RUBY user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end group "Admin", :path=>"/admin/" do policy "Admin" do {"Statement"=>[{"Effect"=>"Allow", "Action"=>"*", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end role "my-role", :path=>"/any/" do instance_profiles( "my-instance-profile" ) assume_role_policy_document do {"Version"=>"2012-10-17", "Statement"=> [{"Sid"=>"", "Effect"=>"Allow", "Principal"=>{"Service"=>"ec2.amazonaws.com"}, "Action"=>"sts:AssumeRole"}]} end policy "role-policy" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end instance_profile "my-instance-profile", :path=>"/profile/" RUBY end subject { client(exclude: [/bob/]) } it do updated = apply(subject) { exclude_bob } expect(updated).to be_falsey end end context 'when exclude a group, a role and an instance profile' do let(:exclude_admin_and_my) do <<-RUBY user "bob", :path=>"/developer/" do login_profile :password_reset_required=>true groups( "Admin", "SES" ) policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end group "SES", :path=>"/ses/" do policy "ses-policy" do {"Statement"=> [{"Effect"=>"Allow", "Action"=>"ses:SendRawEmail", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::aws:policy/AmazonElastiCacheReadOnlyAccess" ) end RUBY end subject { client(exclude: [/Admin/, /^my-/]) } it do updated = apply(subject) { exclude_admin_and_my } expect(updated).to be_falsey end end context 'when specifying exclude option in a DSL' do let(:exclude_everything) do <<-RUBY exclude /.*/ RUBY end subject { client(exclude: []) } it do updated = apply(subject) { exclude_everything } expect(updated).to be_falsey end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/spec/miam/custom_managed_policy_spec.rb
spec/miam/custom_managed_policy_spec.rb
describe 'custom managed policy' do let(:dsl) do <<-RUBY managed_policy "my-policy", :path=>"/" do {"Version"=>"2012-10-17", "Statement"=> [{"Effect"=>"Allow", "Action"=>"directconnect:Describe*", "Resource"=>"*"}]} end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::#{MIAM_TEST_ACCOUNT_ID}:policy/my-policy" ) end RUBY end let(:expected) do {:users=> {"mary"=> {:path=>"/staff/", :groups=>[], :attached_managed_policies=>[ "arn:aws:iam::#{MIAM_TEST_ACCOUNT_ID}:policy/my-policy"], :policies=> {"S3"=> {"Statement"=> [{"Action"=>["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]}}}}, :groups=>{}, :instance_profiles=>{}, :policies=> {"my-policy"=> {:path=>"/", :document=> {"Version"=>"2012-10-17", "Statement"=> [{"Effect"=>"Allow", "Action"=>"directconnect:Describe*", "Resource"=>"*"}]}}}, :roles=>{}} end before(:each) do apply { dsl } end context 'when no change' do subject { client } it do updated = apply(subject) { dsl } expect(updated).to be_falsey expect(export).to eq expected end end context 'when create and attach' do subject { client } it do updated = apply(subject) { <<-RUBY managed_policy "my-policy", :path=>"/" do {"Version"=>"2012-10-17", "Statement"=> [{"Effect"=>"Allow", "Action"=>"directconnect:Describe*", "Resource"=>"*"}]} end managed_policy "my-policy2", :path=>"/" do {"Version"=>"2012-10-17", "Statement"=> [{"Effect"=>"Deny", "Action"=>"directconnect:Describe*", "Resource"=>"*"}]} end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::#{MIAM_TEST_ACCOUNT_ID}:policy/my-policy", "arn:aws:iam::#{MIAM_TEST_ACCOUNT_ID}:policy/my-policy2" ) end RUBY } expect(updated).to be_truthy expected[:policies]["my-policy2"] = {:path=>"/", :document=>{"Version"=>"2012-10-17", "Statement"=>[{"Effect"=>"Deny", "Action"=>"directconnect:Describe*", "Resource"=>"*"}]}} expected[:users]["mary"][:attached_managed_policies] << "arn:aws:iam::#{MIAM_TEST_ACCOUNT_ID}:policy/my-policy2" expected[:users]["mary"][:attached_managed_policies].sort! actual = export actual[:users]["mary"][:attached_managed_policies].sort! expect(actual).to eq expected end end context 'when create and delete' do subject { client } it do updated = apply(subject) { <<-RUBY managed_policy "my-policy2", :path=>"/" do {"Version"=>"2012-10-17", "Statement"=> [{"Effect"=>"Deny", "Action"=>"directconnect:Describe*", "Resource"=>"*"}]} end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::#{MIAM_TEST_ACCOUNT_ID}:policy/my-policy2" ) end RUBY } expect(updated).to be_truthy expected[:policies] = {"my-policy2" => {:path=>"/", :document=>{"Version"=>"2012-10-17", "Statement"=>[{"Effect"=>"Deny", "Action"=>"directconnect:Describe*", "Resource"=>"*"}]}}} expected[:users]["mary"][:attached_managed_policies] = ["arn:aws:iam::#{MIAM_TEST_ACCOUNT_ID}:policy/my-policy2"] expect(export).to eq expected end end context 'when update' do subject { client } it do updated = apply(subject) { <<-RUBY managed_policy "my-policy", :path=>"/" do {"Version"=>"2012-10-17", "Statement"=> [{"Effect"=>"Deny", "Action"=>"directconnect:*", "Resource"=>"*"}]} end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::#{MIAM_TEST_ACCOUNT_ID}:policy/my-policy" ) end RUBY } expect(updated).to be_truthy expected[:policies]["my-policy"] = {:path=>"/", :document=>{"Version"=>"2012-10-17", "Statement"=>[{"Effect"=>"Deny", "Action"=>"directconnect:*", "Resource"=>"*"}]}} expect(export).to eq expected end end context 'when update 7 times' do subject { client } it do 4.times do apply(subject) { dsl } apply(subject) { <<-RUBY managed_policy "my-policy", :path=>"/" do {"Version"=>"2012-10-17", "Statement"=> [{"Effect"=>"Deny", "Action"=>"directconnect:*", "Resource"=>"*"}]} end user "mary", :path=>"/staff/" do policy "S3" do {"Statement"=> [{"Action"=> ["s3:Get*", "s3:List*"], "Effect"=>"Allow", "Resource"=>"*"}]} end attached_managed_policies( "arn:aws:iam::#{MIAM_TEST_ACCOUNT_ID}:policy/my-policy" ) end RUBY } end expected[:policies]["my-policy"] = {:path=>"/", :document=>{"Version"=>"2012-10-17", "Statement"=>[{"Effect"=>"Deny", "Action"=>"directconnect:*", "Resource"=>"*"}]}} expect(export).to eq expected end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam.rb
lib/miam.rb
require 'cgi' require 'json' require 'logger' require 'pp' require 'singleton' require 'thread' require 'aws-sdk-iam' Aws.use_bundled_cert! require 'ruby-progressbar' require 'parallel' require 'term/ansicolor' require 'diffy' require 'hashie' module Miam; end require 'miam/string_helper' require 'miam/ext/hash_ext' require 'miam/logger' require 'miam/template_helper' require 'miam/client' require 'miam/driver' require 'miam/dsl' require 'miam/dsl/context' require 'miam/dsl/context/group' require 'miam/dsl/context/managed_policy' require 'miam/dsl/context/role' require 'miam/dsl/context/user' require 'miam/dsl/converter' require 'miam/exporter' require 'miam/password_manager' require 'miam/utils' require 'miam/version'
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/version.rb
lib/miam/version.rb
module Miam VERSION = '0.2.5.beta1' end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/password_manager.rb
lib/miam/password_manager.rb
class Miam::PasswordManager include Miam::Logger::Helper LOWERCASES = ('a'..'z').to_a UPPERCASES = ('A'..'Z').to_a NUMBERS = ('0'..'9').to_a SYMBOLS = "!@\#$%^&*()_+-=[]{}|'".split(//) def initialize(output, options = {}) @output = output @options = options end def identify(user, type, policy) password = mkpasswd(policy) log(:debug, "mkpasswd: #{password}") puts_password(user, type, password) password end def puts_password(user, type, password) log(:info, "User `#{user}` > `#{type}`: put password to `#{@output}`") open_output do |f| f.puts("#{user},#{type},#{password}") end end private def mkpasswd(policy) chars = [] len = 8 if policy len = policy.minimum_password_length if policy.minimum_password_length > len chars << LOWERCASES.shuffle.first if policy.require_lowercase_characters chars << UPPERCASES.shuffle.first if policy.require_uppercase_characters chars << NUMBERS.shuffle.first if policy.require_numbers chars << SYMBOLS.shuffle.first if policy.require_symbols len -= chars.length end (chars + [*1..9, *'A'..'Z', *'a'..'z'].shuffle.slice(0, len)).shuffle.join end def open_output return if @options[:dry_run] if @output == '-' yield($stdout) $stdout.flush else open(@output, 'a') do |f| yield(f) end end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/string_helper.rb
lib/miam/string_helper.rb
module Miam module StringHelper @colorize = false class << self def colorize=(value) @colorize = value end def colorize @colorize end Term::ANSIColor::Attribute.named_attributes.map do |attribute| define_method(attribute.name) do |str| if colorize Term::ANSIColor.public_send(attribute.name, str) else str end end end end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/logger.rb
lib/miam/logger.rb
class Miam::Logger < ::Logger include Singleton def initialize super($stdout) self.formatter = proc do |severity, datetime, progname, msg| "#{msg}\n" end self.level = Logger::INFO end def set_debug(value) self.level = value ? Logger::DEBUG : Logger::INFO end module Helper def log(level, message, log_options = {}) message = "[#{level.to_s.upcase}] #{message}" unless level == :info message << ' (dry-run)' if @options[:dry_run] message = Miam::StringHelper.public_send(log_options[:color], message) if log_options[:color] logger = @options[:logger] || Miam::Logger.instance logger.send(level, message) end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/exporter.rb
lib/miam/exporter.rb
# coding: utf-8 class Miam::Exporter AWS_MANAGED_POLICY_PREFIX = 'arn:aws:iam::aws:' AWS_CN_MANAGED_POLICY_PREFIX = 'arn:aws-cn:iam::aws:' def self.export(iam, options = {}) self.new(iam, options).export end def initialize(iam, options = {}) @iam = iam @options = options @mutex = Mutex.new @concurrency = options[:export_concurrency] || 16 end def export account_authorization_details = get_account_authorization_details users = account_authorization_details[:user_detail_list] groups = account_authorization_details[:group_detail_list] roles = account_authorization_details[:role_detail_list] policies = account_authorization_details[:policies] instance_profiles = list_instance_profiles group_users = {} instance_profile_roles = {} unless @options[:no_progress] progress_total = users.length + groups.length + roles.length + instance_profiles.length @progressbar = ProgressBar.create( :format => ' %bᗧ%i %p%%', :progress_mark => ' ', :remainder_mark => '・', :total => progress_total, :output => $stderr) end expected = { :users => export_users(users, group_users), :groups => export_groups(groups), :roles => export_roles(roles, instance_profile_roles), :instance_profiles => export_instance_profiles(instance_profiles), :policies => export_policies(policies), } [expected, group_users, instance_profile_roles] end private def export_users(users, group_users) result = {} Parallel.each(users, :in_threads => @concurrency) do |user| user_name = user.user_name groups = user.group_list policies = export_user_policies(user) login_profile = export_login_profile(user_name) attached_managed_policies = user.attached_managed_policies.map(&:policy_arn) @mutex.synchronize do groups.each do |group_name| group_users[group_name] ||= [] group_users[group_name] << user_name end result[user_name] = { :path => user.path, :groups => groups, :policies => policies, :attached_managed_policies => attached_managed_policies } if login_profile result[user_name][:login_profile] = login_profile end progress end end result end def export_user_policies(user) result = {} user.user_policy_list.each do |policy| document = CGI.unescape(policy.policy_document) result[policy.policy_name] = JSON.parse(document) end result end def export_login_profile(user_name) begin resp = @iam.get_login_profile(:user_name => user_name) {:password_reset_required => resp.login_profile.password_reset_required} rescue Aws::IAM::Errors::NoSuchEntity nil end end def export_groups(groups) result = {} Parallel.each(groups, :in_threads => @concurrency) do |group| group_name = group.group_name policies = export_group_policies(group) attached_managed_policies = group.attached_managed_policies.map(&:policy_arn) @mutex.synchronize do result[group_name] = { :path => group.path, :policies => policies, :attached_managed_policies => attached_managed_policies, } progress end end result end def export_group_policies(group) result = {} group.group_policy_list.each do |policy| document = CGI.unescape(policy.policy_document) result[policy.policy_name] = JSON.parse(document) end result end def export_roles(roles, instance_profile_roles) result = {} Parallel.each(roles, :in_threads => @concurrency) do |role| role_name = role.role_name instance_profiles = role.instance_profile_list.map {|i| i.instance_profile_name } policies = export_role_policies(role) attached_managed_policies = role.attached_managed_policies.map(&:policy_arn) role_data = @iam.get_role(role_name: role_name).role max_session_duration = role_data.max_session_duration @mutex.synchronize do instance_profiles.each do |instance_profile_name| instance_profile_roles[instance_profile_name] ||= [] instance_profile_roles[instance_profile_name] << role_name end document = CGI.unescape(role.assume_role_policy_document) result[role_name] = { :path => role.path, :assume_role_policy_document => JSON.parse(document), :instance_profiles => instance_profiles, :policies => policies, :attached_managed_policies => attached_managed_policies, :max_session_duration => max_session_duration, } progress end end result end def export_role_policies(role) result = {} role.role_policy_list.each do |policy| document = CGI.unescape(policy.policy_document) result[policy.policy_name] = JSON.parse(document) end result end def export_instance_profiles(instance_profiles) result = {} Parallel.each(instance_profiles, :in_threads => @concurrency) do |instance_profile| instance_profile_name = instance_profile.instance_profile_name @mutex.synchronize do result[instance_profile_name] = { :path => instance_profile.path, } progress end end result end def export_policies(policies) result = {} Parallel.each(policies, :in_threads => @concurrency) do |policy| if policy.arn.start_with?(AWS_MANAGED_POLICY_PREFIX) or policy.arn.start_with?(AWS_CN_MANAGED_POLICY_PREFIX) next end policy_name = policy.policy_name document = export_policy_document(policy) result[policy_name] = { :path => policy.path, :document => document, } end result end def export_policy_document(policy) policy_version = nil policy_version_list = policy.policy_version_list.sort_by do |pv| pv.version_id[1..-1].to_i end policy_version_list.each do |pv| policy_version = pv if pv.is_default_version break end end document = CGI.unescape(policy_version.document) JSON.parse(document) end def list_instance_profiles @iam.list_instance_profiles.map {|resp| resp.instance_profiles.to_a }.flatten end def get_account_authorization_details account_authorization_details = {} unless @options[:no_progress] progressbar = ProgressBar.create(:title => 'Loading', :total => nil, :output => $stderr) end keys = [ :user_detail_list, :group_detail_list, :role_detail_list, :policies, ] keys.each do |key| account_authorization_details[key] = [] end @iam.get_account_authorization_details.each do |resp| keys.each do |key| account_authorization_details[key].concat(resp[key]) end unless @options[:no_progress] progressbar.increment end end account_authorization_details end def progress @progressbar.increment if @progressbar end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/driver.rb
lib/miam/driver.rb
class Miam::Driver include Miam::Logger::Helper MAX_POLICY_SIZE = 2048 MAX_POLICY_VERSIONS = 5 def initialize(iam, sts, options = {}) @iam = iam @sts = sts @options = options @account_id = nil end def create_user(user_name, attrs) log(:info, "Create User `#{user_name}`", :color => :cyan) unless_dry_run do params = {:user_name => user_name} params[:path] = attrs[:path] if attrs[:path] @iam.create_user(params) end new_user_attrs = {:groups => [], :policies => {}, :attached_managed_policies => []} new_user_attrs[:path] = attrs[:path] if attrs[:path] new_user_attrs end def create_access_key(user_name) log(:info, "Create access key for User `#{user_name}`", :color => :cyan) access_key = nil unless_dry_run do resp = @iam.create_access_key(:user_name => user_name) access_key = { :access_key_id => resp.access_key.access_key_id, :secret_access_key => resp.access_key.secret_access_key, } end access_key end def delete_user(user_name, attrs) log(:info, "Delete User `#{user_name}`", :color => :red) unless_dry_run do if attrs[:login_profile] @iam.delete_login_profile(:user_name => user_name) end attrs[:policies].keys.each do |policy_name| @iam.delete_user_policy(:user_name => user_name, :policy_name => policy_name) end attrs[:groups].each do |group_name| @iam.remove_user_from_group(:group_name => group_name, :user_name => user_name) end attrs[:attached_managed_policies].each do |policy_arn| @iam.detach_user_policy(:user_name => user_name, :policy_arn => policy_arn) end list_access_key_ids(user_name).each do |access_key_id| @iam.delete_access_key(:user_name => user_name, :access_key_id => access_key_id) end list_signing_certificate_ids(user_name).each do |certificate_id| @iam.delete_signing_certificate(:user_name => user_name, :certificate_id => certificate_id) end mfa_devices = @iam.list_mfa_devices(:user_name => user_name).map {|resp| resp.mfa_devices }.flatten mfa_devices.each do |md| @iam.deactivate_mfa_device(:user_name => user_name, :serial_number => md.serial_number) end @iam.delete_user(:user_name => user_name) end end def create_login_profile(user_name, attrs) log_attrs = attrs.dup log_attrs.delete(:password) log(:info, "Update User `#{user_name}`", :color => :green) log(:info, " create login profile: #{log_attrs.inspect}", :color => :green) unless_dry_run do @iam.create_login_profile(attrs.merge(:user_name => user_name)) end end def delete_login_profile(user_name) log(:info, "Update User `#{user_name}`", :color => :green) log(:info, " delete login profile", :color => :green) unless_dry_run do @iam.delete_login_profile(:user_name => user_name) end end def update_login_profile(user_name, attrs, old_attrs) log_attrs = attrs.dup log_attrs.delete(:password) log(:info, "Update User `#{user_name}`", :color => :green) log(:info, Miam::StringHelper.green(" login profile:\n") + Miam::Utils.diff(old_attrs, attrs, :color => @options[:color], :indent => ' '), :color => false) unless_dry_run do @iam.update_login_profile(attrs.merge(:user_name => user_name)) end end def add_user_to_groups(user_name, group_names) log(:info, "Update User `#{user_name}`", :color => :green) log(:info, " add groups=#{group_names.join(',')}", :color => :green) unless_dry_run do group_names.each do |group_name| @iam.add_user_to_group(:group_name => group_name, :user_name => user_name) end end end def remove_user_from_groups(user_name, group_names) log(:info, "Update User `#{user_name}`", :color => :green) log(:info, " remove groups=#{group_names.join(',')}", :color => :green) unless_dry_run do group_names.each do |group_name| @iam.remove_user_from_group(:group_name => group_name, :user_name => user_name) end end end def create_group(group_name, attrs) log(:info, "Create Group `#{group_name}`", :color => :cyan) unless_dry_run do params = {:group_name => group_name} params[:path] = attrs[:path] if attrs[:path] @iam.create_group(params) end new_group_attrs = {:policies => {}, :attached_managed_policies => []} new_group_attrs[:path] = attrs[:path] if attrs[:path] new_group_attrs end def delete_group(group_name, attrs, users_in_group) log(:info, "Delete Group `#{group_name}`", :color => :red) unless_dry_run do attrs[:policies].keys.each do |policy_name| @iam.delete_group_policy(:group_name => group_name, :policy_name => policy_name) end users_in_group.each do |user_name| @iam.remove_user_from_group(:group_name => group_name, :user_name => user_name) end attrs[:attached_managed_policies].each do |policy_arn| @iam.detach_group_policy(:group_name => group_name, :policy_arn => policy_arn) end @iam.delete_group(:group_name => group_name) end end def create_role(role_name, attrs) log(:info, "Create Role `#{role_name}`", :color => :cyan) assume_role_policy_document = attrs.fetch(:assume_role_policy_document) unless_dry_run do params = { :role_name => role_name, :assume_role_policy_document => encode_document(assume_role_policy_document), :max_session_duration => attrs.fetch(:max_session_duration) } params[:path] = attrs[:path] if attrs[:path] @iam.create_role(params) end new_role_attrs = { :instance_profiles => [], :assume_role_policy_document => assume_role_policy_document, :policies => {}, :attached_managed_policies => [], :max_session_duration => attrs.fetch(:max_session_duration), } new_role_attrs[:path] = attrs[:path] if attrs[:path] new_role_attrs end def delete_role(role_name, instance_profile_names, attrs) log(:info, "Delete Role `#{role_name}`", :color => :red) unless_dry_run do attrs[:policies].keys.each do |policy_name| @iam.delete_role_policy(:role_name => role_name, :policy_name => policy_name) end instance_profile_names.each do |instance_profile_name| @iam.remove_role_from_instance_profile(:instance_profile_name => instance_profile_name, :role_name => role_name) end attrs[:attached_managed_policies].each do |policy_arn| @iam.detach_role_policy(:role_name => role_name, :policy_arn => policy_arn) end @iam.delete_role(:role_name => role_name) end end def add_role_to_instance_profiles(role_name, instance_profile_names) log(:info, "Update Role `#{role_name}`", :color => :green) log(:info, " add instance_profiles=#{instance_profile_names.join(',')}", :color => :green) unless_dry_run do instance_profile_names.each do |instance_profile_name| @iam.add_role_to_instance_profile(:instance_profile_name => instance_profile_name, :role_name => role_name) end end end def remove_role_from_instance_profiles(role_name, instance_profile_names) log(:info, "Update Role `#{role_name}`", :color => :green) log(:info, " remove instance_profiles=#{instance_profile_names.join(',')}", :color => :green) unless_dry_run do instance_profile_names.each do |instance_profile_name| @iam.remove_role_from_instance_profile(:instance_profile_name => instance_profile_name, :role_name => role_name) end end end def update_role_settings(role_name, new_settings, old_settings) log(:info, "Update Role `#{role_name}` > Settings", :color => :green) log(:info, Miam::Utils.diff(old_settings, new_settings, :color => @options[:color]), :color => false) unless_dry_run do @iam.update_role(new_settings.merge(role_name: role_name)) end end def update_assume_role_policy(role_name, policy_document, old_policy_document) log(:info, "Update Role `#{role_name}` > AssumeRolePolicy", :color => :green) log(:info, Miam::Utils.diff(old_policy_document, policy_document, :color => @options[:color]), :color => false) unless_dry_run do @iam.update_assume_role_policy( :role_name => role_name, :policy_document => encode_document(policy_document), ) end end def create_instance_profile(instance_profile_name, attrs) log(:info, "Create InstanceProfile `#{instance_profile_name}`", :color => :cyan) unless_dry_run do params = {:instance_profile_name => instance_profile_name} params[:path] = attrs[:path] if attrs[:path] @iam.create_instance_profile(params) end new_instance_profile_attrs = {} new_instance_profile_attrs[:path] = attrs[:path] if attrs[:path] new_instance_profile_attrs end def delete_instance_profile(instance_profile_name, attrs, roles_in_instance_profile) log(:info, "Delete InstanceProfile `#{instance_profile_name}`", :color => :red) unless_dry_run do roles_in_instance_profile.each do |role_name| @iam.remove_role_from_instance_profile(:instance_profile_name => instance_profile_name, :role_name => role_name) end @iam.delete_instance_profile(:instance_profile_name => instance_profile_name) end end def update_name(type, user_or_group_name, new_name) log(:info, "Update #{Miam::Utils.camelize(type.to_s)} `#{user_or_group_name}`", :color => :green) log(:info, Miam::StringHelper.green(" name:\n") + Miam::Utils.diff(user_or_group_name, new_name, :color => @options[:color], :indent => ' '), :color => false) update_user_or_group(type, user_or_group_name, "new_#{type}_name".to_sym => new_name) end def update_path(type, user_or_group_name, new_path, old_path) log(:info, "Update #{Miam::Utils.camelize(type.to_s)} `#{user_or_group_name}`", :color => :green) log(:info, Miam::StringHelper.green(" path:\n") + Miam::Utils.diff(old_path, new_path, :color => @options[:color], :indent => ' '), :color => false) update_user_or_group(type, user_or_group_name, :new_path => new_path) end def update_user_or_group(type, user_or_group_name, params) unless_dry_run do params["#{type}_name".to_sym] = user_or_group_name @iam.send("update_#{type}", params) end end def create_policy(type, user_or_group_name, policy_name, policy_document) log(:info, "Create #{Miam::Utils.camelize(type.to_s)} `#{user_or_group_name}` > Policy `#{policy_name}`", :color => :cyan) log(:info, " #{policy_document.pretty_inspect.gsub("\n", "\n ").strip}", :color => :cyan) put_policy(type, user_or_group_name, policy_name, policy_document) end def update_policy(type, user_or_group_name, policy_name, policy_document, old_policy_document) log(:info, "Update #{Miam::Utils.camelize(type.to_s)} `#{user_or_group_name}` > Policy `#{policy_name}`", :color => :green) log(:info, Miam::Utils.diff(old_policy_document, policy_document, :color => @options[:color]), :color => false) put_policy(type, user_or_group_name, policy_name, policy_document) end def delete_policy(type, user_or_group_name, policy_name) logmsg = "Delete #{Miam::Utils.camelize(type.to_s)} `#{user_or_group_name}` > Policy `#{policy_name}`" log(:info, logmsg, :color => :red) unless_dry_run do params = {:policy_name => policy_name} params["#{type}_name".to_sym] = user_or_group_name @iam.send("delete_#{type}_policy", params) end end def put_policy(type, user_or_group_name, policy_name, policy_document) unless_dry_run do params = { :policy_name => policy_name, :policy_document => encode_document(policy_document), } params["#{type}_name".to_sym] = user_or_group_name @iam.send("put_#{type}_policy", params) end end def attach_policies(type, name, policies) type = type.to_s type_s = type.slice(0, 1).upcase + type.slice(1..-1) log(:info, "Update #{type_s} `#{name}`", :color => :green) log(:info, " attach policies=#{policies.join(',')}", :color => :green) unless_dry_run do policies.each do |arn| @iam.send("attach_#{type}_policy", :"#{type}_name" => name, :policy_arn => arn) end end end def detach_policies(type, name, policies) type = type.to_s type_s = type.slice(0, 1).upcase + type.slice(1..-1) log(:info, "Update #{type_s} `#{name}`", :color => :green) log(:info, " detach policies=#{policies.join(',')}", :color => :red) unless_dry_run do policies.each do |arn| @iam.send("detach_#{type}_policy", :"#{type}_name" => name, :policy_arn => arn) end end end def list_access_key_ids(user_name) @iam.list_access_keys(:user_name => user_name).map {|resp| resp.access_key_metadata.map do |metadata| metadata.access_key_id end }.flatten end def list_signing_certificate_ids(user_name) @iam.list_signing_certificates(:user_name => user_name).map {|resp| resp.certificates.map do |cert| cert.certificate_id end }.flatten end def create_managed_policy(policy_name, attrs) log(:info, "Create ManagedPolicy `#{policy_name}`", :color => :cyan) unless_dry_run do params = { :policy_name => policy_name, :path => attrs[:path], :policy_document => encode_document(attrs[:document]), } @iam.create_policy(params) end end def delete_managed_policy(policy_name, policy_path) log(:info, "Delete ManagedPolicy `#{policy_name}`", :color => :red) unless_dry_run do policy_versions = @iam.list_policy_versions( :policy_arn => policy_arn(policy_name, policy_path), :max_items => MAX_POLICY_VERSIONS ) policy_versions.versions.reject {|pv| pv.is_default_version }.each {|pv| @iam.delete_policy_version( :policy_arn => policy_arn(policy_name, policy_path), :version_id => pv.version_id ) } @iam.delete_policy( :policy_arn => policy_arn(policy_name, policy_path) ) end end def update_managed_policy(policy_name, policy_path, policy_document, old_policy_document) log(:info, "Update ManagedPolicy `#{policy_name}`", :color => :green) log(:info, Miam::Utils.diff(old_policy_document, policy_document, :color => @options[:color]), :color => false) unless_dry_run do policy_versions = @iam.list_policy_versions( :policy_arn => policy_arn(policy_name, policy_path), :max_items => MAX_POLICY_VERSIONS ) if policy_versions.versions.length >= MAX_POLICY_VERSIONS delete_policy_version = policy_versions.versions.reject {|pv| pv.is_default_version }.sort_by {|pv| pv.version_id[1..-1].to_i }.first @iam.delete_policy_version( :policy_arn => policy_arn(policy_name, policy_path), :version_id => delete_policy_version.version_id ) end @iam.create_policy_version( :policy_arn => policy_arn(policy_name, policy_path), :policy_document => encode_document(policy_document), set_as_default: true ) end end def password_policy return @password_policy if instance_variable_defined?(:@password_policy) @password_policy = @iam.get_account_password_policy.password_policy rescue Aws::IAM::Errors::NoSuchEntity @password_policy = nil end private def encode_document(policy_document) if @options[:disable_form_json] JSON.dump(policy_document) else encoded = JSON.pretty_generate(policy_document) if Miam::Utils.bytesize(encoded) > MAX_POLICY_SIZE encoded = JSON.pretty_generate(policy_document) encoded = encoded.gsub(/^\s+/m, '').strip end if Miam::Utils.bytesize(encoded) > MAX_POLICY_SIZE encoded = JSON.dump(policy_document) end encoded end end def unless_dry_run yield unless @options[:dry_run] end def account_id # https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html # http://docs.aws.amazon.com/STS/latest/APIReference/API_GetCallerIdentity.html @account_id ||= @sts.get_caller_identity.account end def policy_arn(policy_name, policy_path) File.join("arn:aws:iam::#{account_id}:policy", policy_path, policy_name) end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/utils.rb
lib/miam/utils.rb
class Miam::Utils class << self def unbrace(str) str.sub(/\A\s*\{/, '').sub(/\}\s*\z/, '') end def camelize(str) str.slice(0, 1).upcase + str.slice(1..-1).downcase end def bytesize(str) if str.respond_to?(:bytesize) str.bytesize else str.length end end def diff(obj1, obj2, options = {}) diffy = Diffy::Diff.new( obj1.pretty_inspect, obj2.pretty_inspect, :diff => '-u' ) out = diffy.to_s(options[:color] ? :color : :text).gsub(/\s+\z/m, '') out.gsub!(/^/, options[:indent]) if options[:indent] out end end # of class methods end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/dsl.rb
lib/miam/dsl.rb
class Miam::DSL def self.convert(exported, options = {}) Miam::DSL::Converter.convert(exported, options) end def self.parse(dsl, path, options = {}) Miam::DSL::Context.eval(dsl, path, options).result end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/template_helper.rb
lib/miam/template_helper.rb
module Miam module TemplateHelper def include_template(template_name, context = {}) @template_name = template_name @caller = caller[0] tmplt = @context.templates[template_name.to_s] unless tmplt raise "Template `#{template_name}` is not defined" end context_orig = @context @context = @context.merge(context) instance_eval(&tmplt) @context = context_orig end def context @context end def required(*args) missing_args = args.map(&:to_s) - @context.keys.map(&:to_s) unless missing_args.empty? ex = ArgumentError.new("Missing arguments: [#{missing_args.join(", ")}] in template: '#{@template_name}'") ex.set_backtrace(@caller) raise ex end end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/client.rb
lib/miam/client.rb
class Miam::Client include Miam::Logger::Helper def initialize(options = {}) @options = { format: :ruby, exclude: [] }.merge(options) aws_config = options.delete(:aws_config) || {} @iam = Aws::IAM::Client.new(aws_config) @sts = Aws::STS::Client.new(aws_config) @driver = Miam::Driver.new(@iam, @sts, options) @password_manager = options[:password_manager] || Miam::PasswordManager.new('-', options) end def export(export_options = {}) exported, group_users, instance_profile_roles = Miam::Exporter.export(@iam, @options) exported.sort_array! if block_given? [:users, :groups, :roles, :instance_profiles, :policies].each do |type| splitted = {:users => {}, :groups => {}, :roles => {}, :instance_profiles => {}, :policies => {}} if export_options[:split_more] exported[type].sort_by {|k, v| k }.each do |name, attrs| more_splitted = splitted.dup more_splitted[type] = {} more_splitted[type][name] = attrs dsl = exec_by_format( :ruby => proc { Miam::DSL.convert(more_splitted, @options).strip }, :json => proc { JSON.pretty_generate(more_splitted) } ) yield(:type => type, :name => name, :dsl => dsl) end else splitted[type] = exported[type] dsl = exec_by_format( :ruby => proc { Miam::DSL.convert(splitted, @options).strip }, :json => proc { JSON.pretty_generate(splitted) } ) yield(:type => type, :dsl => dsl) end end else dsl = exec_by_format( :ruby => proc { Miam::DSL.convert(exported, @options).strip }, :json => proc { JSON.pretty_generate(exported) } ) end end def apply(file) walk(file) end private def walk(file) expected = load_file(file) @options[:exclude] += expected[:exclude] actual, group_users, instance_profile_roles = Miam::Exporter.export(@iam, @options) updated = pre_walk_managed_policies(expected[:policies], actual[:policies]) updated = walk_groups(expected[:groups], actual[:groups], actual[:users], group_users) || updated updated = walk_users(expected[:users], actual[:users], group_users) || updated updated = walk_instance_profiles(expected[:instance_profiles], actual[:instance_profiles], actual[:roles], instance_profile_roles) || updated updated = walk_roles(expected[:roles], actual[:roles], instance_profile_roles) || updated updated = post_walk_managed_policies(actual[:policies]) || updated if @options[:dry_run] false else updated end end def walk_users(expected, actual, group_users) updated = scan_rename(:user, expected, actual, group_users) expected.each do |user_name, expected_attrs| next unless target_matched?(user_name) actual_attrs = actual.delete(user_name) if actual_attrs updated = walk_path(:user, user_name, expected_attrs[:path], actual_attrs[:path]) || updated updated = walk_user(user_name, expected_attrs, actual_attrs) || updated else actual_attrs = @driver.create_user(user_name, expected_attrs) access_key = @driver.create_access_key(user_name) unless @options[:no_access_key] if access_key @password_manager.puts_password(user_name, access_key[:access_key_id], access_key[:secret_access_key]) end walk_user(user_name, expected_attrs, actual_attrs) updated = true end end actual.each do |user_name, attrs| next unless target_matched?(user_name) @driver.delete_user(user_name, attrs) group_users.each do |group_name, users| users.delete(user_name) end updated = true end updated end def walk_user(user_name, expected_attrs, actual_attrs) updated = walk_login_profile(user_name, expected_attrs[:login_profile], actual_attrs[:login_profile]) updated = walk_user_groups(user_name, expected_attrs[:groups], actual_attrs[:groups]) || updated updated = walk_attached_managed_policies(:user, user_name, expected_attrs[:attached_managed_policies], actual_attrs[:attached_managed_policies]) || updated walk_policies(:user, user_name, expected_attrs[:policies], actual_attrs[:policies]) || updated end def walk_login_profile(user_name, expected_login_profile, actual_login_profile) updated = false [expected_login_profile, actual_login_profile].each do |login_profile| if login_profile and not login_profile.has_key?(:password_reset_required) login_profile[:password_reset_required] = false end end if expected_login_profile and not actual_login_profile expected_login_profile[:password] ||= @password_manager.identify(user_name, :login_profile, @driver.password_policy) @driver.create_login_profile(user_name, expected_login_profile) updated = true elsif not expected_login_profile and actual_login_profile @driver.delete_login_profile(user_name) updated = true elsif expected_login_profile != actual_login_profile if @options[:ignore_login_profile] log(:warn, "User `#{user_name}`: difference of login profile has been ignored: expected=#{expected_login_profile.inspect}, actual=#{actual_login_profile.inspect}", :color => :yellow) else @driver.update_login_profile(user_name, expected_login_profile, actual_login_profile) updated = true end end updated end def walk_user_groups(user_name, expected_groups, actual_groups) expected_groups = expected_groups.sort actual_groups = actual_groups.sort updated = false if expected_groups != actual_groups add_groups = expected_groups - actual_groups remove_groups = actual_groups - expected_groups unless add_groups.empty? @driver.add_user_to_groups(user_name, add_groups) end unless remove_groups.empty? @driver.remove_user_from_groups(user_name, remove_groups) end updated = true end updated end def walk_groups(expected, actual, actual_users, group_users) updated = scan_rename(:group, expected, actual, group_users) expected.each do |group_name, expected_attrs| next unless target_matched?(group_name) actual_attrs = actual.delete(group_name) if actual_attrs updated = walk_path(:group, group_name, expected_attrs[:path], actual_attrs[:path]) || updated updated = walk_group(group_name, expected_attrs, actual_attrs) || updated else actual_attrs = @driver.create_group(group_name, expected_attrs) walk_group(group_name, expected_attrs, actual_attrs) updated = true end end actual.each do |group_name, attrs| next unless target_matched?(group_name) users_in_group = group_users.delete(group_name) || [] @driver.delete_group(group_name, attrs, users_in_group) actual_users.each do |user_name, user_attrs| user_attrs[:groups].delete(group_name) end updated = true end updated end def walk_group(group_name, expected_attrs, actual_attrs) updated = walk_policies(:group, group_name, expected_attrs[:policies], actual_attrs[:policies]) walk_attached_managed_policies(:group, group_name, expected_attrs[:attached_managed_policies], actual_attrs[:attached_managed_policies]) || updated end def walk_roles(expected, actual, instance_profile_roles) updated = false expected.each do |role_name, expected_attrs| next unless target_matched?(role_name) actual_attrs = actual.delete(role_name) if actual_attrs updated = walk_role(role_name, expected_attrs, actual_attrs) || updated else actual_attrs = @driver.create_role(role_name, expected_attrs) walk_role(role_name, expected_attrs, actual_attrs) updated = true end end actual.each do |role_name, attrs| next unless target_matched?(role_name) instance_profile_names = [] instance_profile_roles.each do |instance_profile_name, roles| if roles.include?(role_name) instance_profile_names << instance_profile_name end end @driver.delete_role(role_name, instance_profile_names, attrs) instance_profile_roles.each do |instance_profile_name, roles| roles.delete(role_name) end updated = true end updated end def walk_role(role_name, expected_attrs, actual_attrs) if expected_attrs.values_at(:path) != actual_attrs.values_at(:path) log(:warn, "Role `#{role_name}`: 'path' cannot be updated", :color => :yellow) end updated = walk_role_settings(role_name, {max_session_duration: expected_attrs[:max_session_duration]}, {max_session_duration: actual_attrs[:max_session_duration]}) updated = walk_assume_role_policy(role_name, expected_attrs[:assume_role_policy_document], actual_attrs[:assume_role_policy_document]) || updated updated = walk_role_instance_profiles(role_name, expected_attrs[:instance_profiles], actual_attrs[:instance_profiles]) || updated updated = walk_attached_managed_policies(:role, role_name, expected_attrs[:attached_managed_policies], actual_attrs[:attached_managed_policies]) || updated walk_policies(:role, role_name, expected_attrs[:policies], actual_attrs[:policies]) || updated end def walk_role_settings(role_name, expected_settings, actual_settings) updated = false if expected_settings != actual_settings @driver.update_role_settings(role_name, expected_settings, actual_settings) updated = true end updated end def walk_assume_role_policy(role_name, expected_assume_role_policy, actual_assume_role_policy) updated = false expected_assume_role_policy.sort_array! actual_assume_role_policy.sort_array! # With only one entity granted # On IAM # (1) Statement => [ { Principal => AWS => arn } ] # Should be able to specify like: # (2) Statement => [ { Principal => AWS => [arn] } ] # Actually (1) is reflected when config (2) is applied expected_arp_stmt = expected_assume_role_policy.fetch('Statement', []) expected_arp_stmt = expected_arp_stmt.select {|i| i.key?('Principal') } expected_arp_stmt.each do |stmt| stmt['Principal'].each do |k, v| entities = Array(v) stmt['Principal'][k] = entities.first if entities.length < 2 end end if expected_assume_role_policy != actual_assume_role_policy @driver.update_assume_role_policy(role_name, expected_assume_role_policy, actual_assume_role_policy) updated = true end updated end def walk_role_instance_profiles(role_name, expected_instance_profiles, actual_instance_profiles) expected_instance_profiles = expected_instance_profiles.sort actual_instance_profiles = actual_instance_profiles.sort updated = false if expected_instance_profiles != actual_instance_profiles add_instance_profiles = expected_instance_profiles - actual_instance_profiles remove_instance_profiles = actual_instance_profiles - expected_instance_profiles unless add_instance_profiles.empty? @driver.add_role_to_instance_profiles(role_name, add_instance_profiles) end unless remove_instance_profiles.empty? @driver.remove_role_from_instance_profiles(role_name, remove_instance_profiles) end updated = true end updated end def walk_instance_profiles(expected, actual, actual_roles, instance_profile_roles) updated = false expected.each do |instance_profile_name, expected_attrs| next unless target_matched?(instance_profile_name) actual_attrs = actual.delete(instance_profile_name) if actual_attrs updated = walk_instance_profile(instance_profile_name, expected_attrs, actual_attrs) || updated else actual_attrs = @driver.create_instance_profile(instance_profile_name, expected_attrs) walk_instance_profile(instance_profile_name, expected_attrs, actual_attrs) updated = true end end actual.each do |instance_profile_name, attrs| next unless target_matched?(instance_profile_name) roles_in_instance_profile = instance_profile_roles.delete(instance_profile_name) || [] @driver.delete_instance_profile(instance_profile_name, attrs, roles_in_instance_profile) actual_roles.each do |role_name, role_attrs| role_attrs[:instance_profiles].delete(instance_profile_name) end updated = true end updated end def walk_instance_profile(instance_profile_name, expected_attrs, actual_attrs) updated = false if expected_attrs != actual_attrs log(:warn, "InstanceProfile `#{instance_profile_name}`: 'path' cannot be updated", :color => :yellow) end updated end def scan_rename(type, expected, actual, group_users) updated = false expected.each do |name, expected_attrs| renamed_from = expected_attrs[:renamed_from] next unless renamed_from actual_attrs = actual.delete(renamed_from) next unless actual_attrs @driver.update_name(type, renamed_from, name) actual[name] = actual_attrs case type when :user group_users.each do |group_name, users| users.each do |user_name| if user_name == renamed_from user_name.replace(name) end end end when :group users = group_users.delete(renamed_from) group_users[name] = users if users end updated = true end updated end def walk_path(type, user_or_group_name, expected_path, actual_path) updated = false if expected_path != actual_path @driver.update_path(type, user_or_group_name, expected_path, actual_path) updated = true end updated end def walk_policies(type, user_or_group_name, expected_policies, actual_policies) updated = false expected_policies.each do |policy_name, expected_document| actual_document = actual_policies.delete(policy_name) if actual_document updated = walk_policy(type, user_or_group_name, policy_name, expected_document, actual_document) || updated else @driver.create_policy(type, user_or_group_name, policy_name, expected_document) updated = true end end actual_policies.each do |policy_name, document| @driver.delete_policy(type, user_or_group_name, policy_name) updated = true end updated end def walk_policy(type, user_or_group_name, policy_name, expected_document, actual_document) updated = false expected_document.sort_array! actual_document.sort_array! if expected_document != actual_document @driver.update_policy(type, user_or_group_name, policy_name, expected_document, actual_document) updated = true end updated end def walk_attached_managed_policies(type, name, expected_attached_managed_policies, actual_attached_managed_policies) expected_attached_managed_policies = expected_attached_managed_policies.sort actual_attached_managed_policies = actual_attached_managed_policies.sort updated = false if expected_attached_managed_policies != actual_attached_managed_policies add_attached_managed_policies = expected_attached_managed_policies - actual_attached_managed_policies remove_attached_managed_policies = actual_attached_managed_policies - expected_attached_managed_policies unless add_attached_managed_policies.empty? @driver.attach_policies(type, name, add_attached_managed_policies) end unless remove_attached_managed_policies.empty? @driver.detach_policies(type, name, remove_attached_managed_policies) end updated = true end updated end def pre_walk_managed_policies(expected, actual) updated = false expected.each do |policy_name, expected_attrs| next unless target_matched?(policy_name) actual_attrs = actual.delete(policy_name) if actual_attrs if expected_attrs[:path] != actual_attrs[:path] log(:warn, "ManagedPolicy `#{policy_name}`: 'path' cannot be updated", :color => :yellow) end updated = walk_managed_policy(policy_name, actual_attrs[:path], expected_attrs[:document], actual_attrs[:document]) || updated else @driver.create_managed_policy(policy_name, expected_attrs) updated = true end end updated end def walk_managed_policy(policy_name, policy_path, expected_document, actual_document) updated = false expected_document.sort_array! actual_document.sort_array! if expected_document != actual_document @driver.update_managed_policy(policy_name, policy_path, expected_document, actual_document) updated = true end updated end def post_walk_managed_policies(actual) updated = false actual.each do |policy_name, actual_attrs| next unless target_matched?(policy_name) @driver.delete_managed_policy(policy_name, actual_attrs[:path]) updated = true end updated end def load_file(file) if file.kind_of?(String) open(file) do |f| exec_by_format( :ruby => proc { Miam::DSL.parse(f.read, file) }, :json => proc { load_json(f) } ) end elsif file.respond_to?(:read) exec_by_format( :ruby => proc { Miam::DSL.parse(file.read, file.path) }, :json => proc { load_json(f) } ) else raise TypeError, "can't convert #{file} into File" end end def target_matched?(name) result = true if @options[:exclude] result &&= @options[:exclude].all? {|r| name !~ r } end if @options[:target] result &&= @options[:target].any? {|r| name =~ r} end result end def exec_by_format(proc_by_format) format_proc = proc_by_format[@options[:format]] raise "Invalid format: #{@options[:format]}" unless format_proc format_proc.call end def load_json(json) json = JSON.load(json) normalized = {} json.each do |top_key, top_value| normalized[top_key.to_sym] = top_attrs = {} top_value.each do |second_key, second_value| top_attrs[second_key] = second_attrs = {} second_value.each do |third_key, third_value| third_key = third_key.to_sym if third_key == :login_profile new_third_value = {} third_value.each {|k, v| new_third_value[k.to_sym] = v } third_value = new_third_value end second_attrs[third_key] = third_value end end end normalized end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/dsl/converter.rb
lib/miam/dsl/converter.rb
class Miam::DSL::Converter def self.convert(exported, options = {}) self.new(exported, options).convert end def initialize(exported, options = {}) @exported = exported @options = options end def convert [ output_users(@exported[:users]), output_groups(@exported[:groups]), output_roles(@exported[:roles]), output_instance_profiles(@exported[:instance_profiles]), output_managed_policies(@exported[:policies]), ].join("\n") end private def output_users(users) users.each.sort_by {|k, v| k }.map {|user_name, attrs| next unless target_matched?(user_name) output_user(user_name, attrs) }.select {|i| i }.join("\n") end def output_user(user_name, attrs) user_options = {:path => attrs[:path]} <<-EOS user #{user_name.inspect}, #{Miam::Utils.unbrace(user_options.inspect)} do #{output_login_profile(attrs[:login_profile])} #{output_user_groups(attrs[:groups])} #{output_policies(attrs[:policies])} #{output_attached_managed_policies(attrs[:attached_managed_policies])} end EOS end def output_user_groups(groups) if groups.empty? groups = ['# no group'] else groups = groups.map {|i| i.inspect } end groups = "\n " + groups.join(",\n ") + "\n " "groups(#{groups})" end def output_login_profile(login_profile) if login_profile "login_profile #{Miam::Utils.unbrace(login_profile.inspect)}" else '# login_profile :password_reset_required=>true' end end def output_groups(groups) groups.each.sort_by {|k, v| k }.map {|group_name, attrs| next unless target_matched?(group_name) output_group(group_name, attrs) }.select {|i| i }.join("\n") end def output_group(group_name, attrs) group_options = {:path => attrs[:path]} <<-EOS group #{group_name.inspect}, #{Miam::Utils.unbrace(group_options.inspect)} do #{output_policies(attrs[:policies])} #{output_attached_managed_policies(attrs[:attached_managed_policies])} end EOS end def output_roles(roles) roles.each.sort_by {|k, v| k }.map {|role_name, attrs| next unless target_matched?(role_name) output_role(role_name, attrs) }.select {|i| i }.join("\n") end def output_role(role_name, attrs) role_options = {:path => attrs[:path]} <<-EOS role #{role_name.inspect}, #{Miam::Utils.unbrace(role_options.inspect)} do #{output_role_instance_profiles(attrs[:instance_profiles])} #{output_role_max_session_duration(attrs[:max_session_duration])} #{output_assume_role_policy_document(attrs[:assume_role_policy_document])} #{output_policies(attrs[:policies])} #{output_attached_managed_policies(attrs[:attached_managed_policies])} end EOS end def output_role_instance_profiles(instance_profiles) if instance_profiles.empty? instance_profiles = ['# no instance_profile'] else instance_profiles = instance_profiles.map {|i| i.inspect } end instance_profiles = "\n " + instance_profiles.join(",\n ") + "\n " "instance_profiles(#{instance_profiles})" end def output_instance_profiles(instance_profiles) instance_profiles.each.sort_by {|k, v| k }.map {|instance_profile_name, attrs| next unless target_matched?(instance_profile_name) output_instance_profile(instance_profile_name, attrs) }.select {|i| i }.join("\n") end def output_role_max_session_duration(max_session_duration) <<-EOS.strip max_session_duration #{max_session_duration} EOS end def output_assume_role_policy_document(assume_role_policy_document) assume_role_policy_document = assume_role_policy_document.pretty_inspect assume_role_policy_document.gsub!("\n", "\n ").strip! <<-EOS.strip assume_role_policy_document do #{assume_role_policy_document} end EOS end def output_instance_profile(instance_profile_name, attrs) instance_profile_options = {:path => attrs[:path]} <<-EOS instance_profile #{instance_profile_name.inspect}, #{Miam::Utils.unbrace(instance_profile_options.inspect)} EOS end def output_policies(policies) if policies.empty? "# no policy" else policies.map {|policy_name, policy_document| output_policy(policy_name, policy_document) }.join("\n\n ").strip end end def output_policy(policy_name, policy_document) policy_document = policy_document.pretty_inspect policy_document.gsub!("\n", "\n ").strip! <<-EOS.strip policy #{policy_name.inspect} do #{policy_document} end EOS end def output_attached_managed_policies(attached_managed_policies) if attached_managed_policies.empty? attached_managed_policies = ['# attached_managed_policy'] else attached_managed_policies = attached_managed_policies.map {|i| i.inspect } end attached_managed_policies = "\n " + attached_managed_policies.join(",\n ") + "\n " "attached_managed_policies(#{attached_managed_policies})" end def output_managed_policies(policies) policies.each.sort_by {|k, v| k }.map {|policy_name, attrs| next unless target_matched?(policy_name) output_managed_policy(policy_name, attrs) }.select {|i| i }.join("\n") end def output_managed_policy(policy_name, attrs) policy_options = {:path => attrs[:path]} policy_document = attrs[:document].pretty_inspect policy_document.gsub!("\n", "\n ").strip! <<-EOS managed_policy #{policy_name.inspect}, #{Miam::Utils.unbrace(policy_options.inspect)} do #{policy_document} end EOS end def target_matched?(name) result = true if @options[:exclude] result &&= @options[:exclude].all? {|r| name !~ r} end if @options[:target] result &&= @options[:target].any? {|r| name =~ r} end result end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/dsl/context.rb
lib/miam/dsl/context.rb
class Miam::DSL::Context include Miam::TemplateHelper def self.eval(dsl, path, options = {}) self.new(path, options) { eval(dsl, binding, path) } end attr_reader :result def initialize(path, options = {}, &block) @path = path @options = options @result = {:users => {}, :groups => {}, :roles => {}, :instance_profiles => {}, :policies => {}, :exclude => []} @context = Hashie::Mash.new( :path => path, :options => options, :templates => {} ) instance_eval(&block) end def template(name, &block) @context.templates[name.to_s] = block end private def require(file) iamfile = (file =~ %r|\A/|) ? file : File.expand_path(File.join(File.dirname(@path), file)) if File.exist?(iamfile) instance_eval(File.read(iamfile), iamfile) elsif File.exist?(iamfile + '.rb') instance_eval(File.read(iamfile + '.rb'), iamfile + '.rb') else Kernel.require(file) end end def exclude(pattern) @result[:exclude] << pattern end def user(name, user_options = {}, &block) name = name.to_s if @result[:users][name] raise "User `#{name}` is already defined" end attrs = Miam::DSL::Context::User.new(@context, name, &block).result @result[:users][name] = user_options.merge(attrs) end def group(name, group_options = {}, &block) name = name.to_s if @result[:groups][name] raise "Group `#{name}` is already defined" end attrs = Miam::DSL::Context::Group.new(@context, name, &block).result @result[:groups][name] = group_options.merge(attrs) end def role(name, role_options = {}, &block) name = name.to_s if @result[:roles][name] raise "Role `#{name}` is already defined" end attrs = Miam::DSL::Context::Role.new(@context, name, &block).result @result[:roles][name] = role_options.merge(attrs) end def instance_profile(name, instance_profile_options = {}, &block) name = name.to_s if @result[:instance_profiles][name] raise "instance_profile `#{name}` is already defined" end @result[:instance_profiles][name] = instance_profile_options end def managed_policy(name, policy_options = {}, &block) name = name.to_s if @result[:policies][name] raise "ManagedPolicy `#{name}` is already defined" end attrs = Miam::DSL::Context::ManagedPolicy.new(@context, name, &block).result @result[:policies][name] = policy_options.merge(attrs) end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/dsl/context/group.rb
lib/miam/dsl/context/group.rb
class Miam::DSL::Context::Group include Miam::TemplateHelper def initialize(context, name, &block) @group_name = name @context = context.merge(:group_name => name) @result = {:policies => {}, :attached_managed_policies => []} instance_eval(&block) end attr_reader :result private def policy(name) name = name.to_s if @result[:policies][name] raise "Group `#{@group_name}` > Policy `#{name}`: already defined" end policy_document = yield unless policy_document.kind_of?(Hash) raise "Group `#{@group_name}` > Policy `#{name}`: wrong argument type #{policy_document.class} (expected Hash)" end @result[:policies][name] = policy_document end def attached_managed_policies(*policies) @result[:attached_managed_policies].concat(policies.map(&:to_s)) end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/dsl/context/role.rb
lib/miam/dsl/context/role.rb
class Miam::DSL::Context::Role include Miam::TemplateHelper def initialize(context, name, &block) @role_name = name @context = context.merge(:role_name => name) @result = {:instance_profiles => [], :max_session_duration => 3600, :policies => {}, :attached_managed_policies => []} instance_eval(&block) end def result unless @result[:assume_role_policy_document] raise "Role `#{@role_name}`: AssumeRolePolicyDocument is not defined" end @result end private def instance_profiles(*profiles) @result[:instance_profiles].concat(profiles.map(&:to_s)) end def max_session_duration(duration) @result[:max_session_duration] = duration end def assume_role_policy_document if @result[:assume_role_policy_document] raise "Role `#{@role_name}` > AssumeRolePolicyDocument: already defined" end assume_role_policy_document = yield unless assume_role_policy_document.kind_of?(Hash) raise "Role `#{@role_name}` > AssumeRolePolicyDocument: wrong argument type #{policy_document.class} (expected Hash)" end @result[:assume_role_policy_document] = assume_role_policy_document end def policy(name) name = name.to_s if @result[:policies][name] raise "Role `#{@role_name}` > Policy `#{name}`: already defined" end policy_document = yield unless policy_document.kind_of?(Hash) raise "Role `#{@role_name}` > Policy `#{name}`: wrong argument type #{policy_document.class} (expected Hash)" end @result[:policies][name] = policy_document end def attached_managed_policies(*policies) @result[:attached_managed_policies].concat(policies.map(&:to_s)) end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/dsl/context/managed_policy.rb
lib/miam/dsl/context/managed_policy.rb
class Miam::DSL::Context::ManagedPolicy include Miam::TemplateHelper def initialize(context, name, &block) @policy_name = name @context = context.merge(:policy_name => name) @result = {:document => get_document(block)} end attr_reader :result private def get_document(block) document = instance_eval(&block) unless document.kind_of?(Hash) raise "ManagedPolicy `#{@policy_name}`: wrong argument type #{document.class} (expected Hash)" end document end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/dsl/context/user.rb
lib/miam/dsl/context/user.rb
class Miam::DSL::Context::User include Miam::TemplateHelper def initialize(context, name, &block) @user_name = name @context = context.merge(:user_name => name) @result = {:groups => [], :policies => {}, :attached_managed_policies => []} instance_eval(&block) end attr_reader :result private def login_profile(value) @result[:login_profile] = value end def groups(*grps) @result[:groups].concat(grps.map(&:to_s)) end def policy(name) name = name.to_s if @result[:policies][name] raise "User `#{@user_name}` > Policy `#{name}`: already defined" end policy_document = yield unless policy_document.kind_of?(Hash) raise "User `#{@user_name}` > Policy `#{name}`: wrong argument type #{policy_document.class} (expected Hash)" end @result[:policies][name] = policy_document end def attached_managed_policies(*policies) @result[:attached_managed_policies].concat(policies.map(&:to_s)) end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
cookpad/miam
https://github.com/cookpad/miam/blob/f1d53f49da60f3e1cb5539a25c889f01e162dfb9/lib/miam/ext/hash_ext.rb
lib/miam/ext/hash_ext.rb
class Hash def sort_array! keys.each do |key| value = self[key] self[key] = sort_array0(value) end self end private def sort_array0(value) case value when Hash new_value = {} value.keys.sort.each do |k| new_value[k] = sort_array0(value.fetch(k)) end new_value when Array value.map {|v| sort_array0(v) }.sort_by(&:to_s) else value end end end
ruby
MIT
f1d53f49da60f3e1cb5539a25c889f01e162dfb9
2026-01-04T17:51:57.013926Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/spec/spec_helper.rb
ciri-common/spec/spec_helper.rb
require "bundler/setup" require "ciri/common" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/spec/ciri/key_spec.rb
ciri-common/spec/ciri/key_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/crypto' require 'ciri/key' RSpec.describe Ciri::Key do context 'ecdsa recover' do it 'self consistent' do key = Ciri::Key.random msg = Ciri::Utils.keccak "hello world" signature = key.ecdsa_signature(msg) expect(Ciri::Key.ecdsa_recover(msg, signature).raw_public_key).to eq key.raw_public_key end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/spec/ciri/common_spec.rb
ciri-common/spec/ciri/common_spec.rb
RSpec.describe Ciri::Common do it "has a version number" do expect(Ciri::Common::VERSION).not_to be nil end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/spec/ciri/types/hash_spec.rb
ciri-common/spec/ciri/types/hash_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/types/hash' RSpec.describe Ciri::Types::Hash32 do it 'RLP' do hash32 = described_class.new("\x00" * 32) decoded_hash32 = described_class.rlp_decode described_class.rlp_encode(hash32) expect(hash32).to eq decoded_hash32 end it 'size must be 32' do expect do described_class.new("\x00" * 20).validate end.to raise_error(Ciri::Types::Errors::InvalidError) end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/common.rb
ciri-common/lib/ciri/common.rb
require "ciri/common/version" module Ciri module Common # Your code goes here... end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/core_ext.rb
ciri-common/lib/ciri/core_ext.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils' module Ciri # Core extension module for convenient module CoreExt refine(String) do def hex Utils.hex(self) end def dehex Utils.dehex(self) end def keccak Utils.keccak(self) end def big_endian_decode Utils.big_endian_decode(self) end def pad_zero(size) self.rjust(size, "\x00".b) end end refine(Integer) do def ceil_div(size) Utils.ceil_div(self, size) end def big_endian_encode Utils.big_endian_encode(self) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/key.rb
ciri-common/lib/ciri/key.rb
# frozen_string_literal: true # Copyright (c) 2018, by Jiang Jinyang. <https://justjjy.com>, classicalliu. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'openssl' require 'ciri/utils' require 'ciri/core_ext' require 'ciri/crypto' require 'ciri/types/address' using Ciri::CoreExt module Ciri # Ciri::Key represent private/public key pair, it support several encryption methods used in Ethereum # # Examples: # # key = Ciri::Key.random # key.ecdsa_signature(data) # class Key class << self def ecdsa_recover(msg, signature) raw_public_key = Crypto.ecdsa_recover(msg, signature, return_raw_key: true) Ciri::Key.from_public_key(raw_public_key) end def random ec_key = OpenSSL::PKey::EC.new('secp256k1') ec_key.generate_key while (raw_priv_key = ec_key.private_key.to_s(2).size) != 32 warn "generated privkey is not 32 bytes, bytes: #{raw_priv_key.size} privkey: #{Utils.hex raw_priv_key} -> regenerate it..." ec_key.generate_key end Ciri::Key.new(ec_key) end def from_public_key(public_key) if public_key.size == 64 public_key = "\x04".b + public_key end new Ciri::Utils.create_ec_pk(raw_pubkey: public_key) end def from_private_key(private_key) new Ciri::Utils.create_ec_pk(raw_privkey: private_key) end end # initialized from ec_key or raw keys # ec_key is a OpenSSL::PKey::EC object, raw keys is bytes presented keys def initialize(ec_key) @ec_key = ec_key end # raw public key def raw_public_key @raw_public_key ||= ec_key.public_key.to_bn.to_s(2) end def ecdsa_signature(data) Crypto.ecdsa_signature(secp256k1_key, data) end def ecies_encrypt(message, shared_mac_data = '') Crypto.ecies_encrypt(message, ec_key, shared_mac_data) end def ecies_decrypt(data, shared_mac_data = '') Crypto.ecies_decrypt(data, ec_key, shared_mac_data) end def to_address Types::Address.new(Utils.keccak(public_key)[-20..-1]) end def ec_key @ec_key end private # public key def public_key raw_public_key[1..-1] end def secp256k1_key privkey = ec_key.private_key.to_s(2) # some times below error will occurs, raise error with more detail unless privkey.instance_of?(String) && privkey.size == 32 raise ArgumentError, "privkey must be composed of 32 bytes, bytes: #{privkey.size} privkey: #{Utils.to_hex privkey}" end @secp256k1_key ||= Crypto.ensure_secp256k1_key(privkey: privkey) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/common/version.rb
ciri-common/lib/ciri/common/version.rb
module Ciri module Common VERSION = "0.1.0" end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/types/int.rb
ciri-common/lib/ciri/types/int.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'uint' module Ciri module Types Int16 = UInt8 class Int24 < UInt @size = 12 end Int64 = UInt32 class Int256 < UInt @size = 128 end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/types/errors.rb
ciri-common/lib/ciri/types/errors.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri module Types module Errors class Error < StandardError end class InvalidError < Error end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/types/account.rb
ciri-common/lib/ciri/types/account.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils' require 'ciri/trie' require 'ciri/rlp' module Ciri module Types class Account include RLP::Serializable schema( nonce: Integer, balance: Integer, storage_root: RLP::Bytes, code_hash: RLP::Bytes ) default_data code_hash: Utils::BLANK_SHA3, storage_root: Trie::BLANK_NODE_HASH # EMPTY(σ,a) ≡ σ[a]c =KEC􏰁()􏰂∧σ[a]n =0∧σ[a]b =0 def empty? !has_code? && nonce == 0 && balance == 0 end def has_code? code_hash != Utils::BLANK_SHA3 end class << self def new_empty Account.new(balance: 0, nonce: 0) end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/types/address.rb
ciri-common/lib/ciri/types/address.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'errors' require 'ciri/rlp' module Ciri module Types class Address class << self def rlp_encode(address) RLP.encode(address.to_s) end def rlp_decode(data) address = self.new(RLP.decode(data)) address.validate address end end include Errors def initialize(address) @address = address.to_s end def ==(other) self.class == other.class && to_s == other.to_s end def to_s @address end alias to_str to_s def hex Utils.hex to_s end def empty? @address.empty? end def validate # empty address is valid return if empty? raise InvalidError.new("address must be 20 size, got #{@address.size}") unless @address.size == 20 end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/types/log_entry.rb
ciri-common/lib/ciri/types/log_entry.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require 'ciri/utils' require 'ciri/types/address' require 'ciri/types/uint' module Ciri module Types class LogEntry include RLP::Serializable schema( address: Types::Address, topics: [Types::UInt32], data: RLP::Bytes ) def to_blooms [address.to_s, *topics.map {|t| Utils.big_endian_encode(t, size: 32)}] end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/types/receipt.rb
ciri-common/lib/ciri/types/receipt.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require 'ciri/bloom_filter' require 'ciri/types/uint' require 'ciri/types/log_entry' module Ciri module Types class Receipt include RLP::Serializable schema( state_root: RLP::Bytes, gas_used: Integer, bloom: Types::UInt256, logs: [LogEntry], ) def initialize(state_root:, gas_used:, logs:, bloom: nil) bloom ||= begin blooms = logs.reduce([]) {|list, log| list.append *log.to_blooms} BloomFilter.from_iterable(blooms).to_i end super(state_root: state_root, gas_used: gas_used, logs: logs, bloom: bloom) end def bloom_filter BloomFilter.new(bloom) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/types/uint.rb
ciri-common/lib/ciri/types/uint.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils' require 'ciri/rlp' module Ciri module Types class UInt class << self attr_reader :size def rlp_encode(item) RLP.encode new(item).to_bytes end def rlp_decode(encoded) Utils.big_endian_decode(RLP.decode(encoded)) end def max @max ||= 2 ** size - 1 end def min 0 end def valid?(n) n >= 0 && n <= max end end @size = 0 def initialize(value) raise "can't initialize size #{self.class.size} number" if self.class.size <= 0 @value = value end def serialized Utils.big_endian_encode(@value, size: bytes_size) end alias to_bytes serialized def bytes_size self.class.size end def to_i @value end end class UInt8 < UInt @size = 8 end class UInt32 < UInt @size = 32 end class UInt256 < UInt @size = 256 end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/types/bytes.rb
ciri-common/lib/ciri/types/bytes.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' module Ciri module Types Bytes = RLP::Bytes end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-common/lib/ciri/types/hash.rb
ciri-common/lib/ciri/types/hash.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'errors' module Ciri module Types class Hash32 class << self def rlp_encode(hash32) RLP.encode(hash32.to_s) end def rlp_decode(data) hash32 = self.new(RLP.decode(data)) hash32.validate hash32 end end include Errors def initialize(h) @hash32 = h.to_s end def ==(other) self.class == other.class && to_s == other.to_s end def to_s @hash32 end alias to_str to_s def to_hex Utils.to_hex to_s end def empty? @hash32.empty? end def validate # empty address is valid return if empty? raise InvalidError.new("hash32 must be 32 size, got #{@hash32.size}") unless @hash32.size == 32 end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/spec_helper.rb
ciri-p2p/spec/spec_helper.rb
require "bundler/setup" require "ciri/p2p" RSpec.configure do |config| # Enable flags like --only-failures and --next-failure config.example_status_persistence_file_path = ".rspec_status" # Disable RSpec exposing methods globally on `Module` and `main` config.disable_monkey_patching! config.expect_with :rspec do |c| c.syntax = :expect end # set logger require 'ciri/utils/logger' level = %w{1 yes true}.include?(ENV['DEBUG']) ? :debug : :fatal Ciri::Utils::Logger.setup(level: level) end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p_spec.rb
ciri-p2p/spec/ciri/p2p_spec.rb
RSpec.describe Ciri::P2P do it "has a version number" do expect(Ciri::P2P::VERSION).not_to be nil end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p/peer_spec.rb
ciri-p2p/spec/ciri/p2p/peer_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'async' require 'ciri/p2p/peer' require 'ciri/p2p/protocol' require 'ciri/p2p/rlpx/protocol_handshake' RSpec.describe Ciri::P2P::Peer do let(:eth_protocol) {Ciri::P2P::Protocol.new(name: 'eth', version: 63, length: 17)} let(:old_eth_protocol) {Ciri::P2P::Protocol.new(name: 'eth', version: 62, length: 8)} let(:hello_protocol) {Ciri::P2P::Protocol.new(name: 'hello', version: 1, length: 16)} let(:caps) {[ Ciri::P2P::RLPX::Cap.new(name: 'eth', version: 63), Ciri::P2P::RLPX::Cap.new(name: 'eth', version: 62), Ciri::P2P::RLPX::Cap.new(name: 'hello', version: 1), ]} let(:handshake){Ciri::P2P::RLPX::ProtocolHandshake.new(version: 4, name: 'test', caps: caps, id: 0)} let(:protocols){[ eth_protocol, old_eth_protocol, hello_protocol ]} it 'find_protocol_io_by_msg_code' do IO.pipe do |io, io2| peer = Ciri::P2P::Peer.new(io, handshake, protocols, direction: Ciri::P2P::Peer::OUTBOUND) base_offset = Ciri::P2P::RLPX::BASE_PROTOCOL_LENGTH # According to the offset of DEVP2P message code, # we should fetch ETH protocl first which offset range is 1...17 (1...17).each do |raw_code| expect(peer.find_protocol_io_by_msg_code(raw_code + base_offset).protocol).to eq eth_protocol end # the hello protocol offset range is 17...17 + 16 (17...17 + 16).each do |raw_code| expect(peer.find_protocol_io_by_msg_code(raw_code + base_offset).protocol).to eq hello_protocol end end end it 'disconnect a peer' do IO.pipe do |io, io2| peer = Ciri::P2P::Peer.new(io, handshake, protocols, direction: Ciri::P2P::Peer::OUTBOUND) expect(peer.disconnected?).to be_falsey peer.disconnect expect(peer.disconnected?).to be_truthy end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p/peer_store_spec.rb
ciri-p2p/spec/ciri/p2p/peer_store_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/p2p/peer_store' require 'ciri/p2p/node' require 'ciri/p2p/address' require 'ciri/core_ext' using Ciri::CoreExt RSpec.describe Ciri::P2P::PeerStore do let(:peer_store) { described_class.new } let(:node_id) { Ciri::P2P::NodeID.new(Ciri::Key.random) } let(:node_ids) { 10.times.map{Ciri::P2P::NodeID.new(Ciri::Key.random)} } let(:ping_hash) { SecureRandom.bytes(10).keccak } context 'has_ping?' do it '#has_ping?' do expect(peer_store.has_ping?(node_id.to_bytes, ping_hash)).to be_falsey peer_store.update_ping(node_id.to_bytes, ping_hash) expect(peer_store.has_ping?(node_id.to_bytes, ping_hash)).to be_truthy expect(peer_store.has_ping?(node_id.to_bytes, ping_hash, expires_in: 0)).to be_falsey end end context 'has_seen?' do it '#has_seen?' do expect(peer_store.has_seen?(node_id.to_bytes)).to be_falsey peer_store.update_last_seen(node_id.to_bytes) expect(peer_store.has_seen?(node_id.to_bytes)).to be_truthy expect(peer_store.has_seen?(node_id.to_bytes, expires_in: 0)).to be_falsey end end context 'has_ban?' do it '#has_ban?' do expect(peer_store.has_ban?(node_id.to_bytes)).to be_falsey peer_store.ban_peer(node_id.to_bytes) expect(peer_store.has_ban?(node_id.to_bytes)).to be_truthy expect(peer_store.has_ban?(node_id.to_bytes, now: Time.now + 600)).to be_falsey end it 'after banned peer' do # see and ping peer peer_store.update_ping(node_id.to_bytes, ping_hash) peer_store.update_last_seen(node_id.to_bytes) expect(peer_store.has_ping?(node_id.to_bytes, ping_hash)).to be_truthy expect(peer_store.has_seen?(node_id.to_bytes)).to be_truthy # after ban peer_store.ban_peer(node_id.to_bytes) expect(peer_store.has_ping?(node_id.to_bytes, ping_hash)).to be_falsey expect(peer_store.has_seen?(node_id.to_bytes)).to be_falsey end end context 'find_bootnodes' do it 'return bootnodes' do node = Ciri::P2P::Node.new(node_id: node_id, addresses: []) peer_store.add_bootnode(node) expect(peer_store.find_bootnodes(1)).to eq [node] expect(peer_store.find_bootnodes(2)).to eq [node] end it 'find peers first' do node = Ciri::P2P::Node.new(node_id: node_id, addresses: []) node2 = Ciri::P2P::Node.new(node_id: node_ids[0], addresses: []) peer_store.add_bootnode(node) peer_store.add_node(node2) expect(peer_store.find_bootnodes(1)).to eq [node] expect(peer_store.find_bootnodes(2)).to eq [node, node2] end end context 'find_attempt_peers' do it 'return peers' do node = Ciri::P2P::Node.new(node_id: node_id, addresses: []) peer_store.add_node(node) expect(peer_store.find_attempt_peers(1)).to eq [node] expect(peer_store.find_attempt_peers(2)).to eq [node] end it 'should not return already connected peers' do nodes = node_ids.take(3).map do |node_id| Ciri::P2P::Node.new(node_id: node_id, addresses: []) end nodes.each {|node| peer_store.add_node(node) } peer_store.update_peer_status(nodes[0].node_id, Ciri::P2P::PeerStore::Status::CONNECTED) peer_store.update_peer_status(nodes[1].node_id, Ciri::P2P::PeerStore::Status::DISCONNECTED) peer_store.update_peer_status(nodes[2].node_id, Ciri::P2P::PeerStore::Status::UNKNOWN) expect(peer_store.find_attempt_peers(2)).to eq nodes[1..2] expect(peer_store.find_attempt_peers(3)).to eq nodes[1..2] end end context 'report_peer' do it 'report peer' do node = Ciri::P2P::Node.new(node_id: node_id, addresses: []) node2 = Ciri::P2P::Node.new(node_id: node_ids[0], addresses: []) peer_store.add_node(node) peer_store.add_node(node2) peer_store.report_peer(node.node_id, Ciri::P2P::PeerStore::Behaviours::PING) # report peer expect(peer_store.find_attempt_peers(1)).to eq [node] expect(peer_store.find_attempt_peers(2)).to eq [node, node2] # update score for reported peers peer_store.report_peer(node2.node_id, Ciri::P2P::PeerStore::Behaviours::PING) peer_store.report_peer(node2.node_id, Ciri::P2P::PeerStore::Behaviours::PING) expect(peer_store.find_attempt_peers(1)).to eq [node2] expect(peer_store.find_attempt_peers(2)).to eq [node2, node] end end context 'node' do let(:nodes) { node_ids.map {|node_id| Ciri::P2P::Node.new(node_id: node_id, addresses: []) } } let(:addresses) do [ Ciri::P2P::Address.new(ip: '127.0.0.1', tcp_port: 3000, udp_port: 3000), Ciri::P2P::Address.new(ip: '127.0.0.2', tcp_port: 3000, udp_port: 3000), Ciri::P2P::Address.new(ip: '127.0.0.3', tcp_port: 3000, udp_port: 3000), ] end it '#add_node' do expect(peer_store.find_attempt_peers(2)).to eq [] # first node peer_store.add_node(nodes[0]) expect(peer_store.find_attempt_peers(2)).to eq [nodes[0]] # duplicated node peer_store.add_node(nodes[0]) expect(peer_store.find_attempt_peers(2)).to eq [nodes[0]] # second node peer_store.add_node(nodes[1]) expect(peer_store.find_attempt_peers(2)).to eq nodes.take(2) end it '#add_node_addresses' do # add_node_addresses with a non-exits id peer_store.add_node_addresses(node_ids[0], addresses.take(1)) expect(peer_store.get_node_addresses(node_ids[0])).to be_nil # add a node peer_store.add_node(nodes[0]) peer_store.add_node_addresses(nodes[0].node_id, addresses.take(1)) expect(peer_store.get_node_addresses(nodes[0].node_id)).to eq addresses.take(1) # should ignore duplicated address peer_store.add_node_addresses(nodes[0].node_id, addresses.take(2)) expect(peer_store.get_node_addresses(nodes[0].node_id).sort).to eq addresses.take(2).sort end it '#get_node_addresses' do # get bootnode addresses expect(peer_store.get_node_addresses(nodes[0].node_id)).to be_nil peer_store.add_bootnode(nodes[0]) expect(peer_store.get_node_addresses(nodes[0].node_id)).not_to be_nil end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p/kad_spec.rb
ciri-p2p/spec/ciri/p2p/kad_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/p2p/kad' require 'ciri/core_ext' using Ciri::CoreExt RSpec.describe Ciri::P2P::Kad do describe Ciri::P2P::Kad::Node do let(:pubkey1) {10.encode_big_endian.pad_zero(65)} let(:pubkey2) {11.encode_big_endian.pad_zero(65)} let(:pubkey3) {12.encode_big_endian.pad_zero(65)} it '#distance_to' do node1 = described_class.new(pubkey1) node2 = described_class.new(pubkey2) distance = node1.distance_to(node2.id) expect(distance).to be > 0 expect(node1.id ^ node2.id).to eq distance end it '#==' do node1 = described_class.new(pubkey1) node2 = described_class.new(pubkey2) node3 = described_class.new(pubkey1) expect(node1).to eq node3 expect(node1).not_to eq node2 end it '#<=>' do node1 = described_class.new(pubkey1) node2 = described_class.new(pubkey2) node3 = described_class.new(pubkey3) expect([node1, node2, node3].sort).to eq [node1, node2, node3].sort_by{|node| node.id} end end describe Ciri::P2P::Kad::KBucket do let(:pubkey1) {10.encode_big_endian.pad_zero(65)} let(:pubkey2) {11.encode_big_endian.pad_zero(65)} let(:pubkey3) {12.encode_big_endian.pad_zero(65)} let(:pubkey4) {13.encode_big_endian.pad_zero(65)} let(:node1) {Ciri::P2P::Kad::Node.new(pubkey1)} let(:node2) {Ciri::P2P::Kad::Node.new(pubkey2)} let(:node3) {Ciri::P2P::Kad::Node.new(pubkey3)} let(:node4) {Ciri::P2P::Kad::Node.new(pubkey4)} let(:bucket) {described_class.new(start_id: 0, end_id: Ciri::P2P::Kad::K_MAX_NODE_ID)} let(:fake_node_class) do Class.new(Ciri::P2P::Kad::Node) do attr_reader :id def initialize(id) @id = id end end end it '#distance_to' do [node1, node2, node3].each do |node| expect(bucket.distance_to(node.id)).to eq bucket.midpoint ^ node.id end end it '#nodes_by_distance_to' do nodes = [node1, node2, node3] nodes.each {|node| bucket.add(node) } expect(bucket.nodes_by_distance_to(node4.id)).to eq nodes.sort_by{|node| node.distance_to node4.id} end it '#split' do bucket = described_class.new(start_id: 0, end_id: 10) nodes = (1..7).map{|id| fake_node_class.new(id) } nodes.each{|node| bucket.add(node) } expect(nodes.size).to eq 7 lower, upper = bucket.split expect(lower.size).to eq 5 expect(lower.nodes.sort).to eq nodes[0...5].sort expect(upper.size).to eq 2 expect(upper.nodes.sort).to eq nodes[5...7].sort end it '#delete' do nodes = [node1, node2, node3] nodes.each {|node| bucket.add(node) } expect(bucket.size).to eq 3 bucket.delete(node1) expect(bucket.size).to eq 2 expect(bucket.nodes.sort).to eq nodes[1..2].sort end it '#cover?' do bucket = described_class.new(start_id: 0, end_id: 10) expect(bucket.cover?(fake_node_class.new(1))).to be true expect(bucket.cover?(fake_node_class.new(5))).to be true expect(bucket.cover?(fake_node_class.new(10))).to be true expect(bucket.cover?(fake_node_class.new(11))).to be false end it '#full?' do bucket = described_class.new(start_id: 0, end_id: 10, k_size: 4) bucket.add(node1) expect(bucket.full?).to be false bucket.add(node2) expect(bucket.full?).to be false bucket.add(node3) expect(bucket.full?).to be false bucket.add(node4) expect(bucket.full?).to be true end it '#include?' do nodes = [node1, node2, node3] nodes.each do |node| expect(bucket.cover?(node)).to be true expect(bucket.include?(node)).to be false bucket.add(node) expect(bucket.include?(node)).to be true end end end describe Ciri::P2P::Kad::RoutingTable do let(:local_node) { Ciri::P2P::Kad::Node.new(1024.encode_big_endian.pad_zero(65)) } let(:nodes) do 1000.times.map{|i| Ciri::P2P::Kad::Node.new(i.encode_big_endian.pad_zero(65)) } end let(:table) do table = described_class.new(local_node: local_node) nodes.each{ |node| table.add_node(node) } table end it "#get_random_nodes" do expect(table.get_random_nodes(100).count).to eq 100 expect(table.get_random_nodes(2000).count).to eq table.size end it "#idle_buckets" do expect(table.idle_buckets.size).to eq 0 allow(table.buckets[0]).to receive(:last_updated).and_return(Time.now.to_i - 10000) expect(table.idle_buckets.size).to eq 1 end it "#not_full_buckets" do # we must have some nodes not full expect(table.buckets.size).to be > (table.size / 16) expect(table.not_full_buckets.size).to be < table.buckets.size end it "#delete_node" do table_size = table.size node = table.get_random_nodes(1)[0] expect(table.include?(node)).to be true table.delete_node(node) expect(table.size + 1).to eq table_size expect(table.include?(node)).to be false end it '#buckets_by_distance_to' do expect(table.buckets_by_distance_to(42)).to eq table.buckets.sort_by{|bucket| bucket.distance_to(42)} end it "#find_bucket_for_node" do node = table.get_random_nodes(1)[0] bucket = table.find_bucket_for_node(node) expect(bucket.include?(node)).to be true end it '#find_neighbours' do expect(table.find_neighbours(42).size).to be > 0 end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p/address_spec.rb
ciri-p2p/spec/ciri/p2p/address_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/p2p/address' require 'ciri/core_ext' using Ciri::CoreExt RSpec.describe Ciri::P2P::Address do describe Ciri::P2P::Address do it '#==' do addr1 = described_class.new(ip: '127.0.0.1', udp_port:3000, tcp_port: 3001) addr2 = described_class.new(ip: '127.0.0.1', udp_port:3000, tcp_port: 3001) expect(addr1).to eq addr2 end it '#ip' do addr = described_class.new(ip: '127.0.0.1', udp_port:3000, tcp_port: 3001) expect(addr.ip.loopback?).to be true end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p/server_spec.rb
ciri-p2p/spec/ciri/p2p/server_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'async' require 'ciri/p2p/server' require 'ciri/p2p/protocol' require 'ciri/p2p/node' require 'ciri/p2p/rlpx/protocol_handshake' RSpec.describe Ciri::P2P::Server do context 'dial node' do let(:key) do Ciri::Key.random end it 'connecting to bootnodes after started' do bootnode = Ciri::P2P::Node.new( node_id: Ciri::P2P::NodeID.new(key), addresses: [ Ciri::P2P::Address.new( ip: "127.0.0.1", udp_port: 42, tcp_port: 42, ) ] ) server = Ciri::P2P::Server.new(private_key: key, protocols: [], bootnodes: [bootnode], tcp_port: 0) allow(server.dialer).to receive(:dial) {|node| raise StandardError.new("dial error ip:#{node.addresses[0].ip}, tcp_port:#{node.addresses[0].tcp_port}")} expect do server.run end.to raise_error(StandardError, "dial error ip:#{bootnode.addresses[0].ip}, tcp_port:#{bootnode.addresses[0].tcp_port}") end end context('connect peers') do let(:mock_protocol_class) do Class.new(Ciri::P2P::Protocol) do attr_reader :raw_local_node_id, :received_messages, :connected_peers, :disconnected_peers attr_accessor :stop def initialized(context) @raw_local_node_id = context.raw_local_node_id @connected_peers = [] @received_messages = [] @disconnected_peers = [] @stop = false end def received(context, msg) return if @stop @received_messages << msg end def connected(context) return if @stop @connected_peers << context.peer context.send_data(1, "hello from #{Ciri::Utils.to_hex @raw_local_node_id}") end def disconnected(context) return if @stop @disconnected_peers << context.peer end end end def mock_protocol mock_protocol_class.new(name: 'moc', version: 63, length: 17) end def new_node(protocols:, bootnodes: []) private_key = Ciri::Key.random Ciri::P2P::Server.new( private_key: private_key, protocols: protocols, bootnodes: bootnodes, tcp_port: 0, udp_port: 0, ping_interval_secs: 1, discovery_interval_secs: 0.5, dial_outgoing_interval_secs: 0.5) end it "3 nodes connect each other" do protocols = 3.times.map{ mock_protocol } # setup 3 nodes bootnode = new_node(protocols: [protocols[0]]) node1 = nil node2 = nil bootnode_task = nil node1_task = nil node2_task = nil Async::Reactor.run do |task| bootnode_task = task.async do bootnode.run end task.reactor.after(0.1) do node1_task = task.async do task.sleep(0.1) while bootnode.udp_port.zero? || bootnode.tcp_port.zero? node1 = new_node(protocols: [protocols[1]], bootnodes: [bootnode.to_node]) node1.run end node2_task = task.async do task.sleep(0.1) while bootnode.udp_port.zero? || bootnode.tcp_port.zero? node2 = new_node(protocols: [protocols[2]], bootnodes: [bootnode.to_node]) node2.run end end # wait.. and check each node result task.reactor.after(5) do task.async do # wait few seconds... wait_seconds = 0 sleep_interval = 0.3 while wait_seconds < 15 && protocols.any?{|proto| proto.received_messages.count < 2} task.sleep(sleep_interval) wait_seconds += sleep_interval end # check peers attributes protocols.each do |proto| expect(proto.raw_local_node_id).not_to be_nil expect(proto.connected_peers.count - proto.disconnected_peers.count).to eq 2 end # because duplicate connection during booting phase, we maybe have few disconnected peer list_of_disconnected_peers_count = protocols.map{|protocol| protocol.disconnected_peers.count } # node received 2 messages expect(protocols[0].received_messages.count).to eq 2 expect(protocols[1].received_messages.count).to eq 2 expect(protocols[2].received_messages.count).to eq 2 # test disconnected_peers bootnode.disconnect_all node1.disconnect_all node2.disconnect_all protocols.each {|protocol| protocol.stop = true } task.sleep(0.5) # stop all async task bootnode_task.stop node1_task.stop node2_task.stop protocols.each_with_index do |protocol, i| expect(protocol.disconnected_peers.count - list_of_disconnected_peers_count[i]).to eq 2 end task.reactor.stop end end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p/network_state_spec.rb
ciri-p2p/spec/ciri/p2p/network_state_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'async' require 'ciri/p2p/errors' require 'ciri/p2p/network_state' require 'ciri/p2p/peer_store' require 'ciri/p2p/protocol' require 'ciri/p2p/rlpx/protocol_handshake' RSpec.describe Ciri::P2P::NetworkState do let(:eth_protocol) {mock_protocol_class.new(name: 'eth', version: 63, length: 17)} let(:old_eth_protocol) {mock_protocol_class.new(name: 'eth', version: 62, length: 8)} let(:hello_protocol) {mock_protocol_class.new(name: 'hello', version: 1, length: 16)} let(:caps) {[ Ciri::P2P::RLPX::Cap.new(name: 'eth', version: 63), Ciri::P2P::RLPX::Cap.new(name: 'eth', version: 62), Ciri::P2P::RLPX::Cap.new(name: 'hello', version: 1), ]} let(:handshake){Ciri::P2P::RLPX::ProtocolHandshake.new(version: 4, name: 'test', caps: caps, id: "\x00".b * 32)} let(:handshake_only_hello){Ciri::P2P::RLPX::ProtocolHandshake.new(version: 4, name: 'test', caps: [Ciri::P2P::RLPX::Cap.new(name: 'hello', version: 1)], id: "\x01".b * 32)} let(:handshake_only_hi){Ciri::P2P::RLPX::ProtocolHandshake.new(version: 4, name: 'test', caps: [Ciri::P2P::RLPX::Cap.new(name: 'hi', version: 1)], id: "\x01".b * 32)} let(:protocols){[ eth_protocol, old_eth_protocol, hello_protocol ]} let(:peer_store) { Ciri::P2P::PeerStore.new } let(:local_node_id) { key = Ciri::Key.random Ciri::P2P::NodeID.new(key) } # mock connection let(:connection) do Class.new do attr_reader :queue def initialize @queue = [] end def read_msg raise StandardError.new("empty queue") if queue.empty? queue.shift end def close end def closed? @queue.empty? end end.new end let(:mock_protocol_class) do Class.new(Ciri::P2P::Protocol) do attr_reader :protocol_initialized, :connected_peers, :disconnected_peers def initialized(context) @protocol_initialized = true @connected_peers = [] @disconnected_peers = [] end def connected(context) @connected_peers << context.peer end def disconnected(context) @disconnected_peers << context.peer end end end it 'handle peers connected and removed' do network_state = Ciri::P2P::NetworkState.new( protocols: protocols, peer_store: peer_store, local_node_id: local_node_id) Async::Reactor.run do |task| task.reactor.after(5) do raise StandardError.new("test timeout.. must something be wrong") end task.async do network_state.initialize_protocols network_state.new_peer_connected(connection, handshake, direction: :incoming) network_state.new_peer_connected(connection, handshake_only_hello, direction: :incoming) task.reactor.stop end end # check eth_protocol expect(eth_protocol.protocol_initialized).to be_truthy expect(eth_protocol.connected_peers.size).to eq 1 expect(eth_protocol.disconnected_peers.size).to eq 1 # check old_eth_protocol expect(old_eth_protocol.protocol_initialized).to be_truthy expect(old_eth_protocol.connected_peers.size).to eq 0 # check hello_protocol expect(hello_protocol.protocol_initialized).to be_truthy expect(hello_protocol.connected_peers.size).to eq 2 expect(hello_protocol.disconnected_peers.size).to eq 2 end it 'refuse peer connection if cannot match any protocols' do network_state = Ciri::P2P::NetworkState.new( protocols: protocols, peer_store: peer_store, local_node_id: local_node_id) Async::Reactor.run do |task| task.reactor.after(5) do raise StandardError.new("test timeout.. must something be wrong") end task.async do network_state.initialize_protocols expect do network_state.new_peer_connected(connection, handshake_only_hello, direction: :incoming) end.not_to raise_error expect do network_state.new_peer_connected(connection, handshake_only_hi, direction: :incoming) end.to raise_error(Ciri::P2P::UselessPeerError) task.reactor.stop end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p/discovery/protocol_spec.rb
ciri-p2p/spec/ciri/p2p/discovery/protocol_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'spec_helper' require 'ciri/p2p/discovery/protocol' require 'ciri/rlp' RSpec.describe Ciri::P2P::Discovery::Protocol do context 'dicovery message' do let(:key){Ciri::Key.random} let(:ping) do Ciri::P2P::Discovery::Protocol::Ping.new( version: 1, from: Ciri::P2P::Discovery::Protocol::From.new(sender_ip: IPAddr.new('127.0.0.1').to_i, sender_udp_port: 30303, sender_tcp_port: 30303), to: Ciri::P2P::Discovery::Protocol::To.new(recipient_ip: IPAddr.new('192.168.1.3').to_i, recipient_udp_port: 30303), expiration: Time.now.to_i + 3600 ) end it '#validate' do key = Ciri::Key.random msg = Ciri::Utils.keccak "hello world" signature = key.ecdsa_signature(msg) expect(Ciri::Key.ecdsa_recover(msg, signature).raw_public_key).to eq key.raw_public_key end it 'decode and encode message' do msg = Ciri::P2P::Discovery::Protocol::Message.pack(ping, private_key: key) encoded = msg.encode_message msg2 = Ciri::P2P::Discovery::Protocol::Message.decode_message(encoded) expect(msg.message_hash).to eq msg2.message_hash expect(msg.sender.to_s).to eq msg2.sender.to_s expect(msg.sender.to_bytes).to eq Ciri::P2P::NodeID.new(key).to_bytes expect(msg.packet).to eq msg2.packet end let(:too_big_msg) do Class.new do include Ciri::RLP::Serializable schema( data: Ciri::RLP::Bytes ) def self.code 0x00 end end.new(data: "0x00".b * 1280) end it '#pack' do expect do Ciri::P2P::Discovery::Protocol::Message.pack(ping, private_key: key) end.not_to raise_error expect do Ciri::P2P::Discovery::Protocol::Message.pack(too_big_msg, private_key: key) end.to raise_error(Ciri::P2P::InvalidMessageError) end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p/discovery/service_spec.rb
ciri-p2p/spec/ciri/p2p/discovery/service_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/p2p/discovery/service' RSpec.describe Ciri::P2P::Discovery::Service do def new_service(peer_store: Ciri::P2P::PeerStore.new, discovery_interval_secs: 1) Ciri::P2P::Discovery::Service.new( peer_store: peer_store, host: '127.0.0.1', udp_port: 0, tcp_port: 0, private_key: Ciri::Key.random, discovery_interval_secs: discovery_interval_secs, ) end context 'ping' do it 'perform ping/pong' do Async::Reactor.run do |task| # set a large interval to disable performing discovery interval = 1000 s1 = new_service(discovery_interval_secs: interval) s2 = new_service(discovery_interval_secs: interval) task.async { s1.run } task.async { s2.run } # how to avoid time dependency? task.reactor.after(0.1) do expect(s1.peer_store.has_seen?(s2.local_node_id.to_bytes)).to be_falsey s1.send(:send_ping, s2.local_node_id.to_bytes, s2.host, s2.udp_port) end task.reactor.after(0.2) do expect(s1.peer_store.has_seen?(s2.local_node_id.to_bytes)).to be_truthy task.reactor.stop end end end end context 'discovery' do it 'discovery peers' do Async::Reactor.run do |task| interval = 0.1 s1 = new_service(discovery_interval_secs: interval) s2 = new_service(discovery_interval_secs: interval) task.async { s1.run } task.async { s2.run } # sleep 0.1 seconds to wait s2 listen task.reactor.after(0.1) do s1.peer_store.add_node(Ciri::P2P::Node.new( node_id: s2.local_node_id, addresses: [Ciri::P2P::Address.new(ip: s2.host, udp_port: s2.udp_port, tcp_port: s2.tcp_port)])) # fill initial peers into kad_table s1.send(:setup_kad_table) end # check discovery status after 0.2 seconds task.reactor.after(0.5) do # s2 should discovery s1 addresses s2_discover_addresses = s2.peer_store.get_node_addresses(s1.local_node_id.to_bytes) expect(s2_discover_addresses).to eq [Ciri::P2P::Address.new(ip: s1.host, udp_port: s1.udp_port, tcp_port: s1.tcp_port)] task.reactor.stop end end end it 'discovery 3rd peer' do Async::Reactor.run do |task| interval = 0.1 s1 = new_service(discovery_interval_secs: interval) s2 = new_service(discovery_interval_secs: interval) s3 = new_service(discovery_interval_secs: interval) task.async { s1.run } task.async { s2.run } task.async { s3.run } # sleep 0.1 seconds to wait s2 listen task.reactor.after(0.1) do # s1 know s2 s1.peer_store.add_node(Ciri::P2P::Node.new( node_id: s2.local_node_id, addresses: [Ciri::P2P::Address.new(ip: s2.host, udp_port: s2.udp_port, tcp_port: s2.tcp_port)])) # fill initial peers into kad_table s1.send(:setup_kad_table) # s2 know s3 s2.peer_store.add_node(Ciri::P2P::Node.new( node_id: s3.local_node_id, addresses: [Ciri::P2P::Address.new(ip: s3.host, udp_port: s3.udp_port, tcp_port: s3.tcp_port)])) s2.send(:setup_kad_table) end # check discovery status task.reactor.after(1) do # wait few seconds... wait_seconds = 0 sleep_interval = 0.5 while wait_seconds < 10 && (s3_addresses = s1.peer_store.get_node_addresses(s3.local_node_id.to_bytes)).nil? task.sleep(sleep_interval) wait_seconds += sleep_interval end # check s3 address from s1 peer_store expect(s3_addresses).to eq [Ciri::P2P::Address.new(ip: s3.host, udp_port: s3.udp_port, tcp_port: s3.tcp_port)] task.reactor.stop end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p/rplx/encryption_handshake_spec.rb
ciri-p2p/spec/ciri/p2p/rplx/encryption_handshake_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/p2p/rlpx' require 'ciri/key' RSpec.describe Ciri::P2P::RLPX::EncryptionHandshake do it 'do handshake' do pk1 = Ciri::Key.random pk2 = Ciri::Key.random initiator_node_id = Ciri::P2P::NodeID.new pk1 receive_node_id = Ciri::P2P::NodeID.new pk2 initiator = Ciri::P2P::RLPX::EncryptionHandshake.new(private_key: pk1, remote_id: receive_node_id) receiver = Ciri::P2P::RLPX::EncryptionHandshake.new(private_key: pk2, remote_id: initiator_node_id) # initiator send auth-msg initiator_auth_msg = initiator.auth_msg auth_packet = initiator_auth_msg.rlp_encode auth_msg = Ciri::P2P::RLPX::AuthMsgV4.rlp_decode(auth_packet) # check serialize/deserialize expect(auth_msg).to eq initiator_auth_msg # receiver handle auth-msg, get remote random_pubkey nonce_bytes receiver.handle_auth_msg(auth_msg) expect(receiver.remote_random_key.raw_public_key).to eq initiator.random_key.raw_public_key expect(receiver.initiator_nonce).to eq initiator.initiator_nonce # receiver send auth-ack auth_ack_msg = receiver.auth_ack_msg auth_ack_packet = auth_ack_msg.rlp_encode initiator.handle_auth_ack_msg(auth_ack_msg) expect(initiator.remote_random_key.raw_public_key).to eq receiver.random_key.raw_public_key expect(initiator.receiver_nonce).to eq receiver.receiver_nonce #initiator derives secrets initiator_secrets = initiator.extract_secrets(auth_packet, auth_ack_packet, initiator: true) receiver_secrets = receiver.extract_secrets(auth_packet, auth_ack_packet, initiator: false) expect(initiator_secrets.remote_id).to eq receive_node_id expect(receiver_secrets.remote_id).to eq initiator_node_id end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p/rplx/connection_spec.rb
ciri-p2p/spec/ciri/p2p/rplx/connection_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'socket' require 'ciri/p2p/node' require 'ciri/p2p/rlpx/connection' require 'ciri/p2p/rlpx/protocol_handshake' RSpec.describe Ciri::P2P::RLPX::Connection do it 'handshake' do pk1 = Ciri::Key.random pk2 = Ciri::Key.random s1, s2 = UNIXSocket.pair initiator_node_id = Ciri::P2P::NodeID.new pk1 receive_node_id = Ciri::P2P::NodeID.new pk2 initiator = Ciri::P2P::RLPX::Connection.new(s1) receiver = Ciri::P2P::RLPX::Connection.new(s2) initiator_protocol_handshake = Ciri::P2P::RLPX::ProtocolHandshake.new( version: 1, name: "initiator", caps: [Ciri::P2P::RLPX::Cap.new(name: 'hello', version: 1)], listen_port: 33333, id: "ciri-initiator") receiver_protocol_handshake = Ciri::P2P::RLPX::ProtocolHandshake.new( version: 1, name: "receiver", caps: [Ciri::P2P::RLPX::Cap.new(name: 'nihao', version: 2)], listen_port: 22222, id: "ciri-receiver") # start initiator handshakes thr = Thread.new { initiator.encryption_handshake!(private_key: pk1, remote_node_id: receive_node_id) initiator.protocol_handshake!(initiator_protocol_handshake) } receiver.encryption_handshake!(private_key: pk2) # receiver get initiator_protocol_hanshake expect(receiver.protocol_handshake!(receiver_protocol_handshake)).to eq initiator_protocol_handshake # initiator get receiver_protocol_hanshake expect(thr.value).to eq receiver_protocol_handshake end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/spec/ciri/p2p/rplx/frame_io_spec.rb
ciri-p2p/spec/ciri/p2p/rplx/frame_io_spec.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'socket' require 'ciri/p2p/rlpx' require 'ciri/rlp' RSpec.describe Ciri::P2P::RLPX::FrameIO do it 'write_msg and read_msg' do aes_secret = 16.times.map {rand 8}.pack('c*') mac_secret = 16.times.map {rand 8}.pack('c*') egress_mac_init = 32.times.map {rand 8}.pack('c*') ingress_mac_init = 32.times.map {rand 8}.pack('c*') r, w = IO.pipe s1 = Ciri::P2P::RLPX::Secrets.new(aes: aes_secret, mac: mac_secret) s2 = Ciri::P2P::RLPX::Secrets.new(aes: aes_secret, mac: mac_secret) s1.ingress_mac, s1.egress_mac, s2.ingress_mac, s2.egress_mac = 4.times.map {Digest::SHA3.new(256)} s1.egress_mac.update(egress_mac_init) s1.ingress_mac.update(ingress_mac_init) f_io1 = Ciri::P2P::RLPX::FrameIO.new(w, s1) s2.egress_mac.update(ingress_mac_init) s2.ingress_mac.update(egress_mac_init) f_io2 = Ciri::P2P::RLPX::FrameIO.new(r, s2) ['hello world', 'Ethereum is awesome!', 'You known nothing, john snow!' ].each_with_index do |payload, i| encoded_payload = Ciri::RLP.encode(payload) f_io1.send_data(i, encoded_payload) msg = f_io2.read_msg expect(msg.code).to eq i expect(msg.payload).to eq encoded_payload end end it 'write_msg then read_msg in same time' do aes_secret = 16.times.map {rand 8}.pack('c*') mac_secret = 16.times.map {rand 8}.pack('c*') egress_mac_init = 32.times.map {rand 8}.pack('c*') ingress_mac_init = 32.times.map {rand 8}.pack('c*') r, w = UNIXSocket.pair s1 = Ciri::P2P::RLPX::Secrets.new(aes: aes_secret, mac: mac_secret) s2 = Ciri::P2P::RLPX::Secrets.new(aes: aes_secret, mac: mac_secret) s1.ingress_mac, s1.egress_mac, s2.ingress_mac, s2.egress_mac = 4.times.map {Digest::SHA3.new(256)} s1.egress_mac.update(egress_mac_init) s1.ingress_mac.update(ingress_mac_init) f_io1 = Ciri::P2P::RLPX::FrameIO.new(w, s1) s2.egress_mac.update(ingress_mac_init) s2.ingress_mac.update(egress_mac_init) f_io2 = Ciri::P2P::RLPX::FrameIO.new(r, s2) m1 = Ciri::RLP.encode('hello world') m2 = Ciri::RLP.encode('bye world') f_io1.send_data(1, m1) f_io2.send_data(1, m2) msg = f_io2.read_msg expect(msg.code).to eq 1 expect(msg.payload).to eq m1 end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p.rb
ciri-p2p/lib/ciri/p2p.rb
require "ciri/p2p/version" module Ciri module P2p # Your code goes here... end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/network_state.rb
ciri-p2p/lib/ciri/p2p/network_state.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'async' require 'async/semaphore' require 'ciri/utils/logger' require_relative 'peer' require_relative 'errors' require_relative 'protocol_context' module Ciri module P2P # NetworkState # maintaining current connected peers class NetworkState include Utils::Logger attr_reader :peers, :caps, :peer_store, :local_node_id def initialize(protocols:, peer_store:, local_node_id:, max_outgoing: 10, max_incoming: 10, ping_interval_secs: 15) @peers = {} @peers_lock = Async::Semaphore.new @peer_store = peer_store @protocols = protocols @local_node_id = local_node_id @max_outgoing = max_outgoing @max_incoming = max_incoming @ping_interval_secs = ping_interval_secs end def initialize_protocols(task: Async::Task.current) # initialize protocols @protocols.each do |protocol| context = ProtocolContext.new(self, protocol: protocol) task.async {protocol.initialized(context)} end end def number_of_attemp_outgoing @max_outgoing - @peers.values.select(&:outgoing?).count end def new_peer_connected(connection, handshake, direction:, task: Async::Task.current) @peers_lock.acquire do peer = Peer.new(connection, handshake, @protocols, direction: direction) # disconnect already connected peers if @peers.include?(peer.node_id) debug("[#{local_node_id.short_hex}] peer #{peer.inspect} is already connected") # disconnect duplicate connection peer.disconnect return end # check peers protocol_handshake_checks(handshake) @peers[peer.node_id] = peer info "[#{local_node_id.short_hex}] connect to new peer #{peer.inspect}" @peer_store.update_peer_status(peer.node_id, PeerStore::Status::CONNECTED) # run peer logic task.async do register_peer_protocols(peer) handling_peer(peer) end end end def disconnect_peer(peer, reason: nil) @peers_lock.acquire do # only disconnect from peers if direction correct to avoiding delete peer by mistake if (exist_peer = @peers[peer.node_id]) && exist_peer.direction == peer.direction info("[#{local_node_id.short_hex}] disconnect peer: #{peer.inspect}, reason: #{reason}") remove_peer(peer) peer.disconnect @peer_store.update_peer_status(peer.node_id, PeerStore::Status::DISCONNECTED) else debug("[#{local_node_id.short_hex}] Ignoring: disconnect peer: #{peer.inspect}, reason: #{reason}") end end end def disconnect_all debug("[#{local_node_id.short_hex}] disconnect all") peers.each_value do |peer| disconnect_peer(peer, reason: "disconnect all...") end end private def remove_peer(peer) @peers.delete(peer.node_id) deregister_peer_protocols(peer) end def register_peer_protocols(peer, task: Async::Task.current) peer.protocol_ios.dup.each do |protocol_io| task.async do # Protocol#connected context = ProtocolContext.new(self, peer: peer, protocol: protocol_io.protocol, protocol_io: protocol_io) context.protocol.connected(context) rescue StandardError => e error("Protocol#connected error: #{e}\nbacktrace: #{e.backtrace.join "\n"}") disconnect_peer(peer, reason: "Protocol#connected callback error: #{e}") end end end def deregister_peer_protocols(peer, task: Async::Task.current) peer.protocol_ios.dup.each do |protocol_io| task.async do # Protocol#connected context = ProtocolContext.new(self, peer: peer, protocol: protocol_io.protocol, protocol_io: protocol_io) context.protocol.disconnected(context) rescue StandardError => e error("Protocol#disconnected error: {e}\nbacktrace: #{e.backtrace.join "\n"}") disconnect_peer(peer, reason: "Protocol#disconnected callback error: #{e}") end end end # handling peer IO def handling_peer(peer, task: Async::Task.current) start_peer_io(peer) rescue Exception => e remove_peer(peer) error("remove peer #{peer}, error: #{e}") end # starting peer IO loop def start_peer_io(peer, task: Async::Task.current) _ping_timer = task.reactor.every(@ping_interval_secs) do task.async do ping(peer) rescue StandardError => e disconnect_peer(peer, reason: "ping error: #{e}") end end message_service = task.async do loop do raise DisconnectError.new("disconnect peer") if @disconnect msg = peer.connection.read_msg msg.received_at = Time.now handle_message(peer, msg) end rescue StandardError => e disconnect_peer(peer, reason: "io error: #{e}") error("io error: #{e}\n#{e.backtrace.join "\n"}") end message_service.wait end BLANK_PAYLOAD = RLP.encode([]).freeze # response pong to message def ping(peer) peer.connection.send_data(RLPX::Code::PING, BLANK_PAYLOAD) end # response pong to message def pong(peer) peer.connection.send_data(RLPX::Code::PONG, BLANK_PAYLOAD) end # handle peer message def handle_message(peer, msg, task: Async::Task.current) if msg.code == RLPX::Code::PING pong(peer) elsif msg.code == RLPX::Code::DISCONNECT reason = RLP.decode_with_type(msg.payload, Integer) raise DisconnectError.new("receive disconnect message, reason: #{reason}") elsif msg.code == RLPX::Code::PONG # TODO update peer node else # send msg to sub protocol if (protocol_io = peer.find_protocol_io_by_msg_code(msg.code)).nil? raise UnknownMessageCodeError.new("can't find protocol with msg code #{msg.code}") end # fix msg code msg.code -= protocol_io.offset task.async do # Protocol#received context = ProtocolContext.new(self, peer: peer, protocol: protocol_io.protocol, protocol_io: protocol_io) context.protocol.received(context, msg) end end end def protocol_handshake_checks(handshake) if @protocols && count_matching_protocols(handshake.caps) == 0 raise UselessPeerError.new('discovery useless peer') end end # {cap_name => cap_version} def caps_hash @caps_hash ||= @protocols.sort_by do |cap| cap.version end.reduce({}) do |caps_hash, cap| caps_hash[cap.name] = cap.version caps_hash end end # calculate count of matched protocols caps def count_matching_protocols(caps) caps.select do |cap| caps_hash[cap.name] == cap.version end.count end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/protocol_context.rb
ciri-p2p/lib/ciri/p2p/protocol_context.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'forwardable' module Ciri module P2P # ProtocolContext is used to manuaplate class ProtocolContext extend Forwardable attr_reader :peer, :protocol, :protocol_io def_delegators :@network_state, :local_node_id def initialize(network_state, peer: nil, protocol: nil, protocol_io: nil) @network_state = network_state @peer = peer @protocol = protocol @protocol_io = protocol_io end def send_data(code, data, peer: self.peer, protocol: self.protocol.name) ensure_peer(peer).find_protocol_io(protocol).send_data(code, data) end def raw_local_node_id @raw_local_node_id ||= local_node_id.to_bytes end def peers @network_state.peers.values end def find_peer(raw_node_id) @network_state.peers[raw_node_id] end private def ensure_peer(peer) return peer if peer.is_a?(P2P::Peer) @network_state.peers[peer] end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/version.rb
ciri-p2p/lib/ciri/p2p/version.rb
module Ciri module P2P VERSION = "0.3.0" end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/errors.rb
ciri-p2p/lib/ciri/p2p/errors.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri module P2P class Error < StandardError; end class UselessPeerError < Error; end class DisconnectError < Error; end class UnknownMessageCodeError < Error; end class InvalidMessageError < Error; end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/peer_store.rb
ciri-p2p/lib/ciri/p2p/peer_store.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils/logger' module Ciri module P2P # PeerStore store information of all peers we have seen #TODO rewrite with a database(sqlite) # Support score peers class PeerStore PEER_LAST_SEEN_VALID = 12 * 3600 # consider peer is valid if we seen it within 12 hours PING_EXPIRATION_IN = 10 * 60 # allow ping within 10 minutes # report peer behaviours module Behaviours INVALID_DATA = :invalid_data CONNECT = :connect PING = :ping FAILED_TO_CONNECT = :failed_to_connect FAILED_TO_PING = :failed_to_ping UNEXPECT_DISCONNECT = :unexpect_disconnect end include Behaviours # peer status module Status CONNECTED = :connected DISCONNECTED = :disconnected UNKNOWN = :unknown end include Status PEER_INITIAL_SCORE = 100 DEFAULT_SCORE_SCHEMA = { INVALID_DATA => -50, CONNECT => 10, PING => 5, FAILED_TO_PING => -10, FAILED_TO_CONNECT => -10, UNEXPECT_DISCONNECT => -20, } def initialize(score_schema:{}) @peers_ping_records = {} @peers_seen_records = {} @peers = {} @bootnodes = [] @ban_peers = {} @score_schema = DEFAULT_SCORE_SCHEMA.merge(score_schema) end def has_ping?(node_id, ping_hash, expires_in: PING_EXPIRATION_IN) return false if has_ban?(node_id) record = @peers_ping_records[node_id] if record && record[:ping_hash] == ping_hash && (record[:ping_at] + expires_in) > Time.now.to_i return true elsif record @peers_ping_records.delete(node_id) end false end # record ping message def update_ping(node_id, ping_hash, ping_at: Time.now.to_i) @peers_ping_records[node_id] = {ping_hash: ping_hash, ping_at: ping_at} end def update_last_seen(node_id, at: Time.now.to_i) @peers_seen_records[node_id] = at end def has_seen?(node_id, expires_in: PEER_LAST_SEEN_VALID) return false if has_ban?(node_id) seen = (last_seen_at = @peers_seen_records[node_id]) && (last_seen_at + expires_in > Time.now.to_i) # convert to bool !!seen end def add_bootnode(node) @bootnodes << node add_node(node) end def has_ban?(node_id, now: Time.now) record = @ban_peers[node_id] if record && (record[:ban_at].to_i + record[:timeout_secs]) > now.to_i true else @ban_peers.delete(node_id) false end end def ban_peer(node_id, now: Time.now, timeout_secs:600) @ban_peers[node_id] = {ban_at: now, timeout_secs: timeout_secs} end def report_peer(node_id, behaviour) score = @score_schema[behaviour] raise ValueError.new("unsupport report behaviour: #{behaviour}") if score.nil? if (node_info = @peers[node_id]) node_info[:score] += score end end # TODO find high scoring peers, use bootnodes as fallback def find_bootnodes(count) nodes = @bootnodes.sample(count) nodes + find_attempt_peers(count - nodes.size) end # TODO find high scoring peers def find_attempt_peers(count) @peers.values.reject do |peer_info| # reject already connected peers and bootnodes @bootnodes.include?(peer_info[:node]) || peer_status(peer_info[:node].node_id) == Status::CONNECTED end.sort_by do |peer_info| -peer_info[:score] end.map do |peer_info| peer_info[:node] end.take(count) end def add_node_addresses(node_id, addresses) node_info = @peers[node_id] node = node_info && node_info[:node] if node node.addresses = (node.addresses + addresses).uniq end end def get_node_addresses(node_id) peer_info = @peers[node_id] peer_info && peer_info[:node].addresses end def add_node(node) @peers[node.node_id] = {node: node, score: PEER_INITIAL_SCORE, status: Status::UNKNOWN} end def peer_status(node_id) if (peer_info = @peers[node_id]) peer_info[:status] else Status::UNKNOWN end end def update_peer_status(node_id, status) if (peer_info = @peers[node_id]) peer_info[:status] = status end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/peer.rb
ciri-p2p/lib/ciri/p2p/peer.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils' require 'ciri/rlp' require_relative 'rlpx' require_relative 'protocol_io' module Ciri module P2P # represent a connected remote node class Peer OUTBOUND = :outbound INBOUND = :inbound attr_reader :connection, :direction def initialize(connection, handshake, protocols, direction:) @connection = connection @handshake = handshake @protocols = protocols @protocol_io_hash = make_protocol_io_hash(protocols, handshake.caps, connection) @direction = direction end def outgoing? @direction == OUTBOUND end def incoming? @direction == INBOUND end def to_s @display_name ||= begin Utils.hex(node_id.to_bytes)[0..8] end end def inspect "<Peer:#{to_s} direction: #{@direction}>" end def hash node_id.to_bytes.hash end def ==(peer) self.class == peer.class && node_id.to_bytes == peer.node_id.to_bytes end alias eql? == # get NodeID object def node_id key = Ciri::Key.from_public_key(@handshake.id) @node_id ||= NodeID.new(key) end # disconnect peer connections def disconnect @connection.close end def disconnected? @connection.closed? end def protocol_ios @protocol_io_hash.values end def find_protocol(name) @protocol.find do |protocol| protocol.name == name end end def find_protocol_io(name) protocol_ios.find do |protocol_io| protocol_io.protocol.name == name end end # find ProtocolIO by raw message code # used by DEVP2P to find stream of sub-protocol def find_protocol_io_by_msg_code(raw_code) @protocol_io_hash.values.find do |protocol_io| offset = protocol_io.offset protocol = protocol_io.protocol raw_code >= offset && raw_code < offset + protocol.length end end private # return protocol_io_hash # handle multiple sub protocols upon one io def make_protocol_io_hash(protocols, caps, io) # sub protocol offset offset = RLPX::BASE_PROTOCOL_LENGTH result = {} # [name, version] as key protocols_hash = protocols.map {|protocol| [[protocol.name, protocol.version], protocol]}.to_h sorted_caps = caps.sort_by {|c| [c.name, c.version]} sorted_caps.each do |cap| protocol = protocols_hash[[cap.name, cap.version]] next unless protocol # ignore same name old protocols if (old = result[cap.name]) result.delete(cap.name) offset -= old.protocol.length end result[cap.name] = ProtocolIO.new(protocol, offset, io) # move offset, to support next protocol offset += protocol.length end result end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/node.rb
ciri-p2p/lib/ciri/p2p/node.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/key' require 'ciri/utils' module Ciri module P2P # present node id class NodeID attr_reader :public_key alias key public_key def initialize(public_key) unless public_key.is_a?(Ciri::Key) raise TypeError.new("expect Ciri::Key but get #{public_key.class}") end @public_key = public_key end def to_bytes @id ||= key.raw_public_key[1..-1] end def hash to_bytes.hash end def ==(other) self.class == other.class && to_bytes == other.to_bytes end def to_hex Ciri::Utils.hex to_bytes end alias to_s to_hex def short_hex @short_hex ||= to_hex[0..8] end end class Node attr_reader :node_id, :added_at attr_accessor :addresses class << self def parse(node_url) uri = URI.parse(node_url) node_id = NodeID.new(Ciri::Key.from_public_key(Ciri::Utils::dehex(uri.user))) address =Address.new(ip: uri.host, udp_port: uri.port, tcp_port: uri.port) new(node_id: node_id, addresses: [address]) end end def initialize(node_id:, addresses:, added_at: nil) @node_id = node_id @addresses = addresses @added_at = added_at end def ==(other) self.class == other.class && node_id == other.node_id end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/dialer.rb
ciri-p2p/lib/ciri/p2p/dialer.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'async/io' require 'async/io/stream' require_relative 'rlpx/connection' module Ciri module P2P # Discovery and dial new nodes class Dialer include RLPX def initialize(private_key:, handshake:) @private_key = private_key @handshake = handshake end # setup a new connection to node def dial(node) # connect tcp socket # Use Stream to buffer IO operation address = node.addresses&.first return unless address socket = Async::IO::Stream.new(Async::IO::Endpoint.tcp(address.ip.to_s, address.tcp_port).connect) c = Connection.new(socket) c.encryption_handshake!(private_key: @private_key, remote_node_id: node.node_id) remote_handshake = c.protocol_handshake!(@handshake) [c, remote_handshake] end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/rlpx.rb
ciri-p2p/lib/ciri/p2p/rlpx.rb
# frozen_string_literal: true # # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require_relative 'rlpx/message' require_relative 'rlpx/frame_io' require_relative 'rlpx/protocol_messages' require_relative 'rlpx/protocol_handshake' require_relative 'rlpx/encryption_handshake'
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/address.rb
ciri-p2p/lib/ciri/p2p/address.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri module P2P class Address attr_reader :ip, :udp_port, :tcp_port def initialize(ip:, udp_port:, tcp_port: udp_port) @ip = ip.is_a?(IPAddr) ? ip : IPAddr.new(ip) @udp_port = udp_port @tcp_port = tcp_port end def ==(other) self.class == other.class && ip == other.ip && udp_port == other.udp_port end def <=>(other) ip <=> other.ip end def inspect "<PeerStore::Address #{ip.inspect} udp_port: #{udp_port} tcp_port: #{tcp_port}>" end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/protocol.rb
ciri-p2p/lib/ciri/p2p/protocol.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils/logger' module Ciri module P2P # protocol represent P2P sub protocols class Protocol include Utils::Logger attr_reader :name, :version, :length def initialize(name:, version:, length:) @name = name @version = version @length = length end def initialized(context) debug("not implemented Protocol#initialized callback") end def received(context, data) debug("not implemented Protocol#received callback") end def connected(context) debug("not implemented Protocol#connected callback") end def disconnected(context) debug("not implemented Protocol#disconnected callback") end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/server.rb
ciri-p2p/lib/ciri/p2p/server.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'async' require 'async/io' require 'async/io/tcp_socket' require 'forwardable' require 'ciri/utils/logger' require_relative 'rlpx/connection' require_relative 'rlpx/protocol_handshake' require_relative 'errors' require_relative 'peer' require_relative 'network_state' require_relative 'dialer' require_relative 'discovery/service' require_relative 'dial_scheduler' module Ciri module P2P # P2P Server # maintain connection, node discovery, rlpx handshake class Server include Utils::Logger include RLPX extend Forwardable DEFAULT_MAX_PENDING_PEERS = 50 DEFAULT_DIAL_RATIO = 3 attr_reader :handshake, :dial_scheduler, :dialer, :local_address, :tcp_port def_delegators :@network_state, :disconnect_all def initialize(private_key:, protocols:, bootnodes: [], node_name: 'Ciri', host: '127.0.0.1', tcp_port: 33033, udp_port: 33033, max_outgoing: 10, max_incoming:10, ping_interval_secs: 15, discovery_interval_secs: 15, dial_outgoing_interval_secs: 25) @private_key = private_key @node_name = node_name # prepare handshake information @local_node_id = NodeID.new(@private_key) caps = protocols.map do |protocol| Cap.new(name: protocol.name, version: protocol.version) end @handshake = ProtocolHandshake.new(version: BASE_PROTOCOL_VERSION, name: @node_name, id: @local_node_id.to_bytes, caps: caps) @host = host @tcp_port = tcp_port @udp_port = udp_port @dialer = Dialer.new(private_key: private_key, handshake: @handshake) @peer_store = PeerStore.new @network_state = NetworkState.new( protocols: protocols, peer_store: @peer_store, local_node_id: @local_node_id, max_incoming: max_incoming, max_outgoing: max_outgoing, ping_interval_secs: ping_interval_secs) @bootnodes = bootnodes @discovery_interval_secs = discovery_interval_secs @dial_outgoing_interval_secs = dial_outgoing_interval_secs end def udp_port @discovery_service&.udp_port || @udp_port end def to_node address = Address.new(ip: @host, tcp_port: tcp_port, udp_port: udp_port) Node.new(node_id: @local_node_id, addresses: [address]) end # return reactor to wait def run # setup bootnodes @bootnodes.each do |node| @peer_store.add_bootnode(node) end # start server and services Async::Reactor.run do |task| # initialize protocols @network_state.initialize_protocols # wait sub tasks task.async do task.async do # Wait for server started listen # we use listened port to start DiscoveryService to allow 0 port task.sleep(0.5) until @local_address # start discovery service @discovery_service = Discovery::Service.new( peer_store: @peer_store, private_key: @private_key, host: @host, udp_port: @udp_port, tcp_port: @tcp_port, discovery_interval_secs: @discovery_interval_secs) task.async { @discovery_service.run } # start dial outgoing nodes @dial_scheduler = DialScheduler.new( @network_state, @dialer, dial_outgoing_interval_secs: @dial_outgoing_interval_secs) task.async {@dial_scheduler.run} end task.async {start_listen} end.wait end end # start listen and accept clients def start_listen(task: Async::Task.current) endpoint = Async::IO::Endpoint.tcp(@host, @tcp_port) endpoint.bind do |socket| @local_address = socket.local_address info("start accept connections -- listen on #{@local_address.getnameinfo.join(":")}") # update tcp_port if it is 0 if @tcp_port.zero? @tcp_port = @local_address.ip_port end socket.listen(Socket::SOMAXCONN) loop do client, _addrinfo = socket.accept c = Connection.new(client) c.encryption_handshake!(private_key: @private_key) remote_handshake = c.protocol_handshake!(handshake) @network_state.new_peer_connected(c, remote_handshake, direction: Peer::INBOUND) end end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/dial_scheduler.rb
ciri-p2p/lib/ciri/p2p/dial_scheduler.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'async' require 'ciri/utils/logger' module Ciri module P2P # DialScheduler # establish outoging connections class DialScheduler include Utils::Logger def initialize(network_state, dialer, dial_outgoing_interval_secs: 15) @network_state = network_state @dialer = dialer @dial_outgoing_interval_secs = dial_outgoing_interval_secs end def run(task: Async::Task.current) dial_bootnodes # dial outgoing peers every 15 seconds task.reactor.every(@dial_outgoing_interval_secs) do task.async do schedule_dialing_tasks end end end private def dial_bootnodes @network_state.peer_store.find_bootnodes(@network_state.number_of_attemp_outgoing).each do |node| conn, handshake = @dialer.dial(node) @network_state.new_peer_connected(conn, handshake, direction: Peer::OUTBOUND) end end def schedule_dialing_tasks @network_state.peer_store.find_attempt_peers(@network_state.number_of_attemp_outgoing).each do |node| # avoid dial self or connected peers next if @network_state.peers.include?(node.raw_node_id) || node.raw_node_id == @network_state.local_node_id conn, handshake = @dialer.dial(node) @network_state.new_peer_connected(conn, handshake, direction: Peer::OUTBOUND) end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/kad.rb
ciri-p2p/lib/ciri/p2p/kad.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils/logger' require 'ciri/utils' require 'ciri/p2p/node' require 'forwardable' module Ciri module P2P # Kademlia algorithm # modified from https://github.com/ethereum/py-evm/blob/master/p2p/kademlia.py module Kad K_BITS = 8 K_BUCKET_SIZE = 16 K_REQUEST_TIMEOUT = 0.9 K_IDLE_BUCKET_REFRESH_INTERVAL = 3600 K_PUBKEY_SIZE = 512 K_ID_SIZE = 256 K_MAX_NODE_ID = 2 ** K_ID_SIZE - 1 class Node attr_reader :id, :node_id def initialize(node_id) @node_id = node_id @id = Utils.big_endian_decode(Utils.keccak(node_id.to_bytes)) end def distance_to(id) @id ^ id end def ==(other) self.class == other.class && self.id == other.id end def <=>(other) @id <=> other.id end end class KBucket attr_reader :k_size, :nodes, :start_id, :end_id, :last_updated, :replacement_cache def initialize(start_id:, end_id:, k_size: K_BUCKET_SIZE) @start_id = start_id @end_id = end_id @k_size = k_size @nodes = [] @replacement_cache = [] @last_updated = Time.now.to_i end # use to compute node distance with kbucket def midpoint @start_id + (@end_id - @start_id) / 2 end def distance_to(id) midpoint ^ id end # find neighbour nodes def nodes_by_distance_to(id) @nodes.sort_by do |node| node.distance_to(id) end end # split to two kbucket by midpoint def split split_point = midpoint lower = KBucket.new(start_id: @start_id, end_id: split_point) upper = KBucket.new(start_id: split_point + 1, end_id: @end_id) @nodes.each do |node| if node.id <= split_point lower.add(node) else upper.add(node) end end @replacement_cache.each do |node| if node.id <= split_point lower.replacement_cache << node else upper.replacement_cache << node end end [lower, upper] end def delete(node) @nodes.delete(node) end def cover?(node) @start_id <= node.id && node.id <= @end_id end def full? @nodes.size == k_size end # Try add node into bucket # if node is exists, it is moved to the tail # if the node is node exists and bucket not full, it is added at tail # if the bucket is full, node will added to replacement_cache, and return the head of the list, which should be evicted if it failed to respond to a ping. def add(node) @last_updated = Time.now.to_i if @nodes.include?(node) @nodes.delete(node) @nodes << node elsif @nodes.size < k_size @nodes << node else @replacement_cache << node return head end nil end def head @nodes[0] end def include?(node) @nodes.include?(node) end def size @nodes.size end end class RoutingTable attr_reader :buckets, :local_node def initialize(local_node:) @local_node = local_node @buckets = [KBucket.new(start_id: 0, end_id: K_MAX_NODE_ID)] end def get_random_nodes(count) count = size if count > size nodes = [] while nodes.size < count bucket = @buckets.sample next if bucket.nodes.empty? node = bucket.nodes.sample unless nodes.include?(node) nodes << node end end nodes end def idle_buckets bucket_idled_at = Time.now.to_i - K_IDLE_BUCKET_REFRESH_INTERVAL @buckets.select do |bucket| bucket.last_updated < bucket_idled_at end end def not_full_buckets @buckets.select do |bucket| !bucket.full? end end def delete_node(node) find_bucket_for_node(node).delete(node) end def update(node_id) add_node(Node.new(node_id)) end def add_node(node) raise ArgumentError.new("can't add local_node") if @local_node == node bucket = find_bucket_for_node(node) eviction_candidate = bucket.add(node) # bucket is full, otherwise will return nil if eviction_candidate depth = compute_shared_prefix_bits(bucket.nodes) if bucket.cover?(@local_node) || (depth % K_BITS != 0 && depth != K_ID_SIZE) split_bucket(@buckets.index(bucket)) return add_node(node) end return eviction_candidate end nil end def buckets_by_distance_to(id) @buckets.sort_by do |bucket| bucket.distance_to(id) end end def include?(node) find_bucket_for_node(node).include?(node) end def size @buckets.map(&:size).sum end def each_node(&blk) @buckets.each do |bucket| bucket.nodes do |node| blk.call(node) end end end def find_neighbours(id, k: K_BUCKET_SIZE) # convert id to integer unless id.is_a?(Integer) id = Node.new(id).id end nodes = [] buckets_by_distance_to(id).each do |bucket| bucket.nodes_by_distance_to(id).each do |node| if node.id != id nodes << node # find 2 * k nodes to avoid edge cases break if nodes.size == k * 2 end end end sort_by_distance(nodes, id)[0...k] end # do binary search to find node def find_bucket_for_node(node) @buckets.bsearch do |bucket| bucket.end_id >= node.id end end private def split_bucket(index) bucket = @buckets[index] a, b = bucket.split @buckets[index] = a @buckets.insert(index + 1, b) end def compute_shared_prefix_bits(nodes) return K_ID_SIZE if nodes.size < 2 bits = nodes.map{|node| to_binary(node.id) } (1..K_ID_SIZE).each do |i| # check common prefix shared by nodes if bits.map{|b| b[0..i]}.uniq.size != 1 return i - 1 end end end def sort_by_distance(nodes, target_id) nodes.sort_by do |node| node.distance_to(target_id) end end def to_binary(x) x.to_s(2).b.rjust(K_ID_SIZE, "\x00".b) end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/protocol_io.rb
ciri-p2p/lib/ciri/p2p/protocol_io.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'forwardable' require 'async/semaphore' require_relative 'rlpx/message' module Ciri module P2P # send/read sub protocol msg class ProtocolIO class Error < StandardError end class InvalidMessageCode < Error end attr_reader :protocol, :offset def initialize(protocol, offset, frame_io) @protocol = protocol @offset = offset @frame_io = frame_io @semaphore = Async::Semaphore.new end def send_data(code, data) @semaphore.acquire do msg = RLPX::Message.new(code: code, size: data.size, payload: data) write_msg(msg) end end def write_msg(msg) raise InvalidMessageCode, "code #{msg.code} must less than length #{protocol.length}" if msg.code > protocol.length msg.code += offset @frame_io.write_msg(msg) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/discovery/protocol.rb
ciri-p2p/lib/ciri/p2p/discovery/protocol.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/utils/logger' require 'ciri/key' require 'ciri/rlp' require 'ciri/p2p/node' require 'ciri/p2p/errors' require 'ipaddr' module Ciri module P2P module Discovery module Protocol # implement the DiscV4 protocol # https://github.com/ethereum/devp2p/blob/master/discv4.md class Message MAX_LEN=1280 attr_reader :message_hash, :packet_type, :packet_data def initialize(message_hash:, signature:, packet_type:, packet_data:) @message_hash = message_hash @signature = signature @packet_type = packet_type @packet_data = packet_data end # compute key and return NodeID def sender @sender ||= begin encoded_packet_type = Utils.big_endian_encode(packet_type) public_key = Key.ecdsa_recover(Utils.keccak(encoded_packet_type + packet_data), @signature) NodeID.new(public_key) end end def packet packet_class = case @packet_type when Ping::CODE Ping when Pong::CODE Pong when FindNode::CODE FindNode when Neighbors::CODE Neighbors else raise UnknownMessageCodeError.new("unkonwn discovery message code: #{@packet_type}") end # TODO according discv4 protocol, rlp_decode should support ignore additional elements # we should support ignore_extra_data option in Ciri::RLP packet_class.rlp_decode @packet_data end # validate message hash and signature def validate encoded_packet_type = Utils.big_endian_encode(packet_type) raise InvalidMessageError.new("mismatch hash") if message_hash != Utils.keccak(@signature + encoded_packet_type + packet_data) begin sender rescue StandardError => e raise InvalidMessageError.new("recover sender error: #{e}") end end # encode message to string def encode_message buf = String.new buf << message_hash buf << @signature buf << packet_type buf << packet_data buf end class << self # return a Message def decode_message(raw_bytes) hash = raw_bytes[0...32] # signature is 65 length r,s,v signature = raw_bytes[32...97] packet_type = Utils.big_endian_decode raw_bytes[97] packet_data = raw_bytes[98..-1] Message.new(message_hash: hash, signature: signature, packet_type: packet_type, packet_data: packet_data) end # return a new message instance include packet def pack(packet, private_key:) packet_data = Ciri::RLP.encode(packet) packet_type = packet.class.code encoded_packet_type = Utils.big_endian_encode(packet_type) signature = private_key.ecdsa_signature(Utils.keccak(encoded_packet_type + packet_data)).to_s hash = Utils.keccak(signature + encoded_packet_type + packet_data) if (msg_size=hash.size + signature.size + encoded_packet_type.size + packet_data.size) > MAX_LEN raise InvalidMessageError.new("failed to pack, message size is too long, size: #{msg_size}, max_len: #{MAX_LEN}") end Message.new(message_hash: hash, signature: signature, packet_type: packet_type, packet_data: packet_data) end end end # a struct represent which node send this packet class From include Ciri::RLP::Serializable # we should not trust the sender_ip field schema( sender_ip: Integer, sender_udp_port: Integer, sender_tcp_port: Integer, ) end # a struct represent which node is target of this packet class To include Ciri::RLP::Serializable # because discv4 protocol has not give us a name of last field, # we just keep the field value 0 and guess it name should be recipient_tcp_port # https://github.com/ethereum/devp2p/blob/master/discv4.md#ping-packet-0x01 schema( recipient_ip: Integer, recipient_udp_port: Integer, recipient_tcp_port: Integer, ) default_data(recipient_tcp_port: 0) class << self def from_inet_addr(address) from_host_port(address.ip_address, address.ip_port) end def from_host_port(host, port) new(recipient_ip: host.is_a?(IPAddr) ? host.to_i : IPAddr.new(host).to_i, recipient_udp_port: port) end end end # abstract class class Packet def self.code self::CODE end end class Ping < Packet include Ciri::RLP::Serializable CODE = 0x01 schema( version: Integer, from: From, to: To, expiration: Integer, ) default_data(version: 0) end class Pong < Packet include Ciri::RLP::Serializable CODE = 0x02 schema( to: To, ping_hash: RLP::Bytes, expiration: Integer, ) end class FindNode < Packet include Ciri::RLP::Serializable CODE = 0x03 schema( target: RLP::Bytes, expiration: Integer, ) end class Neighbors < Packet include Ciri::RLP::Serializable CODE = 0x04 # neighbour info class Node include Ciri::RLP::Serializable schema( ip: Integer, udp_port: Integer, tcp_port: Integer, node_id: RLP::Bytes, ) end schema( nodes: [Node], expiration: Integer, ) end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/discovery/service.rb
ciri-p2p/lib/ciri/p2p/discovery/service.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. # TODO Items: # [x] implement k-buckets algorithm # [x] implement peerstore(may use sqlite) # [ ] implement a simple scoring system # [ ] testing require 'async' require 'async/io/udp_socket' require 'async/io/endpoint/each' require 'ciri/utils/logger' require 'ciri/core_ext' require 'ciri/p2p/node' require 'ciri/p2p/address' require 'ciri/p2p/peer_store' require 'ciri/p2p/kad' require_relative 'protocol' using Ciri::CoreExt module Ciri module P2P module Discovery # Implement the DiscV4 protocol # https://github.com/ethereum/devp2p/blob/master/discv4.md # notice difference between PeerStore and Kad, # we use PeerStore to store all peers we known(upon 8192), # and use Kad to store our neighbours for discovery query. class Service include Utils::Logger # use message classes defined in Discovery include Protocol attr_reader :peer_store, :local_node_id, :host, :udp_port, :tcp_port # we should consider search from peer_store instead connect to bootnodes everytime def initialize(peer_store:, host:, udp_port:, tcp_port:, private_key:, discovery_interval_secs: 15) @discovery_interval_secs = discovery_interval_secs @cache = Set.new @host = host @udp_port = udp_port @tcp_port = tcp_port @peer_store = peer_store @private_key = private_key @local_node_id = NodeID.new(private_key) @kad_table = Kad::RoutingTable.new(local_node: Kad::Node.new(@local_node_id)) setup_kad_table end def run(task: Async::Task.current) # start listening task.async do start_listen end # search peers every x seconds task.reactor.every(@discovery_interval_secs) do task.async do perform_discovery end end end private def start_listen(task: Async::Task.current) endpoint = Async::IO::Endpoint.udp(@host, @udp_port) endpoint.bind do |socket| @local_address = socket.local_address # update port if port is zero if @udp_port.zero? @udp_port = @local_address.ip_port end info "start discovery server on udp_port: #{@udp_port} tcp_port: #{@tcp_port}\nlocal_node_id: #{@local_node_id}" loop do # read discovery message packet, address = socket.recvfrom(Discovery::Protocol::Message::MAX_LEN) handle_request(packet, address) end end end MESSAGE_EXPIRATION_IN = 10 * 60 # set 10 minutes later to expiration message def handle_request(raw_packet, address, now: Time.now.to_i) msg = Message.decode_message(raw_packet) msg.validate if msg.packet.expiration < now trace("ignore expired message, sender: #{msg.sender}, expired_at: #{msg.packet.expiration}") return end raw_node_id = msg.sender.dehex case msg.packet_type when Ping::CODE @kad_table.update(raw_node_id) from = msg.packet.from from_ip = IPAddr.new(from.sender_ip, Socket::AF_INET) from_udp_port = from.sender_udp_port from_tcp_port = from.sender_tcp_port from_address = Address.new( ip: from_ip, udp_port: from_udp_port, tcp_port: from_tcp_port) debug("receive ping msg from #{from_address.inspect}") # respond pong pong = Pong.new(to: To.from_host_port(from_ip, from_udp_port), ping_hash: msg.message_hash, expiration: Time.now.to_i + MESSAGE_EXPIRATION_IN) pong_msg = Message.pack(pong, private_key: @private_key).encode_message send_msg(pong_msg, from_ip.to_s, from_udp_port) @peer_store.add_node(Node.new(raw_node_id: raw_node_id, addresses: [from_address])) when Pong::CODE # check pong if @peer_store.has_ping?(raw_node_id, msg.packet.ping_hash) # update peer last seen @peer_store.update_last_seen(msg.sender.dehex) else @peer_store.ban_peer(msg.sender.dehex) end when FindNode::CODE unless @peer_store.has_seen?(raw_node_id) # consider add to denylist return end nodes = find_neighbours(msg.packet.target, 20).map do |raw_node_id, addr| Neighbors::Node.new(ip: addr.ip.to_i, udp_port: addr.udp_port, tcp_port: addr.tcp_port, node_id: raw_node_id) end neighbors = Neighbors.new(nodes: nodes, expiration: Time.now.to_i + MESSAGE_EXPIRATION_IN) send_msg_to_node(Message.pack(neighbors, private_key: @private_key).encode_message, raw_node_id) @peer_store.update_last_seen(raw_node_id) when Neighbors::CODE unless @peer_store.has_seen?(raw_node_id) # consider add to denylist return end debug("receive neighours #{msg.packet.nodes.size} from #{raw_node_id.hex}") msg.packet.nodes.each do |node| next if node.node_id == local_node_id debug("receive neighour #{node} from #{raw_node_id.hex}") ip = IPAddr.new(node.ip, Socket::AF_INET) address = Address.new(ip: ip, udp_port: node.udp_port, tcp_port: node.tcp_port) @peer_store.add_node(Node.new(raw_node_id: node.node_id.to_bytes, addresses: [address])) # add new discovered node_id @kad_table.update(node.node_id) end @kad_table.update(raw_node_id) @peer_store.update_last_seen(raw_node_id) else @peer_store.ban_peer(msg.sender.dehex) raise UnknownMessageCodeError.new("can't handle unknown code in discovery protocol, code: #{msg.packet_type}") end rescue StandardError => e @peer_store.ban_peer(msg.sender.dehex) error("discovery error: #{e} from address: #{address}\nbacktrace:#{e.backtrace.join("\n")}") end def send_ping_to_address(target_node_id, address) send_ping(target_node_id, address[3], address[1]) end # send discover ping to peer def send_ping(target_node_id, host, port) ping = Ping.new(to: To.from_host_port(host, port), from: From.new( sender_ip: IPAddr.new(@host).to_i, sender_udp_port: @udp_port, sender_tcp_port: @tcp_port), expiration: Time.now.to_i + MESSAGE_EXPIRATION_IN) ping_msg = Message.pack(ping, private_key: @private_key) send_msg(ping_msg.encode_message, host, port) @peer_store.update_ping(target_node_id, ping_msg.message_hash) end def send_msg_to_node(msg, raw_node_id) address = @peer_store.get_node_addresses(raw_node_id)&.first raise ArgumentsError.new("can't found peer address of #{raw_node_id.hex} from peer_store") unless address send_msg(msg, address.ip.to_s, address.udp_port) end def send_msg(msg, host, port) socket = Async::IO::UDPSocket.new(UDPSocket.new) socket.send(msg, 0, host, port) end # find nerly neighbours def find_neighbours(raw_node_id, count) @kad_table.find_neighbours(raw_node_id, k: count).map do |node| [node.node_id.to_bytes, @peer_store.get_node_addresses(node.node_id.to_bytes)&.first] end.delete_if do |_, addr| addr.nil? end end def setup_kad_table if @kad_table.size.zero? @peer_store.find_bootnodes(20).each do |node| next if @local_node_id == node.node_id debug("setup kad_table with #{node}") @kad_table.update(node.node_id) end end end def perform_discovery(count_of_query_nodes=15, task: Async::Task.current) query_node = NodeID.new(Key.random) query_target = query_node.dehex # randomly search @kad_table.get_random_nodes(15).each do |node| address = @peer_store.get_node_addresses(node.node_id)&.first next unless address # start query node in async task task.async do debug("perform discovery #{address}") send_ping(node.node_id, address.ip.to_s, address.udp_port) query = FindNode.new(target: query_target, expiration: Time.now.to_i + MESSAGE_EXPIRATION_IN) query_msg = Message.pack(query, private_key: @private_key).encode_message send_msg(query_msg, address.ip.to_s, address.udp_port) end end end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/rlpx/encryption_handshake.rb
ciri-p2p/lib/ciri/p2p/rlpx/encryption_handshake.rb
# frozen_string_literal: true # # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/key' require_relative 'secrets' module Ciri module P2P module RLPX SHA_LENGTH = 32 SIGNATURE_LENGTH = 65 PUBLIC_KEY_LENGTH = 64 ECIES_OVERHEAD = 65 + 16 + 32 AUTH_MSG_LENGTH = SIGNATURE_LENGTH + SHA_LENGTH + PUBLIC_KEY_LENGTH + SHA_LENGTH + 1 AUTH_RESP_MSG_LENGTH = PUBLIC_KEY_LENGTH + SHA_LENGTH + 1 HANDSHAKE_TIMEOUT = 5 ENC_AUTH_MSG_LENGTH = AUTH_MSG_LENGTH + ECIES_OVERHEAD ENC_AUTH_RESP_MSG_LENGTH = AUTH_RESP_MSG_LENGTH + ECIES_OVERHEAD # handle key exchange handshake class EncryptionHandshake attr_reader :private_key, :remote_key, :remote_random_key, :initiator_nonce, :receiver_nonce, :remote_id def initialize(private_key:, remote_id:) @private_key = private_key @remote_id = remote_id end def remote_key @remote_key || @remote_id.key end def random_key @random_key ||= Ciri::Key.random end def auth_msg # make nonce bytes nonce = random_nonce(SHA_LENGTH) @initiator_nonce = nonce # remote first byte tag token = dh_compute_key(private_key, remote_key) raise StandardError.new("token size #{token.size} not correct") if token.size != nonce.size # xor signed = xor(token, nonce) signature = random_key.ecdsa_signature(signed).signature initiator_pubkey = private_key.raw_public_key[1..-1] AuthMsgV4.new(signature: signature, initiator_pubkey: initiator_pubkey, nonce: nonce, version: 4) end def handle_auth_msg(msg) @remote_key = Ciri::Key.new(raw_public_key: "\x04" + msg.initiator_pubkey) @initiator_nonce = msg.nonce token = dh_compute_key(private_key, @remote_key) signed = xor(token, msg.nonce) @remote_random_key = Ciri::Key.ecdsa_recover(signed, msg.signature) end def auth_ack_msg # make nonce bytes nonce = random_nonce(SHA_LENGTH) @receiver_nonce = nonce random_pubkey = random_key.raw_public_key[1..-1] AuthRespV4.new(random_pubkey: random_pubkey, nonce: nonce, version: 4) end def handle_auth_ack_msg(msg) # make nonce bytes @receiver_nonce = msg.nonce @remote_random_key = Ciri::Key.new(raw_public_key: "\x04" + msg.random_pubkey) end def extract_secrets(auth_packet, auth_ack_packet, initiator:) secret = dh_compute_key(random_key, remote_random_key) shared_secret = Ciri::Utils.keccak(secret, Ciri::Utils.keccak(receiver_nonce, initiator_nonce)) aes_secret = Ciri::Utils.keccak(secret, shared_secret) mac = Ciri::Utils.keccak(secret, aes_secret) secrets = Secrets.new(remote_id: remote_id, aes: aes_secret, mac: mac) # initial secrets macs mac1 = Digest::SHA3.new(256) mac1.update xor(mac, receiver_nonce) mac1.update auth_packet mac2 = Digest::SHA3.new(256) mac2.update xor(mac, initiator_nonce) mac2.update auth_ack_packet if initiator secrets.egress_mac = mac1 secrets.ingress_mac = mac2 else secrets.egress_mac = mac2 secrets.ingress_mac = mac1 end secrets end private def dh_compute_key(private_key, public_key) private_key.ec_key.dh_compute_key(public_key.ec_key.public_key) end def xor(b1, b2) b1.each_byte.with_index.map {|b, i| b ^ b2[i].ord}.pack('c*') end def random_nonce(size) size.times.map {rand(8)}.pack('c*') end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/rlpx/protocol_messages.rb
ciri-p2p/lib/ciri/p2p/rlpx/protocol_messages.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/key' require 'ciri/rlp/serializable' module Ciri module P2P module RLPX # RLPX protocol code module Code HANDSHAKE = 0x00 DISCONNECT = 0x01 PING = 0x02 PONG = 0x03 end BASE_PROTOCOL_VERSION = 5 BASE_PROTOCOL_LENGTH = 16 BASE_PROTOCOL_MAX_MSG_SIZE = 2 * 1024 SNAPPY_PROTOCOL_VERSION = 5 ### messages class AuthMsgV4 include Ciri::RLP::Serializable schema( signature: RLP::Bytes, initiator_pubkey: RLP::Bytes, nonce: RLP::Bytes, version: Integer ) # keep this field let client known how to format(plain or eip8) attr_accessor :got_plain end class AuthRespV4 include Ciri::RLP::Serializable schema( random_pubkey: RLP::Bytes, nonce: RLP::Bytes, version: Integer ) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/rlpx/errors.rb
ciri-p2p/lib/ciri/p2p/rlpx/errors.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. module Ciri module P2P module RLPX # RLPX basic error class Error < StandardError end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/rlpx/protocol_handshake.rb
ciri-p2p/lib/ciri/p2p/rlpx/protocol_handshake.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp/serializable' module Ciri module P2P module RLPX class Cap include Ciri::RLP::Serializable schema( name: RLP::Bytes, version: Integer ) end # handle protocol handshake class ProtocolHandshake include Ciri::RLP::Serializable schema( version: Integer, name: RLP::Bytes, caps: [Cap], listen_port: Integer, id: RLP::Bytes ) default_data(listen_port: 0) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/rlpx/message.rb
ciri-p2p/lib/ciri/p2p/rlpx/message.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' module Ciri module P2P module RLPX # RLPX message class Message include Ciri::RLP::Serializable attr_accessor :received_at schema( code: Integer, size: Integer, payload: RLP::Bytes ) end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false
ciri-ethereum/ciri
https://github.com/ciri-ethereum/ciri/blob/a4ce792aa04e15d6c6e40d10474dfc73008de5ec/ciri-p2p/lib/ciri/p2p/rlpx/connection.rb
ciri-p2p/lib/ciri/p2p/rlpx/connection.rb
# frozen_string_literal: true # Copyright (c) 2018 by Jiang Jinyang <jjyruby@gmail.com> # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # copies of the Software, and to permit persons to whom the Software is # furnished to do so, subject to the following conditions: # # The above copyright notice and this permission notice shall be included in # all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN # THE SOFTWARE. require 'ciri/rlp' require 'socket' require 'forwardable' require_relative 'frame_io' require_relative 'protocol_messages' require_relative 'errors' require_relative 'encryption_handshake' module Ciri module P2P module RLPX # RLPX::Connection implement RLPX protocol operations # all operations end with bang(!) class Connection extend Forwardable def_delegators :@frame_io, :read_msg, :write_msg, :send_data, :closed?, :close class Error < RLPX::Error end class MessageOverflowError < Error end class UnexpectedMessageError < Error end class FormatError < Error end def initialize(io) set_timeout(io) @io = io @frame_io = nil end # Encryption handshake, exchange keys with node, must been invoked before other operations def encryption_handshake!(private_key:, remote_node_id: nil) enc_handshake = EncryptionHandshake.new(private_key: private_key, remote_id: remote_node_id) secrets = remote_node_id.nil? ? receiver_enc_handshake(enc_handshake) : initiator_enc_handshake(enc_handshake) @frame_io = FrameIO.new(@io, secrets) end # protocol handshake def protocol_handshake!(our_hs) @frame_io.send_data(Code::HANDSHAKE, our_hs.rlp_encode) remote_hs = read_protocol_handshake # enable snappy compress if remote peer support @frame_io.snappy = remote_hs.version >= SNAPPY_PROTOCOL_VERSION remote_hs end private def receiver_enc_handshake(receiver) auth_msg_binary, auth_packet = read_enc_handshake_msg(ENC_AUTH_MSG_LENGTH, receiver.private_key) auth_msg = AuthMsgV4.rlp_decode(auth_msg_binary) receiver.handle_auth_msg(auth_msg) auth_ack_msg = receiver.auth_ack_msg auth_ack_msg_plain_text = auth_ack_msg.rlp_encode auth_ack_packet = if auth_msg.got_plain raise NotImplementedError.new('not support pre eip8 plain text seal') else seal_eip8(auth_ack_msg_plain_text, receiver) end @io.write(auth_ack_packet) @io.flush receiver.extract_secrets(auth_packet, auth_ack_packet, initiator: false) end def initiator_enc_handshake(initiator) initiator_auth_msg = initiator.auth_msg auth_msg_plain_text = initiator_auth_msg.rlp_encode # seal eip8 auth_packet = seal_eip8(auth_msg_plain_text, initiator) @io.write(auth_packet) @io.flush auth_ack_mgs_binary, auth_ack_packet = read_enc_handshake_msg(ENC_AUTH_RESP_MSG_LENGTH, initiator.private_key) auth_ack_msg = AuthRespV4.rlp_decode auth_ack_mgs_binary initiator.handle_auth_ack_msg(auth_ack_msg) initiator.extract_secrets(auth_packet, auth_ack_packet, initiator: true) end def read_enc_handshake_msg(plain_size, private_key) packet = @io.read(plain_size) decrypt_binary_msg = begin private_key.ecies_decrypt(packet) rescue Crypto::ECIESDecryptionError => e nil end # pre eip old plain format return decrypt_binary_msg if decrypt_binary_msg # try decode eip8 format prefix = packet[0...2] size = Ciri::Utils.big_endian_decode(prefix) raise FormatError.new("EIP8 format message size #{size} less than plain_size #{plain_size}") if size < plain_size # continue read remain bytes packet << @io.read(size - plain_size + 2) # decrypt message [private_key.ecies_decrypt(packet[2..-1], prefix), packet] end def read_protocol_handshake msg = @frame_io.read_msg if msg.size > BASE_PROTOCOL_MAX_MSG_SIZE raise MessageOverflowError.new("message size #{msg.size} is too big") end if msg.code == Code::DISCONNECT payload = RLP.decode(msg.payload) raise UnexpectedMessageError.new("expected handshake, get disconnect, reason: #{payload}") end if msg.code != Code::HANDSHAKE raise UnexpectedMessageError.new("expected handshake, get #{msg.code}") end ProtocolHandshake.rlp_decode(msg.payload) end def set_timeout(io) timeout = HANDSHAKE_TIMEOUT if io.is_a?(BasicSocket) secs = Integer(timeout) usecs = Integer((timeout - secs) * 1_000_000) optval = [secs, usecs].pack("l_2") io.setsockopt Socket::SOL_SOCKET, Socket::SO_RCVTIMEO, optval io.setsockopt Socket::SOL_SOCKET, Socket::SO_SNDTIMEO, optval end end def seal_eip8(encoded_msg, handshake) # padding encoded message, make message distinguished from pre eip8 encoded_msg += "\x00".b * rand(100..300) prefix = encoded_prefix(encoded_msg.size + ECIES_OVERHEAD) enc = handshake.remote_key.ecies_encrypt(encoded_msg, prefix) prefix + enc end # encode 16 uint prefix def encoded_prefix(n) prefix = Utils.big_endian_encode(n) # pad to 2 bytes prefix.ljust(2, "\x00".b) end end end end end
ruby
MIT
a4ce792aa04e15d6c6e40d10474dfc73008de5ec
2026-01-04T17:51:58.192661Z
false