ip_shield 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
+ SHA256:
3
+ metadata.gz: f54832ed652f00062f3a7770bce88afb7ba793998041638dfceef3adac5a4d01
4
+ data.tar.gz: 963f19709c1b32aa93470888b80ff8985b4d254933b6f1fc799de62967b56d41
5
+ SHA512:
6
+ metadata.gz: f3c868ff2be3ef91659c031867a0e0fa5958bd7ed72420c58b4d162aade29fcc0b69c5291681dca111ab1044283f01beeead368855f2678024bef5919494663a
7
+ data.tar.gz: afa6f0e75e8f9afbbf8130caa3fa06337730f8cfe3bce68ac3b52605752862580934514110225ceffce919aa1cabf20a0defd39f19215e0289a896804f10d472
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,13 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-10-20
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at Abdullah.Janjua@dvla.gov.uk. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in ip_shield.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ group :development, :test do
11
+ gem "roda"
12
+ gem "rspec", "~> 3.0"
13
+ gem "rubocop", "~> 1.21"
14
+ end
data/README.md ADDED
@@ -0,0 +1,81 @@
1
+ <div align="center">
2
+ <img src="/docs/lego.png" height="auto" width="500" style="border-radius:30%">
3
+ </div>
4
+
5
+ ## IP Shield
6
+ ##### _A simple Roda plugin that helps you secure your Roda application by only allowing authoriased IP addresses an access to your app/page/resources_
7
+
8
+
9
+ Thank you for using `ip_shield` gem. This gem helps defending your Roda application agenst unwanted requests by only granding authorased IP addresses and access to the app, page or any resources.
10
+
11
+
12
+ | 🏁 Installation & Getting statrted |
13
+ | ----------------------------------------- |
14
+
15
+
16
+ Install the gem and add to the application's Gemfile by executing:
17
+
18
+ $ bundle add ip_shield
19
+
20
+ If bundler is not being used to manage dependencies, install the gem by executing:
21
+
22
+ $ gem install ip_shield
23
+
24
+
25
+ | 👔 Usage and examples |
26
+ | ----------------------------------------- |
27
+
28
+ Add the plugin to your Roda Application
29
+ ```ruby
30
+ plugin :ip_shield, '0.0.0.0', ['128.0.0.0', '128.0.0.5']
31
+ ```
32
+
33
+ Check if the request IP is authorised by calling `authorised_ip?` or `must_be_authorised_ip`. Please bear in mind that `authorised_ip?` will return a boolean value. `must_be_authorised_ip` in on the other hand will raise `UnauthorisedIP` error.
34
+ ```ruby
35
+ route do |r|
36
+ r.authorised_ip? ? 'IP is authorised' : 'IP is not authorised'
37
+ end
38
+ ```
39
+
40
+ ```ruby
41
+ route do |r|
42
+ begin
43
+ r.must_be_authorised_ip
44
+ 'IP is authorised'
45
+ rescue UnauthorisedIP
46
+ 'IP is not authorised'
47
+ end
48
+ end
49
+ ```
50
+
51
+ You can add an IP from the request by simply using `authorise_ip`
52
+ ```ruby
53
+ route do |r|
54
+ r.authorise_ip unless r.authorised_ip?
55
+ end
56
+ ```
57
+
58
+ Use `deauthorise_ip` to remove the de-authorise the request IP
59
+ ```ruby
60
+ route do |r|
61
+ r.deauthorise_ip if r.authorised_ip?
62
+ end
63
+ ```
64
+
65
+ Note that calling `authorised_ip?` is not a must. However checking if the IP is authorised will help in preventing you from having a duplicate IPs, or de-authorise an IP that does not exist in the authorised IP list.
66
+
67
+
68
+ | 🛠 Development |
69
+ | ----------------------------------------- |
70
+
71
+
72
+ 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.
73
+
74
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
75
+
76
+ | 📃 License |
77
+ | ----------------------------------------- |
78
+
79
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
80
+
81
+
data/Rakefile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new
11
+
12
+ task default: %i[spec rubocop]
data/docs/lego.png ADDED
Binary file
@@ -0,0 +1,119 @@
1
+ require "ipaddr"
2
+ require "singleton"
3
+
4
+ # the +IPValidator+ is a simple singleton class to validate and manage IP addresses.
5
+ # You can use this class to authorize a list of IP address.
6
+ class IPValidator
7
+ include Singleton
8
+ attr_accessor :ips
9
+
10
+ # Invalid IP boundary error
11
+ class InvalidIPsBoundary < StandardError; end
12
+
13
+ # Invalid IP address error
14
+ class InvalidIP < StandardError; end
15
+
16
+ INVALID_BOUNDARY = "IP boundary must be an array of 2 elements: high and low".freeze
17
+ IP_DOES_NOT_EXIST = "the given IP is not within the authorised list".freeze
18
+ INVALID_IP = "IP must be a valid IPv4 or IPv6".freeze
19
+
20
+ def initialize() @ips = []; end
21
+
22
+ # Ensure that all IPs are valid. an IP is invalid if its nil, not a string, or not in a IPv4 or
23
+ # IPv6 format. In case of a boundary-ip, it also must also be an array of 2
24
+ # elements (ex. [high, low]). if one or more IP in the list is invalid,
25
+ # it will raise an error. Otherwise, it will return self
26
+ #
27
+ # @example
28
+ # invalid_ip = ['0.0....']
29
+ # invalid_ip.each {|ip| IPValidator.instance.add_ip(ip)}
30
+ #
31
+ # IPValidator.instance.check_ips # will raise InvalidIP error
32
+ #
33
+ # @raise
34
+ # * InvalidIPsBoundary: if the array has an invalid number of elements.
35
+ # * InvalidIP: if the IP address is invalid
36
+ #
37
+ # @param [Array] ip_addr_list a list of all IP address
38
+ # @return [IPValidator] will return self unless one or more IP is invalid
39
+ def check_ips(ip_addr_list = @ips)
40
+ ip_addr_list.each do |ip_addr|
41
+ if ip_addr.is_a?(Array)
42
+ ip_addr
43
+ .tap { |ip| raise InvalidIPsBoundary, INVALID_BOUNDARY unless ip.count.eql?(2) }
44
+ .each { |ip| raise InvalidIP, INVALID_IP unless is_ip?(ip) }
45
+ else
46
+ raise InvalidIP, INVALID_IP unless is_ip?(ip_addr)
47
+ end
48
+ end
49
+
50
+ return_self
51
+ end
52
+
53
+ # Checks if the IP is authorized. The IP is authorized if any of the following true:
54
+ # 1. the IP matches on of the IPs in the list +@ips+
55
+ # 2. the IP is within any IP boundaries in +@ips+
56
+ # this function will return true if any 1 or 2 is true. Otherwise, it will return false.
57
+ #
58
+ # @example
59
+ # IPValidator
60
+ # .instance
61
+ # .is_authorize_ip?('0.0.0.0')
62
+ #
63
+ # @param [String] ip_addr the IP address
64
+ # @return [TrueClass, FalseClass] true if the IP is authorized. Otherwise return false
65
+ def is_authorize_ip?(ip_addr)
66
+ ip_range, ip_list = @ips.partition{|all_ips| all_ips.is_a? Array}
67
+
68
+ ip_list.filter!{|ip| IPAddr.new(ip).to_i === IPAddr.new(ip_addr).to_i}
69
+ ip_list.empty? && ip_range.filter! do |range|
70
+ low = IPAddr.new(range.first)
71
+ high = IPAddr.new(range.last)
72
+ current = IPAddr.new(ip_addr)
73
+
74
+ (low..high) === current
75
+ end
76
+
77
+ (ip_list.count + ip_range.count).positive?
78
+ end
79
+
80
+ # Use this function to add new IPs to the authorized IP list.
81
+ #
82
+ # @note
83
+ # This function will check if the IP is valid before adding the IP to the
84
+ # authorized IP list.
85
+ #
86
+ # @example
87
+ # IPValidator.instance.add_ip('0.0.0.0')
88
+ #
89
+ # @param [String] ip_addr the IP address to be added
90
+ # @return [IPValidator] self
91
+ def add_ip(ip_addr)
92
+ check_ips([ip_addr]) && @ips.push(ip_addr)
93
+ return_self
94
+ end
95
+
96
+ # Use this function to remove the IP from the authorized IP list. The given IP
97
+ # must exist in the IP list
98
+ #
99
+ # @raise
100
+ # InvalidIP: If the IP does not exist in the authorized IP list
101
+ #
102
+ # @param [String] ip_addr the IP address to be removed
103
+ # @return [IPValidator] self
104
+ def remove_ip(ip_addr)
105
+ raise InvalidIP, IP_DOES_NOT_EXIST if @ips.delete(ip_addr).nil?
106
+ return_self
107
+ end
108
+
109
+ private
110
+
111
+ def is_ip?(ip_addr = @ips)
112
+ return false if ip_addr.nil?
113
+ return false unless ip_addr.is_a? String
114
+
115
+ true if IPAddr.new(ip_addr) rescue false
116
+ end
117
+
118
+ def return_self() self; end
119
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module IpShield
4
+ VERSION = "0.1.0"
5
+ end
data/lib/ip_shield.rb ADDED
@@ -0,0 +1,125 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "ip_shield/version"
4
+ require_relative "ip_shield/ip_validator"
5
+ require "ipaddr"
6
+ require 'roda'
7
+ class Roda
8
+ module RodaPlugins
9
+ module IpShield
10
+
11
+ # Unauthorised IP error
12
+ class UnauthorisedIP < RodaError; end
13
+
14
+ # invalid IP error
15
+ class InvalidIP < RodaError; end
16
+
17
+ # Auto configure +ip_shield+ plugin. Set IPs when the plugin is loaded. The provided
18
+ # IP will be authorize automatically as long as they as are valid IPv4 or IPv6. There are
19
+ # two ways to set IP.
20
+ # 1. As a string. Ex; '0.0.0.0'
21
+ # 2. As an array of low and high boundaries. Ex; ['0.0.0.0', '0.0.0.7']
22
+ #
23
+ # @note
24
+ # boundaries should be an array with two string elements - IP. The first element must
25
+ # be low IP and the second should be high.
26
+ #
27
+ # @example
28
+ # plugin :ip_shield, '0.0.0.0', ['128.0.0.0', '128.0.0.5']
29
+ #
30
+ # @param [Object] app App
31
+ # @param [Array] ip_addrs list of aip addresses
32
+ def self.configure(app, *ip_addrs)
33
+ ip_addrs = app.opts[:ip_shield] || ip_addrs
34
+ ip_addrs.each { |ip_addr| IPValidator.instance.add_ip(ip_addr) } unless ip_addrs.nil? || ip_addrs.empty?
35
+ end
36
+
37
+ module RequestMethods
38
+
39
+ # A simple but fun way to check if the request IP is authorised. Only added IPs are
40
+ # authorised. If the IP is not added, then it will be considered as deauthorise ip and
41
+ # therefore this function will return false.
42
+ #
43
+ # @example
44
+ # r.authorised_ip? ? 'IP is authorised' : 'IP is not authorised'
45
+ #
46
+ # @return [TrueClass, FalseClass] true only if the request IP is authorised & false if not
47
+ def authorised_ip?
48
+ req_ip_addr = ip_addr(self)
49
+
50
+ IPValidator
51
+ .instance
52
+ .is_authorize_ip?(req_ip_addr)
53
+ end
54
+
55
+ # This function will raise +UnauthorisedIP+ error if the request IP is not authorised.
56
+ # Use this function if you would like to hard-stop the program execution but be
57
+ # sure to handle the error.
58
+ #
59
+ # @example
60
+ # begin
61
+ # r.must_be_authorised_ip
62
+ # 'IP is authorised'
63
+ # rescue UnauthorisedIP
64
+ # 'IP is not authorised'
65
+ # end
66
+ #
67
+ # @raise
68
+ # UnauthorisedIP: The request IP is not authorised'
69
+ #
70
+ # @return [TrueClass, FalseClass] true if IP is authorised or raise UnauthorisedIP when isn't
71
+ def must_be_authorised_ip
72
+ req_ip_addr = ip_addr(self)
73
+
74
+ IPValidator
75
+ .instance
76
+ .is_authorize_ip?(req_ip_addr)
77
+ .tap { |auth| raise UnauthorisedIP, 'The request IP is not authorised' unless auth }
78
+ end
79
+
80
+ # Remove an IP from the authorised list. The IP must be valid and exist in the
81
+ # authorised IP list. Its recommended to check if the IP exist before deauthorise it.
82
+ #
83
+ # @example
84
+ # r.deauthorise_ip if r.authorised_ip?
85
+ #
86
+ # @raise
87
+ # IP_DOES_NOT_EXIST: the given IP is not within the authorised list
88
+ def deauthorise_ip
89
+ IPValidator
90
+ .instance
91
+ .remove_ip(ip_addr(self))
92
+ end
93
+
94
+ # Add an IP ti the authorised list. You can only add any of the following:
95
+ # 1. IP as a string. Ex; '0.0.0.0'
96
+ # 2. An array of low and high boundaries. Ex; ['0.0.0.0', '0.0.0.7']
97
+ #
98
+ # @note
99
+ # The IP validity will get checked automatically before it gets added to the
100
+ # authorise IP list. However, there are no checks for duplicate IPs. Its
101
+ # recommended to check if the IP exist before authorise it.
102
+ #
103
+ # @example
104
+ # r.authorise_ip unless r.authorised_ip?
105
+ #
106
+ # @return [String|Array] an IP as a string or an IP boundary
107
+ def authorise_ip
108
+ IPValidator
109
+ .instance
110
+ .add_ip(ip_addr(self))
111
+ end
112
+
113
+ private
114
+
115
+ def ip_addr(request)
116
+ request&.ip.nil? ? (raise InvalidIP, 'No IP is not found') : request.ip
117
+ end
118
+
119
+ end
120
+ end
121
+
122
+ register_plugin(:ip_shield, IpShield)
123
+ end
124
+ end
125
+
data/sig/ip_shield.rbs ADDED
@@ -0,0 +1,4 @@
1
+ module IpShield
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,57 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: ip_shield
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Abdullah Janjua
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-11-24 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: 'do it: Write a longer description or delete this line.'
14
+ email:
15
+ - AbdullahJanjuauk@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".rspec"
21
+ - ".rubocop.yml"
22
+ - CHANGELOG.md
23
+ - CODE_OF_CONDUCT.md
24
+ - Gemfile
25
+ - README.md
26
+ - Rakefile
27
+ - docs/lego.png
28
+ - lib/ip_shield.rb
29
+ - lib/ip_shield/ip_validator.rb
30
+ - lib/ip_shield/version.rb
31
+ - sig/ip_shield.rbs
32
+ homepage: https://github.com/DevAbdullahUk/roda-IPShield
33
+ licenses:
34
+ - MIT
35
+ metadata:
36
+ homepage_uri: https://github.com/DevAbdullahUk/roda-IPShield
37
+ source_code_uri: https://github.com/DevAbdullahUk/roda-IPShield
38
+ post_install_message:
39
+ rdoc_options: []
40
+ require_paths:
41
+ - lib
42
+ required_ruby_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: 2.6.0
47
+ required_rubygems_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '0'
52
+ requirements: []
53
+ rubygems_version: 3.3.7
54
+ signing_key:
55
+ specification_version: 4
56
+ summary: 'do it: Write a short summary, because RubyGems requires one.'
57
+ test_files: []