has_more_secure_token 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: 54e34de9390dbf1565102871c5e30612cbd57203415b267a52dff7cc3facb56f
4
+ data.tar.gz: 6164572a64e581f39dffa0109019afcc6c5c0e31d98c661431b588750550b38c
5
+ SHA512:
6
+ metadata.gz: 8b0c9801b204fa69d5251e9804b69349ff3bcc10596851567d6ed5881a41f899f76a4f3be2e3c282cf1a540f75ccd3350e606fdd2f002520da7f78c268b34036
7
+ data.tar.gz: acc4980052214b93b6f19de44050efdfd89527a00353a9019737c9ffa66c29d67af805dd7e4dbc0beae11881194d1bdc0f2922afe6bfa7f0e85c3d1030af653f
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,32 @@
1
+ require:
2
+ - rubocop-performance
3
+ - rubocop-rspec
4
+
5
+ AllCops:
6
+ NewCops: enable
7
+ SuggestExtensions: false
8
+ TargetRubyVersion: 2.7
9
+ Exclude:
10
+ - 'spec/dummy/db/schema.rb'
11
+ - 'vendor/**/*'
12
+
13
+ Gemspec/DevelopmentDependencies:
14
+ EnforcedStyle: gemspec
15
+
16
+ Style/StringLiterals:
17
+ Enabled: true
18
+
19
+ Style/StringLiteralsInInterpolation:
20
+ Enabled: true
21
+
22
+ Layout/AccessModifierIndentation:
23
+ EnforcedStyle: outdent
24
+
25
+ Layout/LineLength:
26
+ Max: 120
27
+
28
+ Naming/RescuedExceptionsVariableName:
29
+ PreferredName: error
30
+
31
+ Style/Documentation:
32
+ Enabled: false
@@ -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 7896757+mintyfresh@users.noreply.github.com. 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/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2023 Minty Fresh
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
+ # HasMoreSecureToken
2
+
3
+ TODO: Delete this and the text below, and describe your gem
4
+
5
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/has_more_secure_token`. To experiment with that code, run `bin/console` for an interactive prompt.
6
+
7
+ ## Installation
8
+
9
+ TODO: Replace `has_more_secure_token` with your gem name right after releasing it to RubyGems.org. Please do not do it earlier due to security reasons. Alternatively, replace this section with instructions to install your gem from git if you don't plan to release to RubyGems.org.
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ $ bundle add has_more_secure_token
14
+
15
+ If bundler is not being used to manage dependencies, install the gem by executing:
16
+
17
+ $ gem install has_more_secure_token
18
+
19
+ Finally, add this to your `app/models/application_record.rb`:
20
+
21
+ ```ruby
22
+ class ApplicationRecord < ActiveRecord::Base
23
+ include HasMoreSecureToken
24
+
25
+ # ...
26
+ end
27
+ ```
28
+
29
+ Note: HasMoreSecureToken was developed and tested only with PostgreSQL (major versions 12, 14, and 15).
30
+
31
+ ## Usage
32
+
33
+ To use time-safe lookups with `has_secure_token`, we specify a `find_by_digest` with the digest algorithm we wish to use:
34
+ ```ruby
35
+ class User < ApplicationRecord
36
+ has_secure_token :password_reset_token, find_by_digest: 'sha256'
37
+ end
38
+ ```
39
+ Doing so will override the `find_by_{token-name}` and `find_by_{token-name}!` methods (`find_by_password_reset_token` and `find_by_password_reset_token!` in the example above) that perform secure finds.
40
+
41
+ For example, if we now need to locate a User record by a token, we use:
42
+ ```ruby
43
+ # Read a token from somewhere...
44
+ token = params[:password_reset_token]
45
+
46
+ User.find_by_password_reset_token(token) # => #<User:0x0000...>
47
+ ```
48
+ And this will produce the following database query:
49
+ ```ruby
50
+ User Load (1.9ms) SELECT "users".* FROM "users" WHERE digest("users"."password_reset_token", 'SHA256') = $1 LIMIT $2 [["password_reset_token", "<32 bytes of binary data>"], ["LIMIT", 1]]
51
+ ```
52
+
53
+ As a nice side-effect, since a binary representation of the digest is used, Rails omits the exact values from our logs (regardless of whether our log filters are configured to match the name of the attribute).
54
+
55
+ ### Improving Performance with Indices
56
+
57
+ HasMoreSecureToken uses binary hashes directly rather than a hex representation, so we can define an index to speed up lookups for the above example as follows:
58
+ ```ruby
59
+ enable_extension 'pgcrypto' # required for `digest(...)` if not already enabled
60
+
61
+ create_table :users do |t|
62
+ # We include a unique index to ensure no duplicate tokens are generated
63
+ t.binary :password_reset_token, null: false, index: { unique: true }
64
+
65
+ t.index "digest(password_reset_token, 'SHA256')",
66
+ name: 'index_users_on_password_reset_token_digest',
67
+ using: :hash # recommended for PG12 and newer
68
+ end
69
+ ```
70
+ Since we are only concerned with the equality (`=`) operator, using a HASH index will provide fast lookups without revealing timing information in the same way a BTREE index might.
71
+
72
+ ## Development
73
+
74
+ 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.
75
+
76
+ 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).
77
+
78
+ ## Contributing
79
+
80
+ Bug reports and pull requests are welcome on GitHub at https://github.com/mintyfresh/has_more_secure_token. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/mintyfresh/has_more_secure_token/blob/main/CODE_OF_CONDUCT.md).
81
+
82
+ ## License
83
+
84
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
85
+
86
+ ## Code of Conduct
87
+
88
+ Everyone interacting in the HasMoreSecureToken project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/mintyfresh/has_more_secure_token/blob/main/CODE_OF_CONDUCT.md).
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]
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module HasMoreSecureToken
4
+ VERSION = '0.1.0'
5
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'has_more_secure_token/version'
4
+
5
+ require 'active_record'
6
+
7
+ module HasMoreSecureToken
8
+ MINIMUM_TOKEN_LENGTH = ActiveRecord::SecureToken::MINIMUM_TOKEN_LENGTH
9
+
10
+ module ClassMethods
11
+ # @param attribute [Symbol]
12
+ # @param length [Integer]
13
+ # @param find_by_digest [String, nil]
14
+ # @return [void]
15
+ def has_secure_token(attribute = :token, length: MINIMUM_TOKEN_LENGTH, find_by_digest: nil) # rubocop:disable Naming/PredicateName
16
+ finds_secure_token_by_digest(attribute, length: length, digest: find_by_digest) if find_by_digest
17
+
18
+ super(attribute, length: length)
19
+ end
20
+
21
+ # @param attribute [Symbol]
22
+ # @param length [Integer]
23
+ # @param digest [String]
24
+ # @return [void]
25
+ def finds_secure_token_by_digest(attribute, length: MINIMUM_TOKEN_LENGTH, digest: 'sha256')
26
+ # The digest must be a valid algorithm.
27
+ openssl_digest = OpenSSL::Digest.new(digest)
28
+
29
+ # An arel node that matches the format of the digest in the index.
30
+ token_arel = arel_token_digest(attribute, openssl_digest.name)
31
+
32
+ define_singleton_method(:"find_by_#{attribute}") do |token|
33
+ # Short-circuit to avoid the database query if the token is obviously invalid.
34
+ return if token.blank? || (token = token.to_s).length != length
35
+
36
+ # A bound parameter that matches the format of the digest in the index.
37
+ token_hash = bind_token_param(attribute.to_s, openssl_digest.digest(token))
38
+
39
+ # Produces:
40
+ # digest("table_name"."attribute", 'SHA256') = $1
41
+ find_by(token_arel.eq(token_hash))
42
+ end
43
+
44
+ define_singleton_method(:"find_by_#{attribute}!") do |token|
45
+ send(:"find_by_#{attribute}", token) or raise_record_not_find_by_token!
46
+ end
47
+ end
48
+
49
+ private
50
+
51
+ # @param attribute [Symbol]
52
+ # @param digest [String]
53
+ # @return [Arel::Nodes::Node]
54
+ def arel_token_digest(attribute, digest)
55
+ Arel::Nodes::NamedFunction.new('digest', [arel_table[attribute], Arel::Nodes.build_quoted(digest)])
56
+ end
57
+
58
+ # @param attribute [String]
59
+ # @param value [String]
60
+ # @return [Arel::Nodes::BindParam]
61
+ def bind_token_param(attribute, value)
62
+ Arel::Nodes::BindParam.new(ActiveRecord::Relation::QueryAttribute.new(attribute, value, secure_token_type))
63
+ end
64
+
65
+ # @return [ActiveModel::Type::Value]
66
+ def secure_token_type
67
+ @secure_token_type ||= ActiveRecord::Type.lookup(:binary)
68
+ end
69
+
70
+ # @return [void]
71
+ def raise_record_not_find_by_token!
72
+ none.raise_record_not_found_exception!
73
+ end
74
+ end
75
+
76
+ # @private
77
+ def self.included(base)
78
+ super(base)
79
+ base.extend(ClassMethods)
80
+ end
81
+ end
@@ -0,0 +1,4 @@
1
+ module HasMoreSecureToken
2
+ VERSION: String
3
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
4
+ end
metadata ADDED
@@ -0,0 +1,168 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: has_more_secure_token
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Minty Fresh
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2023-09-01 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: pg
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ">="
32
+ - !ruby/object:Gem::Version
33
+ version: '0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ">="
39
+ - !ruby/object:Gem::Version
40
+ version: '0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rails
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: '0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '13.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '13.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec-rails
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rubocop
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: rubocop-performance
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: rubocop-rspec
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ description: Time-safe finders for ActiveRecord's has_secure_token.
126
+ email:
127
+ - 7896757+mintyfresh@users.noreply.github.com
128
+ executables: []
129
+ extensions: []
130
+ extra_rdoc_files: []
131
+ files:
132
+ - ".rspec"
133
+ - ".rubocop.yml"
134
+ - CODE_OF_CONDUCT.md
135
+ - LICENSE.txt
136
+ - README.md
137
+ - Rakefile
138
+ - lib/has_more_secure_token.rb
139
+ - lib/has_more_secure_token/version.rb
140
+ - sig/has_more_secure_token.rbs
141
+ homepage: https://github.com/mintyfresh/has_more_secure_token
142
+ licenses:
143
+ - MIT
144
+ metadata:
145
+ allowed_push_host: https://rubygems.org
146
+ rubygems_mfa_required: 'true'
147
+ homepage_uri: https://github.com/mintyfresh/has_more_secure_token
148
+ source_code_uri: https://github.com/mintyfresh/has_more_secure_token
149
+ post_install_message:
150
+ rdoc_options: []
151
+ require_paths:
152
+ - lib
153
+ required_ruby_version: !ruby/object:Gem::Requirement
154
+ requirements:
155
+ - - ">="
156
+ - !ruby/object:Gem::Version
157
+ version: 2.7.0
158
+ required_rubygems_version: !ruby/object:Gem::Requirement
159
+ requirements:
160
+ - - ">="
161
+ - !ruby/object:Gem::Version
162
+ version: '0'
163
+ requirements: []
164
+ rubygems_version: 3.4.13
165
+ signing_key:
166
+ specification_version: 4
167
+ summary: Time-safe finders for ActiveRecord's has_secure_token.
168
+ test_files: []