ruby-common 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 83aecf7e9b5979539d523fa823e5d934887ca1151e8a3c5d2e43a7d7c920c7f6
4
+ data.tar.gz: 6305c58936a279511f7693c38b026362f9b319667cc1d39365ab7c70f5db98ca
5
+ SHA512:
6
+ metadata.gz: b408ffc285089ec0c4ee95c23c54cac048b044d3fcdc4b348071001962d8076b60c5872ac41bd01ea23b1db81052a507bd3cededb69ece1f73ea75979a69767b
7
+ data.tar.gz: 85d274de5356d315745775489926aad0fcc568223e41f02545d7fc803349d92e6920dea3a3a5eb8ee151144762d57dfbdf161e8846c6215df07d813adad4c109
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2024-08-13
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 adrian.parzych@iterative.pl. 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,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+ ruby '3.0.2'
5
+
6
+ # Specify your gem's dependencies in ruby-common.gemspec
7
+ gemspec
8
+
9
+ gem "rake", "~> 13.0"
10
+ gem 'rspec'
11
+ gem 'rbnacl', "~> 7.1.2"
12
+ gem "msgpack", "~> 1.7.3"
13
+
14
+ group :development, :test do
15
+ gem 'rspec'
16
+ end
data/Gemfile.lock ADDED
@@ -0,0 +1,34 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ ruby-common (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ diff-lcs (1.5.1)
10
+ rake (13.2.1)
11
+ rspec (3.13.0)
12
+ rspec-core (~> 3.13.0)
13
+ rspec-expectations (~> 3.13.0)
14
+ rspec-mocks (~> 3.13.0)
15
+ rspec-core (3.13.0)
16
+ rspec-support (~> 3.13.0)
17
+ rspec-expectations (3.13.1)
18
+ diff-lcs (>= 1.2.0, < 2.0)
19
+ rspec-support (~> 3.13.0)
20
+ rspec-mocks (3.13.1)
21
+ diff-lcs (>= 1.2.0, < 2.0)
22
+ rspec-support (~> 3.13.0)
23
+ rspec-support (3.13.1)
24
+
25
+ PLATFORMS
26
+ x86_64-linux
27
+
28
+ DEPENDENCIES
29
+ rake (~> 13.0)
30
+ rspec
31
+ ruby-common!
32
+
33
+ BUNDLED WITH
34
+ 2.3.5
data/LICENSE.md ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 AdScore Technologies DMCC [AE]
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,174 @@
1
+ # Ruby::Common
2
+
3
+ [![Software License](https://img.shields.io/badge/license-MIT-brightgreen.svg?style=flat-square)](LICENSE.md)
4
+
5
+ This library provides various utilities for parsing [Adscore](https://adscore.com) signatures v4 and v5,
6
+ and virtually anything that might be useful for customers doing server-side
7
+ integration with the service.
8
+
9
+ ## Compatibility
10
+
11
+ ### Supported Signature v5 algorithms
12
+ 1. `v5_0200H - OpenSSL CBC, HTTP query`
13
+ 2. `v5_0200S - OpenSSL CBC, PHP serialize`
14
+ 3. `v5_0201H - OpenSSL GCM, HTTP query`
15
+ 4. `v5_0201S - OpenSSL GCM, PHP serialize`
16
+ 5. `v5_0101H - sodium secretbox, HTTP query`
17
+ 6. `v5_0101S - sodium secretbox, PHP serialize`
18
+ 7. `v5_0200J - OpenSSL CBC, JSON`
19
+ 8. `v5_0201J - OpenSSL GCM, JSON`
20
+ 9. `v5_0101J - sodium secretbox, JSON`
21
+ 10. `v5_0101M - sodium secretbox, msgpack`
22
+ 11. `v5_0200M - OpenSSL CBC, msgpack`
23
+ 12. `v5_0201M - OpenSSL GCM, msgpack`
24
+
25
+ ### Not supported Signature v5 algorithms
26
+
27
+ 1. `v5_0101I - sodium secretbox, igbinary`
28
+ 2. `v5_0200I - OpenSSL CBC, igbinary`
29
+ 3. `v5_0201I - OpenSSL GCM, igbinary`
30
+
31
+ ## Installation
32
+
33
+ You have few options:
34
+
35
+ ### Sharing source code
36
+
37
+ Add this line to your application's Gemfile:
38
+ ```ruby
39
+ gem "ruby-common", :git => "https://github.com/Adscore/ruby-common"
40
+ ```
41
+
42
+ And then execute:
43
+
44
+ $ bundle install
45
+
46
+ Or install it yourself as:
47
+
48
+ $ gem install ruby-common
49
+
50
+ ## Usage
51
+
52
+ ### V4 signature decryption
53
+
54
+ When zone's "Response signature algorithm" is set to "Hashing" or "Signing", it means that V4 signatures are in use. They provide basic means to check incoming traffic for being organic and valuable, but do not carry any additional information.
55
+
56
+ Following are few quick examples of how to use verifier, first import the entry point for library:
57
+
58
+
59
+
60
+ ```ruby
61
+ require 'ruby-common'
62
+
63
+ begin
64
+ # Verify with base64 encoded key. No expiry parameter, the default expiry time for requestTime and signatureTime is 60s
65
+ result = Signature4Verifier.verify(
66
+ <signature>,
67
+ <user_agent>,
68
+ <key>,
69
+ [<ip_address>]
70
+ )
71
+ rescue VersionError
72
+ # It means that the signature is not the V5 one, check your zone settings and ensure the signatures
73
+ # are coming from the chosen zone.
74
+ rescue ParseError
75
+ # It means that the signature metadata is malformed and cannot be parsed, or contains invalid data,
76
+ # check for corruption underway.
77
+ rescue VerifyError
78
+ # Signature could not be verified - usually this is a matter of IP / user agent mismatch (or spoofing).
79
+ # They must be bit-exact, so even excessive whitespace or casing change can trigger the problem.
80
+ end
81
+
82
+
83
+ [..]
84
+ require 'ruby-common'
85
+
86
+ begin
87
+ # Verify with checking if expired and non base64 encoded key
88
+ #
89
+ # IF signatureTime + expiry > CurrentDateInSeconds
90
+ # THEN result.getExpired() = true
91
+ result = Signature4Verifier.verify(
92
+ <signature>,
93
+ <user_agent>,
94
+ <key_none_encoded>,
95
+ [<ip_address>],
96
+ expiry: 120, #signature cant be older than 2 min
97
+ is_key_base64_encoded: False # notify that we use non encoded key
98
+ );
99
+ [..]
100
+
101
+
102
+ [..]
103
+ require 'ruby-common'
104
+
105
+ begin
106
+ # Verify against number of ip4 and ip6 addresses
107
+ # (No expiry parameter, the default expiry time for requestTime and signatureTime is 120s)
108
+ result = Signature4Verifier.verify(
109
+ <signature>,
110
+ <user_agent>,
111
+ <key_none_encoded>,
112
+ #Multiple ip addresses either from httpXForwardForIpAddresses and remoteIpAddresses header
113
+ ["73.109.57.137", "73.109.57.138", "73.109.57.139", "73.109.57.140", "0:0:0:0:0:ffff:4d73:55d3", "0:0:0:0:0:fffff:4d73:55d4", "0:0:0:0:0:fffff:4d73:55d5", "0:0:0:0:0:fffff:4d73:55d6"],
114
+ expiry: 120, #signature cant be older than 2 min
115
+ is_key_base64_encoded: False # notify that we use non encoded key
116
+ );
117
+ [..]
118
+
119
+ ```
120
+ The `result` is an instance of the [Signature4VerificationResult](lib/ruby-common/v4/Signature4VerificationResult.rb) class.
121
+
122
+
123
+
124
+ ### V5 signature decryption
125
+
126
+ V5 is in fact an encrypted payload containing various metadata about the traffic. Its decryption does not rely on IP address
127
+ nor User Agent string, so it is immune for environment changes usually preventing V4 to be even decoded. Judge result is also
128
+ included in the payload, but client doing the integration can make its own decision basing on the metadata accompanying.
129
+
130
+ Zone has to be set explicitly to V5 signature, if you don't see the option, please contact support as we are rolling this
131
+ mode on customer's demand. The format supports a wide variety of encryption and serialization methods, some of them are included
132
+ in this repository, but it can be extended to fulfill specific needs.
133
+
134
+ It can be integrated in V4-compatible mode, not making use of any V5 features (see V4 verification):
135
+
136
+
137
+
138
+
139
+ ```ruby
140
+ require 'ruby-common'
141
+
142
+ begin
143
+
144
+ # Three things are necessary to verify the signature - at least one IP address in array, User Agent string
145
+ # and the signature itself. Result is represented by Signature5VerificationResult class.
146
+ result = Signature4Verifier.verify(
147
+ <signature>,
148
+ <user_agent>,
149
+ <key>,
150
+ [<ip_address>]
151
+ )
152
+ rescue VersionError
153
+ # It means that the signature is not the V5 one, check your zone settings and ensure the signatures
154
+ # are coming from the chosen zone.
155
+ rescue ParseError
156
+ # It means that the signature metadata is malformed and cannot be parsed, or contains invalid data,
157
+ # check for corruption underway.
158
+ rescue VerifyError
159
+ # Signature could not be verified - usually this is a matter of IP / user agent mismatch (or spoofing).
160
+ # They must be bit-exact, so even excessive whitespace or casing change can trigger the problem.
161
+ end
162
+ ```
163
+ The `result` is an instance of the [Signature5VerificationResult](lib/ruby-common/v5/Signature5VerificationResult.rb) class.
164
+
165
+ The result field score only after a successful verify() call. This is expected behavior, to preserve compliance with V4 behavior - the result is only valid when it's proven belonging to a visitor, in other case will be thrown exception. For custom integrations not relying on built-in verification routines (usually more tolerant), the result is present also in result field, but it's then the integrator's reponsibility to ensure whether it's trusted or not. When desired validation is more strict than the built-in one, the verify() can be called first, and after that any additional verification may take place.
166
+
167
+ Note: V4 signature parser also holds the payload, but it does not contain any useful informations, only timestamps and signed strings; especially - it does not contain any Judge result value, it is derived from the signature via several hashing/verification approaches.
168
+
169
+
170
+ ## Integration
171
+
172
+ Any questions you have with custom integration, please contact our support@adscore.com. Please remember that we do
173
+ require adequate technical knowledge in order to be able to help with the integration; there are other integration
174
+ methods which do not require any, or require very little programming.
data/Rakefile ADDED
@@ -0,0 +1,4 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ task default: %i[]
@@ -0,0 +1,29 @@
1
+ require_relative './v4/Signature4VerifierService.rb'
2
+
3
+ # Entry point of AdScore signature v4 verification library. It expose verify method allowing to verify
4
+ # AdScore signature against given set of ipAddress(es) for given zone.
5
+
6
+ class Signature4Verifier
7
+ DEFAULT_EXPIRY_TIME_SEC = 60
8
+
9
+ # Default request and signature expiration is set to 60s
10
+ #
11
+ # @param signature [String] which we want to verify
12
+ # @param user_agent [String] with full description of user agent like 'Mozilla/5.0 (Linux; Android 9; SM-J530F)...'
13
+ # @param key [String] containing related zone key
14
+ # @param ip_addresses [Array<String>] containing ip4 or ip6 addresses against which we check
15
+ # signature. Usually, is fulfilled from httpXForwardForIpAddresses or/and remoteIpAddresses
16
+ # header. All possible ip addresses may be provided at once, in case of correct result,
17
+ # verifier returns list of chosen ip addresses that matched with the signature.
18
+ # @param expiry [Number] which is time in seconds. IF signatureTime + expiry > CurrentDateInSeconds THEN result is expired
19
+ # @param is_key_base64_encoded [Boolean] defining if passed key is base64 encoded or not. Default is set to false.
20
+ # @return [Signature4VerificationResult] verification results
21
+ # @raise [VersionError] if there is an error related to version parsing or compatibility.
22
+ # @raise [ParseError] if there is an error parsing the signature or during decryption process
23
+ # @raise [VerifyError] if there is an error during verify decrypted Signature
24
+ # @return Signature4VerificationResult
25
+ def self.verify(signature, user_agent, key, ip_addresses, expiry: DEFAULT_EXPIRY_TIME_SEC, is_key_base64_encoded: false)
26
+ Signature4VerifierService.verifySignature(signature, user_agent, key, ip_addresses, expiry, is_key_base64_encoded)
27
+ end
28
+ end
29
+
@@ -0,0 +1,31 @@
1
+ require_relative './v5/Signature5VerifierService.rb'
2
+
3
+ # Entry point of AdScore signature v5 verification library. It expose verify method allowing to verify
4
+ # AdScore signature against given set of ipAddress(es) for given zone.
5
+ #
6
+ # V5 is in fact an encrypted payload containing various metadata about the traffic.
7
+ # Its decryption does not rely on IP address nor User Agent string,
8
+ # so it is immune for environment changes usually preventing V4 to be even decoded.
9
+ # result is also included in the payload, but client doing the integration can make its own decision basing on the metadata accompanying.
10
+
11
+ class Signature5Verifier
12
+
13
+ # Verifies the signature against the provided user agent, key, and IP addresses.
14
+ #
15
+ # @param signature The string which we want to verify.
16
+ # @param user_agent String with full description of user agent like 'Mozilla/5.0 (Linux; Android 9; SM-J530F)...'.
17
+ # @param key "Zone Response Key" which you might find in "Zone Encryption" page.
18
+ # @param ip_addresses List of strings containing IPv4 or IPv6 addresses against which we check signature.
19
+ # Usually fulfilled from httpXForwardForIpAddresses or/and remoteIpAddresses header.
20
+ # All possible IP addresses may be provided at once; the verifier returns a list of chosen
21
+ # IP addresses that matched with the signature.
22
+ # @return Signature5VerificationResult object representing the result of the signature verification.
23
+ # @raise VersionError If there is an error related to version parsing or compatibility.
24
+ # @raise ParseError If there is an error parsing the signature or during decryption process
25
+ # @raise VerifyError If there is an error during verify decrypted Signature
26
+ # @return Signature5VerificationResult
27
+
28
+ def self.verify(signature, user_agent, key, ip_addresses)
29
+ Signature5VerifierService.verifySignature(signature, user_agent, key, ip_addresses)
30
+ end
31
+ end
@@ -0,0 +1,7 @@
1
+ # Custom exception classes
2
+ class VerifyError < StandardError; end
3
+ class VersionError < StandardError; end
4
+ class ParseError < StandardError; end
5
+ class SignatureParseError < ParseError; end
6
+ class StructParseError < ParseError; end
7
+ class DecryptError < ParseError; end
@@ -0,0 +1,27 @@
1
+ require 'ipaddr'
2
+
3
+ module IpV6Utils
4
+
5
+ def self.validate(ip_address)
6
+ begin
7
+ ip = IPAddr.new(ip_address)
8
+ return ip.ipv6?
9
+ rescue IPAddr::InvalidAddressError
10
+ return false
11
+ end
12
+ end
13
+
14
+ def self.abbreviate(ip_address)
15
+ begin
16
+ ip = IPAddr.new(ip_address)
17
+
18
+ unless ip.ipv6?
19
+ raise ArgumentError, "Invalid address: #{ip_address}"
20
+ end
21
+
22
+ return ip.to_s
23
+ rescue IPAddr::InvalidAddressError
24
+ raise ArgumentError, "Invalid address: #{ip_address}"
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,96 @@
1
+ require 'stringio'
2
+
3
+ module PhpUnpack
4
+ NAME = "name"
5
+ CODE = "code"
6
+
7
+ def self.unpack(format, input, byte_slice = true)
8
+ instructions = format.split('/')
9
+ offset = 0
10
+ result = {}
11
+
12
+ instructions.each do |instruction|
13
+ code_and_name = get_code_and_name(instruction)
14
+ code = code_and_name[CODE]
15
+ name = code_and_name[NAME]
16
+
17
+ decoded_data, bytes_offset = decode(input, code)
18
+ result[name] = decoded_data
19
+ offset = offset + bytes_offset
20
+
21
+ if byte_slice
22
+ input.slice!(0, bytes_offset)
23
+ end
24
+ end
25
+ result
26
+ end
27
+
28
+ def self.decode(input, code)
29
+ case code
30
+ when 'c'
31
+ decoded_data = input.unpack('c')
32
+ bytes_offset = 1
33
+ when 'C'
34
+ decoded_data = input.unpack('C')
35
+ bytes_offset = 1
36
+ when 'n'
37
+ decoded_data = input.unpack('n')
38
+ bytes_offset = 2
39
+ when 'N'
40
+ decoded_data = input.unpack('N')
41
+ bytes_offset = 4
42
+ when 'J'
43
+ decoded_data = input.unpack1('Q>')
44
+ bytes_offset = 8
45
+ when 'v'
46
+ decoded_data = input.unpack('v')
47
+ bytes_offset = 2
48
+ else
49
+ raise ArgumentError, "Unrecognized instruction: #{code}"
50
+ end
51
+
52
+ [decoded_data, bytes_offset]
53
+ end
54
+
55
+ def self.pack(format, *inputs)
56
+ instructions = format.split('')
57
+ raise ArgumentError, "Invalid format length, expected #{inputs.length} number of codes" unless instructions.length == inputs.length
58
+
59
+ buffer = StringIO.new
60
+ instructions.each_with_index do |code, i|
61
+ encoded_data = encode(inputs[i], code)
62
+ buffer.write(encoded_data)
63
+ end
64
+
65
+ buffer.string
66
+ end
67
+
68
+ def self.encode(input, code)
69
+ case code
70
+ when 'c'
71
+ [input.to_i].pack('c')
72
+ when 'C'
73
+ [input.to_i].pack('C')
74
+ when 'n'
75
+ [input.to_i].pack('n')
76
+ when 'N'
77
+ [input.to_i].pack('N')
78
+ when 'J'
79
+ [input.to_i].pack('J')
80
+ when 'v'
81
+ [input.to_i].pack('v')
82
+ else
83
+ raise ArgumentError, "Unrecognized instruction: #{code}"
84
+ end
85
+ end
86
+
87
+ private
88
+
89
+ def self.get_code_and_name(instruction)
90
+ raise ArgumentError, "Empty instruction" if instruction.nil? || instruction.empty?
91
+
92
+ code = instruction[0]
93
+ name = instruction[1..-1]
94
+ { CODE => code, NAME => name }
95
+ end
96
+ end
@@ -0,0 +1,22 @@
1
+ # Utility class for signature verification
2
+ class SignatureVerifierUtils
3
+ def self.character_to_int(value)
4
+ value.to_i
5
+ end
6
+
7
+ def self.base64_decode(key)
8
+ if key.include? "-" or key.include? "_" then
9
+ return Base64.urlsafe_decode64(key)
10
+ end
11
+ return Base64.decode64(key)
12
+ end
13
+
14
+ def self.encode(key, data)
15
+ begin
16
+ hmac = OpenSSL::HMAC.new(key, 'sha256')
17
+ return hmac.update(data).digest
18
+ rescue StandardError => e
19
+ raise SignatureParseError, "Error encode data"
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,9 @@
1
+ class VerifierConstants
2
+ RESULTS = {
3
+ 0 => "ok",
4
+ 3 => "junk",
5
+ 6 => "proxy",
6
+ 9 => "bot"
7
+ }.freeze
8
+
9
+ end
@@ -0,0 +1,11 @@
1
+ require 'openssl'
2
+ require 'base64'
3
+
4
+ module AsymmetricOpenSSL
5
+
6
+ def self.verify_data(data, token, public_key_pem)
7
+ pub_key = OpenSSL::PKey::EC.new(public_key_pem)
8
+ digest = OpenSSL::Digest.new('sha256')
9
+ pub_key.verify(digest,token, data)
10
+ end
11
+ end
@@ -0,0 +1,40 @@
1
+ class Signature4VerificationResult
2
+ attr_accessor :score, :verdict, :ip_address, :request_time,
3
+ :signature_time, :expired
4
+
5
+ def initialize(score:, verdict:, ip_address:, request_time:,
6
+ signature_time:, expired: false)
7
+ @score = score
8
+ @verdict = verdict
9
+ @ip_address = ip_address
10
+ @request_time = request_time
11
+ @signature_time = signature_time
12
+ @expired = expired
13
+ end
14
+
15
+ def self.is_expired()
16
+ new(
17
+ score: nil,
18
+ verdict: nil,
19
+ ip_address: nil,
20
+ request_time: nil,
21
+ signature_time: nil,
22
+ expired: true
23
+ )
24
+ end
25
+
26
+ def to_h
27
+ {
28
+ score: @score,
29
+ verdict: @verdict,
30
+ ip_address: @ip_address,
31
+ request_time: @request_time,
32
+ signature_time: @signature_time,
33
+ expired: @expired
34
+ }
35
+ end
36
+
37
+ def to_s
38
+ "ValidationResult(score: #{@score}, verdict: #{@verdict}, ip_address: #{@ip_address}, request_time: #{@request_time}, signature_time: #{@signature_time}, expired: #{@expired})"
39
+ end
40
+ end