raterr 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: e4614602ed0eff315d079ff1c3bc3aa833b78c79
4
+ data.tar.gz: 39b4868b210bb9ab286e3cb8d7c1a150dfb0d680
5
+ SHA512:
6
+ metadata.gz: fdde30dccf0a1222370af16f6e497d847e4d91d22982c3c3cd37cc8f8457c67f947ce6671ecf6974ce1ad9a310b6ab5ad2e08d4fcd0abfee9d5a8d2dd245e950
7
+ data.tar.gz: 71119931434fc2def696903d3523c42364455d63564c2a4ef5301f64a0fd49ab327cb429b80d3643cffbaf172f5ddcaa4761216d501df7caecebbc8edd3ddb14
data/.gitignore ADDED
@@ -0,0 +1,12 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+
11
+ # rspec failure tracking
12
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.0
5
+ before_install: gem install bundler -v 1.14.3
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at wizard.oneandonly@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in raterr.gemspec
4
+ gemspec
5
+ gem 'byebug', require: false
6
+ gem 'codecov', require: false, group: :test
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Stefan Slaveykov
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,88 @@
1
+ # Raterr
2
+ [![Build Status](https://travis-ci.org/wizardone/raterr.svg?branch=master)](https://travis-ci.org/wizardone/raterr)
3
+ [![codecov](https://codecov.io/gh/wizardone/raterr/branch/master/graph/badge.svg)](https://codecov.io/gh/wizardone/raterr)
4
+
5
+ `Raterr` allows you to enforce rate limiting restrictions on visitors
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'raterr'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install raterr
22
+
23
+ ## Usage
24
+ For Ruby based application you need to tell `Raterr` what store to use.
25
+ Currently it supports a simple hash or a `ActiveSupport::Cache::MemoryStore`
26
+ It is best to load the store in an initializer of any other kind of file
27
+ that is loaded initially.
28
+ ```ruby
29
+ # Use either
30
+ Raterr::Cache.store = ActiveSupport::Cache::MemoryStore.new
31
+ # Or
32
+ Raterr::Cache.store = Hash.new
33
+ ```
34
+ To enforce rate limiting use:
35
+ ```ruby
36
+ Raterr.enforce(request, period: :minute, max: 200, code: 429)
37
+ ```
38
+ The result of `Raterr.enforce` is always a pseudo status. In case the
39
+ rate limit has not been reached you will get a pseudo `200` status + the
40
+ number of attempts. This allows you to do additional checks. If
41
+ it has been reached you will get whatever status you configured, or the
42
+ default one, which is 429 + a text message.
43
+
44
+ An example usage in a Rails application would be:
45
+ ```ruby
46
+ class MyController < Base::ApplicationController
47
+ before_action :rate_limit, only: :index
48
+
49
+ def index
50
+ # Do something cool
51
+ end
52
+
53
+ private
54
+
55
+ def rate_limit
56
+ result = Raterr.enforce(request, period: :minute, max: 10)
57
+ if result[:status] == 429
58
+ # Do whatever you want to do when the rate limit is reached
59
+ render plain: result[:text], status: result[:status] and return
60
+ else
61
+ puts "Number of attempts: #{result[:attempts]}"
62
+ end
63
+ end
64
+ end
65
+ ```
66
+ If you want to add limiting to the whole app you would put it in an
67
+ application controller and so on...
68
+
69
+ You can configure the period error code and the max attempts. The allowed periods
70
+ are: `:minute, :hour, :day`.
71
+
72
+ Currently `Raterr` checks the unique ip address of the visitor to
73
+ determine the amount of visits.
74
+ ## Development
75
+
76
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
77
+
78
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
79
+
80
+ ## Contributing
81
+
82
+ Bug reports and pull requests are welcome on GitHub at https://github.com/wizardone/raterr. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
83
+
84
+
85
+ ## License
86
+
87
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
88
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "raterr"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/lib/raterr/day.rb ADDED
@@ -0,0 +1,25 @@
1
+ module Raterr
2
+ class Day
3
+
4
+ include Mixin
5
+
6
+ HOURS_PER_DAY = 24.freeze
7
+
8
+ private
9
+
10
+ def max_per_day
11
+ options[:max]
12
+ end
13
+ alias_method :max_per_period, :max_per_day
14
+
15
+ def rate_period
16
+ start_time + 3600 * HOURS_PER_DAY
17
+ end
18
+
19
+ def try_after
20
+ "#{HOURS_PER_DAY - ((Time.now - start_time) / 3600).ceil} hours"
21
+ end
22
+ end
23
+ end
24
+
25
+
@@ -0,0 +1,24 @@
1
+ module Raterr
2
+ class Hour
3
+
4
+ include Mixin
5
+
6
+ MINUTES_PER_HOUR = 60.freeze
7
+
8
+ private
9
+
10
+ def max_per_hour
11
+ options[:max]
12
+ end
13
+ alias_method :max_per_period, :max_per_hour
14
+
15
+ def rate_period
16
+ start_time + 3600
17
+ end
18
+
19
+ def try_after
20
+ "#{MINUTES_PER_HOUR - ((Time.now - start_time) / MINUTES_PER_HOUR).ceil} minutes"
21
+ end
22
+ end
23
+ end
24
+
@@ -0,0 +1,23 @@
1
+ module Raterr
2
+ class Minute
3
+
4
+ include Mixin
5
+
6
+ SECONDS_PER_MINUTE = 60.freeze
7
+
8
+ private
9
+
10
+ def max_per_minutes
11
+ options[:max]
12
+ end
13
+ alias_method :max_per_period, :max_per_minutes
14
+
15
+ def rate_period
16
+ start_time + SECONDS_PER_MINUTE
17
+ end
18
+
19
+ def try_after
20
+ "#{SECONDS_PER_MINUTE - (Time.now - start_time).ceil} seconds"
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,65 @@
1
+ module Raterr
2
+ module Mixin
3
+
4
+ attr_reader :request, :options
5
+
6
+ def initialize(request, options)
7
+ @request = request
8
+ @options = options
9
+ end
10
+
11
+ def rate_limit_exceeded
12
+ {
13
+ status: options[:code] || Raterr::DEFAULTS[:code],
14
+ text: Raterr::DEFAULTS[:message] % { time: try_after }
15
+ }
16
+ end
17
+
18
+ def allowed?
19
+ reset_cache if Time.now > rate_period
20
+ fetch_cache[:attempts] <= max_per_period
21
+ end
22
+
23
+ def proceed
24
+ attempts = fetch_cache[:attempts] + 1
25
+ set_cache(attempts)
26
+
27
+ {
28
+ status: 200,
29
+ attempts: attempts
30
+ }
31
+ end
32
+
33
+ private
34
+
35
+ def identifier
36
+ # TODO: extend with other options from the request
37
+ request.ip.to_s
38
+ end
39
+
40
+ def fetch_cache
41
+ cache.fetch(identifier) { { attempts: 1, start_time: Time.now } }
42
+ end
43
+
44
+ def set_cache(value)
45
+ cache_attributes = {}.tap do |cache|
46
+ cache[:attempts] = value
47
+ cache[:start_time] = start_time
48
+ end
49
+ cache.is_a?(Hash) ? cache[identifier] = cache_attributes :
50
+ cache.write(identifier, cache_attributes)
51
+ end
52
+
53
+ def reset_cache
54
+ cache.delete(identifier)
55
+ end
56
+
57
+ def cache
58
+ Raterr.store
59
+ end
60
+
61
+ def start_time
62
+ fetch_cache[:start_time]
63
+ end
64
+ end
65
+ end
@@ -0,0 +1,32 @@
1
+ module Raterr
2
+ class PeriodBuilder
3
+
4
+ attr_reader :request, :period, :options
5
+
6
+ class << self
7
+ def call(request, options)
8
+ new(request, options).build
9
+ end
10
+ end
11
+
12
+ def initialize(request, options)
13
+ @period = options[:period] || DEFAULTS[:period]
14
+ @request = request
15
+ @options = options
16
+ end
17
+
18
+ def build
19
+ klass = case period
20
+ when :minute
21
+ Raterr::Minute
22
+ when :hour
23
+ Raterr::Hour
24
+ when :day
25
+ Raterr::Day
26
+ else
27
+ raise "Invalid limit period, available options are: #{Raterr::AVAILABLE_PERIODS.join(', ')}"
28
+ end
29
+ klass.new(request, options)
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,3 @@
1
+ module Raterr
2
+ VERSION = "0.1.0"
3
+ end
data/lib/raterr.rb ADDED
@@ -0,0 +1,27 @@
1
+ require 'raterr/version'
2
+ require 'raterr/period_builder'
3
+ require 'raterr/mixin'
4
+ require 'raterr/hour'
5
+ require 'raterr/day'
6
+ require 'raterr/minute'
7
+
8
+ module Raterr
9
+
10
+ AVAILABLE_PERIODS = [:minute, :hour, :day, :week, :month].freeze
11
+ DEFAULTS = {
12
+ max: 100,
13
+ code: 429,
14
+ message: "Rate limit exceeded. Try again in %{time}.",
15
+ period: :hour
16
+ }.freeze
17
+
18
+ class << self
19
+
20
+ attr_accessor :store
21
+
22
+ def enforce(request, **options)
23
+ period = PeriodBuilder.call(request, options)
24
+ period.allowed? ? period.proceed : period.rate_limit_exceeded
25
+ end
26
+ end
27
+ end
data/raterr.gemspec ADDED
@@ -0,0 +1,27 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'raterr/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "raterr"
8
+ spec.version = Raterr::VERSION
9
+ spec.authors = ["Stefan Slaveykov"]
10
+ spec.email = ["wizard.oneandonly@gmail.com"]
11
+
12
+ spec.summary = %q{Ruby rate limiter}
13
+ spec.description = %q{A gem allowing you to set rate limiting on your application}
14
+ spec.homepage = "https://github.com/wizardone/raterr"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
18
+ f.match(%r{^(test|spec|features)/})
19
+ end
20
+ spec.bindir = "exe"
21
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
22
+ spec.require_paths = ["lib"]
23
+
24
+ spec.add_development_dependency "bundler", "~> 1.14"
25
+ spec.add_development_dependency "rake", "~> 10.0"
26
+ spec.add_development_dependency "rspec", "~> 3.0"
27
+ end
metadata ADDED
@@ -0,0 +1,104 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: raterr
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Stefan Slaveykov
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-10-03 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.14'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.14'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ description: A gem allowing you to set rate limiting on your application
56
+ email:
57
+ - wizard.oneandonly@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".rspec"
64
+ - ".travis.yml"
65
+ - CODE_OF_CONDUCT.md
66
+ - Gemfile
67
+ - LICENSE.txt
68
+ - README.md
69
+ - Rakefile
70
+ - bin/console
71
+ - bin/setup
72
+ - lib/raterr.rb
73
+ - lib/raterr/day.rb
74
+ - lib/raterr/hour.rb
75
+ - lib/raterr/minute.rb
76
+ - lib/raterr/mixin.rb
77
+ - lib/raterr/period_builder.rb
78
+ - lib/raterr/version.rb
79
+ - raterr.gemspec
80
+ homepage: https://github.com/wizardone/raterr
81
+ licenses:
82
+ - MIT
83
+ metadata: {}
84
+ post_install_message:
85
+ rdoc_options: []
86
+ require_paths:
87
+ - lib
88
+ required_ruby_version: !ruby/object:Gem::Requirement
89
+ requirements:
90
+ - - ">="
91
+ - !ruby/object:Gem::Version
92
+ version: '0'
93
+ required_rubygems_version: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - ">="
96
+ - !ruby/object:Gem::Version
97
+ version: '0'
98
+ requirements: []
99
+ rubyforge_project:
100
+ rubygems_version: 2.6.13
101
+ signing_key:
102
+ specification_version: 4
103
+ summary: Ruby rate limiter
104
+ test_files: []