enkrip 0.1.0 → 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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: ed86ace6f37ae25ece693100929e8c4a85721901fdce14878ba320293937c776
4
- data.tar.gz: 0b744465c19433f28b0317e933f11d711446aad4accdf2cbfee7863264256abc
3
+ metadata.gz: 62d803f39c181c552acaa84f83944d62517403a4b53ebed182dbb06e037c5e43
4
+ data.tar.gz: 015c4bcbe6cecad4aac9471a95910016f569a4e6ed86e27471a680f9eb71ee14
5
5
  SHA512:
6
- metadata.gz: 22acbd270fa85f882801487b5e507b59085af06592dd57bbdd23e66e85a761683243640cf00ca9eb193c31cb99df200cff0356e3651275630cdb016c5f1aa7d5
7
- data.tar.gz: fd963e2d091f3a29a3a5542bf0d7b4f80b5b71998c9747ed4309be683f0f2a97abbfb5dbada4fe7ae6c63b523cdc028380190feb74902bdc1c76e6c6c3da75b0
6
+ metadata.gz: 3c26336dde773471976452c1b49b0020646d1022d21ad44bd6f0c0c5a3a41224c4f935b0692b17829f6dbac62babd4c64f260890e433726f33fbc77176baa5b4
7
+ data.tar.gz: 1cfeca3f7bd2e5bed00e441d9b51bf8cf03df76c724991ef7d428446be776170a4322744b140756e0884c858f9cf788413608222b67ccdc114a1d584c8330158
data/CHANGELOG.md ADDED
@@ -0,0 +1,21 @@
1
+ 1.0.0:
2
+ * Breaking: Enkrip 1.0 cannot read data that Enkrip 0.1.x wrote. Use MIGRATION.md to move 0.1.x data to Active Record Encryption.
3
+ * Breaking: require Ruby 3.2 or newer and Active Record 8.0 or 8.1.
4
+ * Breaking: replace `enkrip_configure` with the `enkrip` macro, which uses a custom attribute type instead of callbacks.
5
+ * Breaking: replace the `ENKRIP_LENGTH`, `ENKRIP_SALT`, and `ENKRIP_SECRET` environment variables with `Enkrip.configure(secret:, salt:)`.
6
+ * Breaking: replace `Enkrip::Engine.encrypt` and `Enkrip::Engine.decrypt` with `Enkrip.encrypt` and `Enkrip.decrypt`.
7
+ * Breaking: remove the `Enkrip::KEY`, `Enkrip::SECRET`, `Enkrip::SALT`, `Enkrip::LENGTH`, and `ENCRYPTED_CONFIG` constants.
8
+ * Breaking: raise `Enkrip::DecryptionError` instead of returning `nil` when a value cannot be decrypted.
9
+ * Encrypt with AES-256-GCM, a SHA256 key, and the JSON serializer. Pin every option, so Rails `load_defaults` cannot change the format.
10
+ * Encrypt empty strings. Enkrip 0.1.x stored them as plaintext.
11
+ * Fix dirty tracking: a record loaded from the database is no longer marked as changed.
12
+ * Keep plaintext in memory when a save fails.
13
+ * Encrypt values written with `update_columns` and `insert_all`.
14
+
15
+ 0.1.0:
16
+ * Add Enkrip's configuration
17
+ * Implement encryption and decryption
18
+ * Create `Enkrip::Model` and `Enkrip::Engine`
19
+
20
+ 0.0.0:
21
+ * Initial commit
data/MIGRATION.md ADDED
@@ -0,0 +1,210 @@
1
+ # Migrate from Enkrip to Active Record Encryption
2
+
3
+ This guide moves data that Enkrip encrypted to [Active Record Encryption](https://guides.rubyonrails.org/active_record_encryption.html), which is built into Rails 7.0 and newer. The guide was tested with Rails 8.1 against data that Enkrip wrote on Active Support 5.2.
4
+
5
+ Enkrip 0.1.x requires Active Record 5.2, so you cannot install it next to Rails 7. This guide uses a small decryptor that reads the old Enkrip values without the gem.
6
+
7
+ > [!NOTE]
8
+ > This guide is for data that Enkrip 0.1.x wrote. Enkrip 1.0 uses a different format and runs on Rails 8. To migrate data from Enkrip 1.0:
9
+ >
10
+ > - Keep the gem and the `Enkrip.configure` initializer until Step 8. Skip Step 1.
11
+ > - Skip Step 3. In Step 6, remove `require "enkrip_legacy"`, use `Enkrip.decrypt` instead of `EnkripLegacy.decrypt`, and run the task without the `ENKRIP_*` variables.
12
+ > - In Step 8, remove the gem, the initializer, and the Enkrip secret and salt instead of the `ENKRIP_*` variables.
13
+
14
+ ## Before you start
15
+
16
+ - Back up the database. Do a test run on a copy of production data first.
17
+ - Plan a maintenance window. Between the deploy and the end of the backfill, rows that are not migrated yet show the Enkrip ciphertext as a string, and numeric attributes show `0`. Stop writes to the affected tables during the window.
18
+ - Keep the `ENKRIP_LENGTH`, `ENKRIP_SALT`, and `ENKRIP_SECRET` values until the migration is complete.
19
+
20
+ ## Step 1: Remove Enkrip and upgrade Rails
21
+
22
+ 1. Remove `gem 'enkrip'` from the Gemfile.
23
+ 2. Upgrade the app to Rails 7.0 or newer.
24
+
25
+ ## Step 2: Set up Active Record Encryption keys
26
+
27
+ Generate the keys:
28
+
29
+ ```bash
30
+ bin/rails db:encryption:init
31
+ ```
32
+
33
+ Store the output in Rails credentials (`bin/rails credentials:edit`) or in a secrets manager. Do not store the keys in plaintext environment files.
34
+
35
+ ## Step 3: Add the legacy decryptor
36
+
37
+ Create `lib/enkrip_legacy.rb`:
38
+
39
+ ```ruby
40
+ # frozen_string_literal: true
41
+
42
+ # Decrypts values that the enkrip gem wrote. Delete this file after the migration.
43
+ module EnkripLegacy
44
+ class Error < StandardError; end
45
+
46
+ # Enkrip used ActiveSupport::MessageEncryptor with default options. The default
47
+ # cipher was AES-256-GCM in a Rails 5.2 app (load_defaults 5.2) and AES-256-CBC
48
+ # otherwise. Pin every option, because the defaults changed in later Rails versions.
49
+ # Marshal is safe here only because the encryptor checks the message signature first.
50
+ def self.encryptors
51
+ @encryptors ||= begin
52
+ key = ActiveSupport::KeyGenerator.new(
53
+ ENV.fetch("ENKRIP_SECRET"),
54
+ hash_digest_class: OpenSSL::Digest::SHA1,
55
+ iterations: 2**16
56
+ ).generate_key(ENV.fetch("ENKRIP_SALT"), ENV.fetch("ENKRIP_LENGTH").to_i)
57
+
58
+ [
59
+ ActiveSupport::MessageEncryptor.new(key, cipher: "aes-256-gcm", serializer: Marshal),
60
+ ActiveSupport::MessageEncryptor.new(key, cipher: "aes-256-cbc", digest: "SHA1", serializer: Marshal)
61
+ ]
62
+ end
63
+ end
64
+
65
+ # Raises EnkripLegacy::Error when no encryptor can read the value. Enkrip
66
+ # returned nil on a purpose mismatch; this method raises instead, so a wrong
67
+ # purpose cannot overwrite data with nil.
68
+ def self.decrypt(value, purpose: nil)
69
+ encryptors.each do |encryptor|
70
+ result = encryptor.decrypt_and_verify(value, purpose: purpose)
71
+ return result unless result.nil?
72
+ rescue ActiveSupport::MessageEncryptor::InvalidMessage, ActiveSupport::MessageVerifier::InvalidSignature
73
+ next
74
+ end
75
+ raise Error, "cannot decrypt the Enkrip value (check the ENKRIP_* variables and the purpose)"
76
+ end
77
+ end
78
+ ```
79
+
80
+ Load it from the rake task in Step 6, or add `require "enkrip_legacy"` to an initializer.
81
+
82
+ ## Step 4: Update the models
83
+
84
+ Replace `include Enkrip::Model` and the `enkrip_configure` block with `encrypts`. Keep the columns as `text`.
85
+
86
+ Before:
87
+
88
+ ```ruby
89
+ class Post < ActiveRecord::Base
90
+ include Enkrip::Model
91
+
92
+ enkrip_configure do |config|
93
+ config.string_attributes << :my_string
94
+ config.numeric_attributes << :my_numeric
95
+ config.purpose = :example
96
+ end
97
+ end
98
+ ```
99
+
100
+ After:
101
+
102
+ ```ruby
103
+ class Post < ApplicationRecord
104
+ attribute :my_numeric, :integer
105
+ encrypts :my_string, :my_numeric
106
+ end
107
+ ```
108
+
109
+ How the Enkrip options map:
110
+
111
+ | Enkrip option | Active Record Encryption |
112
+ | --- | --- |
113
+ | `string_attributes` | `encrypts :name` |
114
+ | `numeric_attributes` | `attribute :name, :integer` before `encrypts :name`. Use `:float` or `:decimal` if `convert_method_for_numeric_attribute` was `:to_f` or `:to_d`. |
115
+ | `purpose` | Used only by the backfill in Step 6. |
116
+ | `default_value_if_numeric_attribute_blank` | No equivalent. A blank numeric value is now `nil`, not `0`. |
117
+
118
+ To query an encrypted column with `where`, add `deterministic: true` to that attribute. Enkrip could not query encrypted columns, so existing code does not need this.
119
+
120
+ ## Step 5: Allow unencrypted reads during the migration
121
+
122
+ Add this line to `config/application.rb`:
123
+
124
+ ```ruby
125
+ config.active_record.encryption.support_unencrypted_data = true
126
+ ```
127
+
128
+ Without this setting, every read of a row that is not migrated yet raises `ActiveRecord::Encryption::Errors::Decryption`. You remove the setting in Step 8.
129
+
130
+ ## Step 6: Run the backfill
131
+
132
+ Create `lib/tasks/enkrip.rake`. Edit `enkrip_targets` so that it lists every model that used Enkrip.
133
+
134
+ ```ruby
135
+ # frozen_string_literal: true
136
+
137
+ # Moves Enkrip data to Active Record Encryption. Delete this file after the migration.
138
+ require "enkrip_legacy"
139
+
140
+ # One entry per model. Copy the attributes and the purpose from the model's old
141
+ # enkrip_configure block. Use purpose: nil if the block did not set one.
142
+ enkrip_targets = lambda do
143
+ {
144
+ Post => { attributes: %i[my_string my_numeric], purpose: :example }
145
+ }
146
+ end
147
+
148
+ namespace :enkrip do
149
+ desc "Re-encrypt Enkrip values with Active Record Encryption"
150
+ task migrate: :environment do
151
+ enkrip_targets.call.each do |model, config|
152
+ model.find_each do |record|
153
+ values = config[:attributes].each_with_object({}) do |attr, result|
154
+ raw = record.read_attribute_before_type_cast(attr)
155
+ next if raw.nil? || ActiveRecord::Encryption.encryptor.encrypted?(raw)
156
+
157
+ # Enkrip stored blank values as plaintext. Re-save them so they get encrypted.
158
+ result[attr] = raw.blank? ? raw : EnkripLegacy.decrypt(raw, purpose: config[:purpose])
159
+ end
160
+ # update_columns skips validations, callbacks, and updated_at.
161
+ record.update_columns(values) if values.any?
162
+ end
163
+ end
164
+ end
165
+
166
+ desc "Count rows that still hold values that are not encrypted by Active Record Encryption"
167
+ task check: :environment do
168
+ remaining = 0
169
+ enkrip_targets.call.each do |model, config|
170
+ count = model.find_each.count do |record|
171
+ config[:attributes].any? do |attr|
172
+ raw = record.read_attribute_before_type_cast(attr)
173
+ !raw.nil? && !ActiveRecord::Encryption.encryptor.encrypted?(raw)
174
+ end
175
+ end
176
+ puts "#{model.name}: #{count} rows left"
177
+ remaining += count
178
+ end
179
+ abort "Migration is not complete" if remaining.positive?
180
+ end
181
+ end
182
+ ```
183
+
184
+ Run the backfill with the old Enkrip values in the environment:
185
+
186
+ ```bash
187
+ ENKRIP_LENGTH=... ENKRIP_SALT=... ENKRIP_SECRET=... bin/rails enkrip:migrate
188
+ ```
189
+
190
+ The task skips values that are already encrypted, so you can run it again after a failure. If it raises `EnkripLegacy::Error`, check the `ENKRIP_*` values and the `purpose` for that model.
191
+
192
+ ## Step 7: Verify
193
+
194
+ ```bash
195
+ bin/rails enkrip:check
196
+ ```
197
+
198
+ Every model must show `0 rows left`. Then open a few records in the Rails console and compare the values with the values in the old app.
199
+
200
+ ## Step 8: Clean up
201
+
202
+ 1. Remove `support_unencrypted_data = true` from `config/application.rb`, and deploy.
203
+ 2. Delete `lib/enkrip_legacy.rb` and `lib/tasks/enkrip.rake`.
204
+ 3. Remove `ENKRIP_LENGTH`, `ENKRIP_SALT`, and `ENKRIP_SECRET` from every environment.
205
+ 4. Database backups made before the migration still hold Enkrip ciphertext. Keep the old `ENKRIP_*` values in a secrets manager for as long as you keep those backups, then destroy the values.
206
+
207
+ ## Behavior changes
208
+
209
+ - A blank numeric attribute is `nil`, not `0`. Handle `nil` in your code, or set a default value for new records (`attribute :my_numeric, :integer, default: 0`).
210
+ - A value that cannot be decrypted raises an error. Enkrip returned `nil`.
data/README.md CHANGED
@@ -1,50 +1,68 @@
1
+ [![Gem Version](https://badge.fury.io/rb/enkrip.svg)](https://badge.fury.io/rb/enkrip)
2
+
1
3
  # Enkrip
2
4
 
3
- Encrypt & decrypt Active Record's model attributes with Message Encryptor.
5
+ > [!WARNING]
6
+ > **Enkrip is deprecated for production use.** Version 1.0 is a learning rewrite for Rails 8. For production, use [Active Record Encryption](https://guides.rubyonrails.org/active_record_encryption.html), which is built into Rails 7.0 and newer and supports key rotation and queries on encrypted columns. To move existing Enkrip data, follow [MIGRATION.md](MIGRATION.md).
4
7
 
5
- ## Goals
8
+ Enkrip encrypts Active Record attributes with [ActiveSupport::MessageEncryptor](https://api.rubyonrails.org/classes/ActiveSupport/MessageEncryptor.html) (AES-256-GCM). Each encrypted attribute uses a custom attribute type, so:
6
9
 
7
- * Seamlessly encrypt and decrypt value for both string and numeric attribute
8
- * Compatible with Active Model validation
9
- * Automatically convert numeric attributes to desired data types
10
+ * The value in memory is always plaintext of the right class (`String`, `Integer`, `BigDecimal`, and so on).
11
+ * Only the value in the database is ciphertext.
12
+ * Validations, dirty tracking, `update_columns`, and `insert_all` work as usual.
10
13
 
11
- ## Limitations
14
+ ## Requirements
12
15
 
13
- * All attributes that are defined in `numeric_attributes` will be forced to use UTF-8 encoding
14
- * Enkrip requires Active Record 5.2 or newer
15
- * Does not compatible with [activerecord-import](https://rubygems.org/gems/activerecord-import)
16
+ * Ruby 3.2 or newer
17
+ * Active Record 8.0 or 8.1
16
18
 
17
19
  ## Installation
18
20
 
19
- Add `enkrip` to your Rails app’s Gemfile and run bundle install:
21
+ Add `enkrip` to your Gemfile and run `bundle install`:
20
22
 
21
- ```
23
+ ```ruby
22
24
  gem 'enkrip'
23
25
  ```
24
26
 
25
27
  ## Configuration
26
28
 
27
- After installation, you need to define `ENKRIP_LENGTH`, `ENKRIP_SALT`, and `ENKRIP_SECRET` environment variables:
29
+ Enkrip needs a secret (at least 32 bytes) and a salt (at least 16 bytes). Generate them:
28
30
 
29
- ```
30
- # example
31
- export ENKRIP_LENGTH=32 # 32 is default value from ActiveSupport::MessageEncryptor.key_len
32
- export ENKRIP_SALT=random_salt_with_length_32 # you can generate from SecureRandom.random_bytes(YOUR_ENKRIP_LENGTH)
33
- export ENKRIP_SECRET=random_secret_with_length_32
31
+ ```ruby
32
+ require 'securerandom'
33
+ SecureRandom.hex(32) # secret
34
+ SecureRandom.hex(16) # salt
34
35
  ```
35
36
 
36
- ## Usage
37
+ Store both values in Rails credentials (`bin/rails credentials:edit`) or in a secrets manager. Do not put them in a plaintext `.env` file:
38
+
39
+ ```yaml
40
+ enkrip:
41
+ secret: <64 hex characters>
42
+ salt: <32 hex characters>
43
+ ```
37
44
 
38
- Use text data type for encrypted attributes
45
+ Then configure Enkrip in an initializer. `Enkrip.configure` raises `Enkrip::ConfigurationError` if a value is missing or too short, so a bad value stops the app at boot:
39
46
 
47
+ ```ruby
48
+ # config/initializers/enkrip.rb
49
+ Enkrip.configure(
50
+ secret: Rails.application.credentials.dig(:enkrip, :secret),
51
+ salt: Rails.application.credentials.dig(:enkrip, :salt)
52
+ )
40
53
  ```
41
- # migration
42
54
 
43
- class CreatePosts < ActiveRecord::Migration[5.2]
55
+ ## Usage
56
+
57
+ Use the `text` column type for encrypted attributes, whatever the attribute type is:
58
+
59
+ ```ruby
60
+ class CreatePosts < ActiveRecord::Migration[8.1]
44
61
  def change
45
62
  create_table :posts do |t|
46
63
  t.text :my_string
47
64
  t.text :my_numeric
65
+ t.text :price
48
66
 
49
67
  t.timestamps
50
68
  end
@@ -52,49 +70,57 @@ class CreatePosts < ActiveRecord::Migration[5.2]
52
70
  end
53
71
  ```
54
72
 
55
- After run the migration, define you encrypted attributes
56
-
57
- ```
58
- # Active Record model
73
+ Declare the encrypted attributes with `enkrip`. The `type` option and any other options select the attribute type, as in `attribute name, type, **options`. The default type is `:string`:
59
74
 
60
- class Post < ActiveRecord::Base
75
+ ```ruby
76
+ class Post < ApplicationRecord
61
77
  include Enkrip::Model
62
78
 
63
- enkrip_configure do |config|
64
- config.string_attributes << :my_string
65
- config.numeric_attributes << :my_numeric
66
- config.purpose = :example # optional, default is nil
67
- config.convert_method_for_numeric_attribute = :to_f # optional, default is to_i
68
- config.default_value_if_numeric_attribute_blank = 0.0 # optional, default is 0
69
- end
79
+ enkrip :my_string, purpose: :post
80
+ enkrip :my_numeric, type: :integer, purpose: :post
81
+ enkrip :price, type: :decimal, precision: 10, scale: 2
82
+
83
+ validates :my_numeric, numericality: { greater_than: 0 }
84
+ validates :my_string, presence: true
70
85
  end
71
86
  ```
72
87
 
73
- You can check encrypted value from rails console with raw query
88
+ `purpose` is optional. A value encrypted with one purpose cannot be decrypted with another purpose, so a ciphertext copied from one column into another column does not decrypt.
74
89
 
75
- ```
76
- # Rails 5.2 console
77
- post = Post.new => #<Post id: nil, my_string: nil, my_numeric: nil, created_at: nil, updated_at: nil>
78
- post.valid? # => false
79
- post.errors.full_messages # => ["My numeric must be greater than 0", "My string can't be blank"]
90
+ ```ruby
91
+ post = Post.create!(my_string: 'aloha', my_numeric: '5', price: '9.99')
92
+ post.my_numeric # => 5
80
93
 
81
- post.my_string = "aloha" # => "aloha"
82
- post.my_numeric = 5 # => 5
83
- post.save # => true
94
+ ActiveRecord::Base.connection.select_value('SELECT my_string FROM posts LIMIT 1')
95
+ # => "Miiym4QLKiYHFVvl...--qq96w95UU1DZc+Qg--qJ4hDjx27d7KXqGAAq5vcw==" (ciphertext--nonce--auth tag)
84
96
 
85
- raw = ActiveRecord::Base.connection.exec_query 'SELECT my_string, my_numeric FROM posts limit 1'
97
+ post.reload.my_string # => "aloha"
98
+ post.changed? # => false
99
+ ```
86
100
 
87
- raw.rows.first[raw.columns.find_index('my_string')]
88
- # => "TUVQcnRBck5oYzMvRlRZUWR3Mzlzdz09LS1tZ09xNGNYbnkzdFc2d1duMEIrdUdBPT0=--ffae1f04753ca5c636915746a4c6fccf81897138"
101
+ ### Encrypt values outside a model
89
102
 
90
- raw.rows.first[raw.columns.find_index('my_numeric')]
91
- # => "TkdSbURRNzVMbUF6MjF0bjI2ZEtmQT09LS1rRHhqQ2xpWGhYaHBoRlhCRnVZSmh3PT0=--74e45e6c96df78258a1731994a71a74c5047d655"
103
+ ```ruby
104
+ ciphertext = Enkrip.encrypt('hello world', purpose: :example)
92
105
 
93
- post.reload
94
- post.my_string # => "aloha"
95
- post.my_numeric # => 5
106
+ Enkrip.decrypt(ciphertext, purpose: :example) # => "hello world"
107
+ Enkrip.decrypt(ciphertext, purpose: :other) # raises Enkrip::DecryptionError
108
+ Enkrip.decrypt(ciphertext) # raises Enkrip::DecryptionError
96
109
  ```
97
110
 
111
+ `Enkrip.encrypt` accepts any value that JSON can represent, except `nil`.
112
+
113
+ ## Errors
114
+
115
+ * `Enkrip::ConfigurationError`: Enkrip is not configured, or the secret or the salt is too short.
116
+ * `Enkrip::DecryptionError`: the ciphertext is invalid, the key is wrong, or the purpose does not match. Enkrip never returns `nil` for a value that it cannot decrypt, so a wrong key cannot replace stored data with `nil`.
117
+
118
+ ## Limitations
119
+
120
+ * You cannot query an encrypted column with `where(my_string: 'aloha')`. Each encryption uses a random nonce, so the same value gives a different ciphertext every time.
121
+ * Enkrip has no key rotation. If you change the secret or the salt, Enkrip cannot read the existing data.
122
+ * Enkrip 1.0 cannot read data that Enkrip 0.1.x wrote, and Enkrip 0.1.x cannot read data that Enkrip 1.0 wrote.
123
+
98
124
  ## License
99
125
 
100
126
  Enkrip is released under the [MIT License](https://opensource.org/licenses/MIT).
data/lib/enkrip/engine.rb CHANGED
@@ -1,22 +1,54 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Enkrip
4
- LENGTH = ENV['ENKRIP_LENGTH'].to_i # ActiveSupport::MessageEncryptor.key_len
5
- SALT = ENV['ENKRIP_SALT'] # SecureRandom.random_bytes(LENGTH)
6
- SECRET = ENV['ENKRIP_SECRET']
7
- KEY = ActiveSupport::KeyGenerator.new(SECRET).generate_key(SALT, LENGTH).freeze
8
-
4
+ # Encrypts and decrypts single values with AES-256-GCM.
5
+ #
6
+ # Every option is pinned, so the Rails `load_defaults` setting cannot change
7
+ # the message format. The JSON serializer never deserializes Ruby objects.
9
8
  class Engine
10
- class << self
11
- @@verifier = ActiveSupport::MessageEncryptor.new(Enkrip::KEY)
9
+ CIPHER = 'aes-256-gcm'
10
+ MIN_SECRET_BYTES = 32
11
+ MIN_SALT_BYTES = 16
12
+ KEY_ITERATIONS = 2**16
13
+
14
+ def initialize(secret:, salt:)
15
+ validate!(:secret, secret, MIN_SECRET_BYTES)
16
+ validate!(:salt, salt, MIN_SALT_BYTES)
17
+
18
+ key = ActiveSupport::KeyGenerator
19
+ .new(secret, hash_digest_class: OpenSSL::Digest::SHA256, iterations: KEY_ITERATIONS)
20
+ .generate_key(salt, ActiveSupport::MessageEncryptor.key_len(CIPHER))
21
+ @encryptor = ActiveSupport::MessageEncryptor.new(key, cipher: CIPHER, serializer: :json)
22
+ end
23
+
24
+ # A nil value is not allowed: decrypt uses a nil result to detect a purpose mismatch.
25
+ def encrypt(value, purpose: nil)
26
+ raise ArgumentError, 'Enkrip cannot encrypt nil' if value.nil?
27
+
28
+ @encryptor.encrypt_and_sign(value, purpose: purpose)
29
+ end
30
+
31
+ # Raises DecryptionError instead of returning nil, so a wrong key or
32
+ # purpose cannot silently replace stored data with nil.
33
+ def decrypt(value, purpose: nil)
34
+ result = @encryptor.decrypt_and_verify(value, purpose: purpose)
35
+ raise DecryptionError, 'Enkrip cannot decrypt the value: the purpose does not match' if result.nil?
36
+
37
+ result
38
+ rescue ActiveSupport::MessageEncryptor::InvalidMessage
39
+ raise DecryptionError, 'Enkrip cannot decrypt the value: the message is invalid or the key is wrong'
40
+ end
41
+
42
+ def inspect
43
+ "#<#{self.class.name} cipher=#{CIPHER}>"
44
+ end
45
+
46
+ private
12
47
 
13
- def encrypt(value, purpose: nil)
14
- @@verifier.encrypt_and_sign value, purpose: purpose
15
- end
48
+ def validate!(name, value, min_bytes)
49
+ return if value.is_a?(String) && value.bytesize >= min_bytes
16
50
 
17
- def decrypt(value, purpose: nil)
18
- @@verifier.decrypt_and_verify value, purpose: purpose
19
- end
51
+ raise ConfigurationError, "Enkrip #{name} must be a String of at least #{min_bytes} bytes"
20
52
  end
21
53
  end
22
54
  end
data/lib/enkrip/model.rb CHANGED
@@ -1,47 +1,25 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Enkrip
4
+ # Adds the `enkrip` macro to an Active Record model.
5
+ #
6
+ # class Post < ApplicationRecord
7
+ # include Enkrip::Model
8
+ #
9
+ # enkrip :title, purpose: :post
10
+ # enkrip :views, type: :integer
11
+ # end
4
12
  module Model
5
13
  extend ActiveSupport::Concern
6
14
 
7
- included do
8
- after_find :decrypt
9
- before_save :encrypt
10
- after_save :decrypt
11
-
12
- def encrypt
13
- self.class::ENCRYPTED_CONFIG.all_attributes.each do |attr|
14
- self[attr] = Enkrip::Engine.encrypt(self[attr], purpose: self.class::ENCRYPTED_CONFIG.purpose) if respond_to?(attr) && self[attr].present?
15
- end
16
- end
17
-
18
- def decrypt
19
- self.class::ENCRYPTED_CONFIG.all_attributes.each do |attr|
20
- self[attr] = Enkrip::Engine.decrypt(self[attr], purpose: self.class::ENCRYPTED_CONFIG.purpose) if respond_to?(attr) && self[attr].present?
21
- end
22
- end
23
- end
24
-
25
15
  class_methods do
26
- def enkrip_configure
27
- config = OpenStruct.new(
28
- string_attributes: [],
29
- numeric_attributes: [],
30
- purpose: nil,
31
- convert_method_for_numeric_attribute: :to_i,
32
- default_value_if_numeric_attribute_blank: 0
33
- )
34
-
35
- yield config
36
-
37
- config.all_attributes = config.string_attributes + config.numeric_attributes
38
- const_set :ENCRYPTED_CONFIG, config
16
+ # Declares encrypted attributes. `type` and `options` select the subtype,
17
+ # as in `attribute name, type, **options`. The database column must be `text`.
18
+ def enkrip(*names, type: :string, purpose: nil, **options)
19
+ raise ArgumentError, 'enkrip needs at least one attribute name' if names.empty?
39
20
 
40
- config.numeric_attributes.each do |attr|
41
- define_method(attr) do
42
- value = super()
43
- value.present? ? value.force_encoding('UTF-8').send(config.convert_method_for_numeric_attribute) : config.default_value_if_numeric_attribute_blank
44
- end
21
+ names.each do |name|
22
+ attribute name, Enkrip::Type.new(subtype: ActiveRecord::Type.lookup(type, **options), purpose: purpose)
45
23
  end
46
24
  end
47
25
  end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Enkrip
4
+ # An attribute type that encrypts the value of another type (the subtype).
5
+ #
6
+ # Casting uses the subtype, so the in-memory value is always plaintext of the
7
+ # right class. Only the value sent to the database is ciphertext.
8
+ class Type < ActiveModel::Type::Value
9
+ attr_reader :subtype, :purpose
10
+
11
+ delegate :type, :cast, to: :subtype
12
+
13
+ def initialize(subtype:, purpose: nil)
14
+ super()
15
+ @subtype = subtype
16
+ @purpose = purpose
17
+ end
18
+
19
+ def serialize(value)
20
+ plaintext = subtype.serialize(value)
21
+ return if plaintext.nil?
22
+
23
+ Enkrip.encrypt(plaintext, purpose: purpose)
24
+ end
25
+
26
+ def deserialize(value)
27
+ return if value.nil?
28
+
29
+ subtype.deserialize(Enkrip.decrypt(value, purpose: purpose))
30
+ end
31
+
32
+ # GCM uses a random nonce, so two ciphertexts of one value always differ.
33
+ # Compare the decrypted old value with the new value instead.
34
+ def changed_in_place?(raw_old_value, new_value)
35
+ deserialize(raw_old_value) != new_value
36
+ end
37
+ end
38
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Enkrip
4
- VERSION = '0.1.0'
4
+ VERSION = '1.0.0'
5
5
  end
data/lib/enkrip.rb CHANGED
@@ -1,6 +1,36 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require 'active_record'
4
- require 'enkrip/version'
5
- require 'enkrip/engine'
6
- require 'enkrip/model'
4
+
5
+ # Encrypts Active Record attributes with ActiveSupport::MessageEncryptor.
6
+ module Enkrip
7
+ class Error < StandardError; end
8
+ class ConfigurationError < Error; end
9
+ class DecryptionError < Error; end
10
+
11
+ class << self
12
+ # Builds the engine at once, so a bad secret or salt fails at boot.
13
+ # A failed call keeps the current engine.
14
+ def configure(secret:, salt:)
15
+ @engine = Engine.new(secret: secret, salt: salt)
16
+ nil
17
+ end
18
+
19
+ def engine
20
+ @engine || raise(ConfigurationError, 'Enkrip is not configured. Call Enkrip.configure first.')
21
+ end
22
+
23
+ def encrypt(value, purpose: nil)
24
+ engine.encrypt(value, purpose: purpose)
25
+ end
26
+
27
+ def decrypt(value, purpose: nil)
28
+ engine.decrypt(value, purpose: purpose)
29
+ end
30
+ end
31
+ end
32
+
33
+ require_relative 'enkrip/version'
34
+ require_relative 'enkrip/engine'
35
+ require_relative 'enkrip/type'
36
+ require_relative 'enkrip/model'
metadata CHANGED
@@ -1,14 +1,13 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: enkrip
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.0
4
+ version: 1.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Kunto Aji Kristianto
8
- autorequire:
9
8
  bindir: bin
10
9
  cert_chain: []
11
- date: 2018-10-28 00:00:00.000000000 Z
10
+ date: 1980-01-02 00:00:00.000000000 Z
12
11
  dependencies:
13
12
  - !ruby/object:Gem::Dependency
14
13
  name: activerecord
@@ -16,101 +15,43 @@ dependencies:
16
15
  requirements:
17
16
  - - ">="
18
17
  - !ruby/object:Gem::Version
19
- version: '5.2'
18
+ version: '8.0'
20
19
  - - "<"
21
20
  - !ruby/object:Gem::Version
22
- version: '6'
21
+ version: '9'
23
22
  type: :runtime
24
23
  prerelease: false
25
24
  version_requirements: !ruby/object:Gem::Requirement
26
25
  requirements:
27
26
  - - ">="
28
27
  - !ruby/object:Gem::Version
29
- version: '5.2'
28
+ version: '8.0'
30
29
  - - "<"
31
30
  - !ruby/object:Gem::Version
32
- version: '6'
33
- - !ruby/object:Gem::Dependency
34
- name: bundler
35
- requirement: !ruby/object:Gem::Requirement
36
- requirements:
37
- - - "~>"
38
- - !ruby/object:Gem::Version
39
- version: '1.16'
40
- type: :development
41
- prerelease: false
42
- version_requirements: !ruby/object:Gem::Requirement
43
- requirements:
44
- - - "~>"
45
- - !ruby/object:Gem::Version
46
- version: '1.16'
47
- - !ruby/object:Gem::Dependency
48
- name: rake
49
- requirement: !ruby/object:Gem::Requirement
50
- requirements:
51
- - - "~>"
52
- - !ruby/object:Gem::Version
53
- version: '12.3'
54
- type: :development
55
- prerelease: false
56
- version_requirements: !ruby/object:Gem::Requirement
57
- requirements:
58
- - - "~>"
59
- - !ruby/object:Gem::Version
60
- version: '12.3'
61
- - !ruby/object:Gem::Dependency
62
- name: minitest
63
- requirement: !ruby/object:Gem::Requirement
64
- requirements:
65
- - - "~>"
66
- - !ruby/object:Gem::Version
67
- version: '5.11'
68
- type: :development
69
- prerelease: false
70
- version_requirements: !ruby/object:Gem::Requirement
71
- requirements:
72
- - - "~>"
73
- - !ruby/object:Gem::Version
74
- version: '5.11'
75
- - !ruby/object:Gem::Dependency
76
- name: sqlite3
77
- requirement: !ruby/object:Gem::Requirement
78
- requirements:
79
- - - "~>"
80
- - !ruby/object:Gem::Version
81
- version: '0'
82
- type: :development
83
- prerelease: false
84
- version_requirements: !ruby/object:Gem::Requirement
85
- requirements:
86
- - - "~>"
87
- - !ruby/object:Gem::Version
88
- version: '0'
89
- description: Enkrip will encrypt & decrypt Active Record attributes seamlessly with
90
- Message Encryptor. By default compatible with Active model validation
31
+ version: '9'
32
+ description: Enkrip encrypts Active Record attributes with AES-256-GCM through a custom
33
+ attribute type. It works with Active Model validations and dirty tracking.
91
34
  email: kuntoaji@kaklabs.com
92
35
  executables: []
93
36
  extensions: []
94
37
  extra_rdoc_files: []
95
38
  files:
96
- - ".gitignore"
97
- - Gemfile
98
- - Gemfile.lock
39
+ - CHANGELOG.md
99
40
  - LICENSE.txt
41
+ - MIGRATION.md
100
42
  - README.md
101
- - Rakefile
102
- - enkrip.gemspec
103
43
  - lib/enkrip.rb
104
44
  - lib/enkrip/engine.rb
105
45
  - lib/enkrip/model.rb
46
+ - lib/enkrip/type.rb
106
47
  - lib/enkrip/version.rb
107
- - test/test_enkrip.rb
108
- - test/test_helper.rb
109
- homepage: http://github.com/kuntoaji/enkrip
48
+ homepage: https://github.com/kuntoaji/enkrip
110
49
  licenses:
111
50
  - MIT
112
- metadata: {}
113
- post_install_message:
51
+ metadata:
52
+ source_code_uri: https://github.com/kuntoaji/enkrip
53
+ changelog_uri: https://github.com/kuntoaji/enkrip/blob/master/CHANGELOG.md
54
+ rubygems_mfa_required: 'true'
114
55
  rdoc_options: []
115
56
  require_paths:
116
57
  - lib
@@ -118,16 +59,14 @@ required_ruby_version: !ruby/object:Gem::Requirement
118
59
  requirements:
119
60
  - - ">="
120
61
  - !ruby/object:Gem::Version
121
- version: '0'
62
+ version: '3.2'
122
63
  required_rubygems_version: !ruby/object:Gem::Requirement
123
64
  requirements:
124
65
  - - ">="
125
66
  - !ruby/object:Gem::Version
126
67
  version: '0'
127
68
  requirements: []
128
- rubyforge_project:
129
- rubygems_version: 2.7.6
130
- signing_key:
69
+ rubygems_version: 4.0.20
131
70
  specification_version: 4
132
- summary: encrypt & decrypt Active Record attributes with Message Encryptor
71
+ summary: Encrypt and decrypt Active Record attributes with ActiveSupport::MessageEncryptor
133
72
  test_files: []
data/.gitignore DELETED
@@ -1 +0,0 @@
1
- *.gem
data/Gemfile DELETED
@@ -1,3 +0,0 @@
1
- source 'https://rubygems.org'
2
-
3
- gemspec
data/Gemfile.lock DELETED
@@ -1,43 +0,0 @@
1
- PATH
2
- remote: .
3
- specs:
4
- enkrip (0.1.0)
5
- activerecord (>= 5.2, < 6)
6
-
7
- GEM
8
- remote: https://rubygems.org/
9
- specs:
10
- activemodel (5.2.1)
11
- activesupport (= 5.2.1)
12
- activerecord (5.2.1)
13
- activemodel (= 5.2.1)
14
- activesupport (= 5.2.1)
15
- arel (>= 9.0)
16
- activesupport (5.2.1)
17
- concurrent-ruby (~> 1.0, >= 1.0.2)
18
- i18n (>= 0.7, < 2)
19
- minitest (~> 5.1)
20
- tzinfo (~> 1.1)
21
- arel (9.0.0)
22
- concurrent-ruby (1.0.5)
23
- i18n (1.1.1)
24
- concurrent-ruby (~> 1.0)
25
- minitest (5.11.3)
26
- rake (12.3.1)
27
- sqlite3 (1.3.13)
28
- thread_safe (0.3.6)
29
- tzinfo (1.2.5)
30
- thread_safe (~> 0.1)
31
-
32
- PLATFORMS
33
- ruby
34
-
35
- DEPENDENCIES
36
- bundler (~> 1.16)
37
- enkrip!
38
- minitest (~> 5.11)
39
- rake (~> 12.3)
40
- sqlite3
41
-
42
- BUNDLED WITH
43
- 1.16.6
data/Rakefile DELETED
@@ -1,8 +0,0 @@
1
- require 'rake/testtask'
2
-
3
- Rake::TestTask.new do |t|
4
- t.libs << 'test'
5
- end
6
-
7
- desc 'Run tests'
8
- task default: :test
data/enkrip.gemspec DELETED
@@ -1,21 +0,0 @@
1
- require 'date'
2
- require_relative 'lib/enkrip/version'
3
-
4
- Gem::Specification.new do |spec|
5
- spec.name = 'enkrip'
6
- spec.version = Enkrip::VERSION
7
- spec.date = Date.today.to_s
8
- spec.summary = 'encrypt & decrypt Active Record attributes with Message Encryptor'
9
- spec.description = 'Enkrip will encrypt & decrypt Active Record attributes seamlessly with Message Encryptor. By default compatible with Active model validation'
10
- spec.author = 'Kunto Aji Kristianto'
11
- spec.email = 'kuntoaji@kaklabs.com'
12
- spec.files = `git ls-files -z`.split("\x0")
13
- spec.homepage = 'http://github.com/kuntoaji/enkrip'
14
- spec.license = 'MIT'
15
-
16
- spec.add_dependency 'activerecord', '>= 5.2', '< 6'
17
- spec.add_development_dependency 'bundler', '~> 1.16'
18
- spec.add_development_dependency 'rake', '~> 12.3'
19
- spec.add_development_dependency 'minitest', '~> 5.11'
20
- spec.add_development_dependency 'sqlite3', '~> 0'
21
- end
data/test/test_enkrip.rb DELETED
@@ -1,33 +0,0 @@
1
- require 'test_helper'
2
-
3
- describe Enkrip do
4
- def test_version
5
- assert Enkrip::VERSION
6
- end
7
-
8
- def test_encryption_decryption
9
- model = ExampleModel.new my_string: '', my_numeric: 0
10
- assert_equal model.valid?, false
11
-
12
- model.my_string = 'my example string'
13
- model.my_numeric = 1
14
- model.save!
15
- model.reload
16
-
17
- raw = ActiveRecord::Base.connection.exec_query 'SELECT my_string, my_numeric FROM example_models limit 1'
18
- encrypted_my_string = raw.rows.first.first
19
- encrypted_my_numeric = raw.rows.first.last
20
-
21
- assert_equal encrypted_my_string.nil?, false
22
- assert_equal encrypted_my_string.empty?, false
23
- refute_equal encrypted_my_string, model.my_string
24
- assert_equal model.my_string, 'my example string'
25
- assert_equal Enkrip::Engine.decrypt(encrypted_my_string, purpose: :example), 'my example string'
26
-
27
- assert_equal encrypted_my_numeric.nil?, false
28
- assert_equal encrypted_my_numeric.empty?, false
29
- refute_equal encrypted_my_numeric, model.my_numeric
30
- assert_equal model.my_numeric, 1
31
- assert_equal Enkrip::Engine.decrypt(encrypted_my_numeric, purpose: :example).to_i, 1
32
- end
33
- end
data/test/test_helper.rb DELETED
@@ -1,25 +0,0 @@
1
- require 'minitest/autorun'
2
-
3
- ENV['ENKRIP_LENGTH'] = '32'
4
- ENV['ENKRIP_SALT'] = 'y\xBC\xAD\xA7\xAE6\xAD\x9F](\x89\xB2\xF6!\xED\xC8\xA2(1\x8E\xA9&/ef`\xD3\xB3\x11\xB6C\xB4' # SecureRandom.random_bytes(LENGTH)
5
- ENV['ENKRIP_SECRET'] = 'f031fbebc6bb5a69094139c24090fd42'
6
-
7
- require_relative '../lib/enkrip'
8
-
9
- ActiveRecord::Base.establish_connection adapter: 'sqlite3', database: ':memory:', encoding: 'unicode'
10
- ActiveRecord::Base.connection.create_table(:example_models, force: true) do |t|
11
- t.text :my_string
12
- t.text :my_numeric
13
- end
14
-
15
- class ExampleModel < ActiveRecord::Base
16
- include Enkrip::Model
17
- validates :my_numeric, numericality: { greater_than: 0 }
18
- validates :my_string, presence: true
19
-
20
- enkrip_configure do |config|
21
- config.string_attributes << :my_string
22
- config.numeric_attributes << :my_numeric
23
- config.purpose = :example # optional
24
- end
25
- end