diffcrypt 0.1.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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 123f8eedd18059e8df8ceee8ab1d8bf67db179c05102f13fc0eb826e05c5d1de
4
+ data.tar.gz: 9ea816271de575fc3e101b2bc7898ab85513beffc0ab126426a286e86310ebdc
5
+ SHA512:
6
+ metadata.gz: 8a97bbbd2f9c0f3f5ec04acb7ab65514b747da321fa1bf1d295c9e7a8a98b755d711b653cc888c60fa44b26a1e115a87061ee80d01788e6680a05e42eb5c8162
7
+ data.tar.gz: 5a1b1446b201762d5463d0774638dee995af9c26c6aad375f804f0682dd0efb8ce74c4fb40c7c048ba306a1e24fa18bc37408173f4bbe1852e12bd552522f25d
@@ -0,0 +1,10 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+ Gemfile.lock
10
+ *.gem
@@ -0,0 +1,15 @@
1
+ AllCops:
2
+ NewCops: enable
3
+
4
+ Style/ClassAndModuleChildren:
5
+ Exclude:
6
+ - test/**/*_test.rb
7
+ Style/Documentation:
8
+ Enabled: false
9
+ Metrics/MethodLength:
10
+ Exclude:
11
+ - test/**/*_test.rb
12
+
13
+ Layout/LineLength:
14
+ Exclude:
15
+ - test/**/*_test.rb
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.6.6
6
+ before_install: gem install bundler -v 2.1.4
data/Gemfile ADDED
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in diffcrypt.gemspec
6
+ gemspec
7
+
8
+ gem 'minitest', '~> 5.0'
9
+ gem 'rake', '~> 13.0'
10
+ gem 'rubocop', '~> 0.86'
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Marc Qualie
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.
@@ -0,0 +1,84 @@
1
+ # Diffcrypt
2
+
3
+ Diffable encrypted files that you can safely commit into your repo.
4
+
5
+
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'diffcrypt'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install diffcrypt
22
+
23
+
24
+
25
+ ## Usage
26
+
27
+
28
+ ### Encrypt existing file
29
+
30
+ ```ruby
31
+ encryptor = Diffcrypt::Encryptor.new('99e1f86b9e61f24c56ff4108dd415091')
32
+ yaml = File.read('test/fixtures/example.yml')
33
+ encrypted = encryptor.encrypt(yaml)
34
+ File.write('tmp/example.yml.enc', encrypted)
35
+ ```
36
+
37
+ ### Decrypt a file
38
+
39
+ ```ruby
40
+ encryptor = Diffcrypt::Encryptor.new('99e1f86b9e61f24c56ff4108dd415091')
41
+ yaml = File.read('test/fixtures/example.yml.enc')
42
+ config = YAML.safe_load(encryptor.decrypt(yaml))
43
+ ```
44
+
45
+ ### Rails
46
+
47
+ Currently there is not native support for rails, but ActiveSupport can be monkeypatched to override
48
+ the build in encrypter.
49
+
50
+ ```ruby
51
+ require 'diffcrypt/rails/encrypted_configuration'
52
+ module Rails
53
+ class Application
54
+ def encrypted(path, key_path: 'config/master.key', env_key: 'RAILS_MASTER_KEY')
55
+ Diffcrypt::Rails::EncryptedConfiguration.new(
56
+ config_path: Rails.root.join(path),
57
+ key_path: Rails.root.join(key_path),
58
+ env_key: env_key,
59
+ raise_if_missing_key: config.require_master_key,
60
+ )
61
+ end
62
+ end
63
+ end
64
+ ```
65
+
66
+
67
+
68
+ ## Development
69
+
70
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
71
+
72
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
73
+
74
+
75
+
76
+ ## Contributing
77
+
78
+ Bug reports and pull requests are welcome on GitHub at https://github.com/marcqualie/diffcrypt.
79
+
80
+
81
+
82
+ ## License
83
+
84
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rake/testtask'
5
+
6
+ Rake::TestTask.new(:test) do |t|
7
+ t.libs << 'test'
8
+ t.libs << 'lib'
9
+ t.test_files = FileList['test/**/*_test.rb']
10
+ end
11
+
12
+ task default: :test
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require 'bundler/setup'
5
+ require 'diffcrypt'
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require 'irb'
15
+ IRB.start(__FILE__)
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'lib/diffcrypt/version'
4
+
5
+ Gem::Specification.new do |spec|
6
+ spec.name = 'diffcrypt'
7
+ spec.version = Diffcrypt::VERSION
8
+ spec.authors = ['Marc Qualie']
9
+ spec.email = ['marc@marcqualie.com']
10
+
11
+ spec.summary = 'Diffable encrypted configuration files'
12
+ spec.description = 'Diffable encrypted configuration files that can be safely committed into a git repository'
13
+ spec.homepage = 'https://github.com/marcqualie/diffcrypt'
14
+ spec.license = 'MIT'
15
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
16
+
17
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
18
+
19
+ spec.metadata['homepage_uri'] = spec.homepage
20
+ spec.metadata['source_code_uri'] = 'https://github.com/marcqualie/diffcrypt'
21
+ # spec.metadata['changelog_uri'] = "TODO: Put your gem's CHANGELOG.md URL here."
22
+
23
+ # Specify which files should be added to the gem when it is released.
24
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
25
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
26
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
27
+ end
28
+ spec.bindir = 'exe'
29
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
30
+ spec.require_paths = ['lib']
31
+
32
+ spec.add_runtime_dependency 'activesupport', '~> 6.0.0'
33
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'diffcrypt/encryptor'
4
+ require 'diffcrypt/version'
5
+
6
+ module Diffcrypt
7
+ class Error < StandardError; end
8
+
9
+ class MissingContentError < RuntimeError
10
+ def initialize(content_path)
11
+ super "Missing encrypted content file in #{content_path}."
12
+ end
13
+ end
14
+
15
+ class MissingKeyError < RuntimeError
16
+ def initialize(key_path:, env_key:)
17
+ super \
18
+ 'Missing encryption key to decrypt file with. ' \
19
+ "Ask your team for your master key and write it to #{key_path} or put it in the ENV['#{env_key}']."
20
+ end
21
+ end
22
+ end
@@ -0,0 +1,86 @@
1
+ # rubocop:disable Layout/LineLength
2
+ # frozen_string_literal: true
3
+
4
+ require 'pathname'
5
+ require 'tmpdir'
6
+ require 'securerandom'
7
+ require 'yaml'
8
+
9
+ require 'active_support/message_encryptor'
10
+
11
+ module Diffcrypt
12
+ class Encryptor
13
+ CIPHER = 'aes-128-gcm'
14
+
15
+ def self.generate_key
16
+ SecureRandom.hex(ActiveSupport::MessageEncryptor.key_len(CIPHER))
17
+ end
18
+
19
+ def initialize(key)
20
+ @key = key
21
+ @encryptor ||= ActiveSupport::MessageEncryptor.new([key].pack('H*'), cipher: CIPHER)
22
+ end
23
+
24
+ # @param [String] contents The raw YAML string to be encrypted
25
+ def decrypt(contents)
26
+ yaml = YAML.safe_load contents
27
+ decrypted = decrypt_hash yaml
28
+ YAML.dump decrypted
29
+ end
30
+
31
+ # @param [Hash] data
32
+ # @return [Hash]
33
+ def decrypt_hash(data)
34
+ data.each do |key, value|
35
+ data[key] = if value.is_a?(Hash) || value.is_a?(Array)
36
+ decrypt_hash(value)
37
+ else
38
+ decrypt_string value
39
+ end
40
+ end
41
+ data
42
+ end
43
+
44
+ # @param [String] contents The raw YAML string to be encrypted
45
+ # @param [String, nil] original_encrypted_contents The original (encrypted) content to determine which keys have changed
46
+ def encrypt(contents, original_encrypted_contents = nil)
47
+ yaml = YAML.safe_load contents
48
+ original_yaml = original_encrypted_contents ? YAML.safe_load(original_encrypted_contents) : nil
49
+ encrypted = encrypt_values yaml, original_yaml
50
+ YAML.dump encrypted
51
+ end
52
+
53
+ # @param [String] value Plain text string that needs encrypting
54
+ # @return [String]
55
+ def encrypt_string(value)
56
+ @encryptor.encrypt_and_sign value
57
+ end
58
+
59
+ # TODO: Fix the complexity of this method
60
+ # rubocop:disable Metrics/PerceivedComplexity, Metrics/MethodLength, Metrics/CyclomaticComplexity
61
+ # @param [Hash] keys
62
+ # @return [Hash]
63
+ def encrypt_values(data, original_data = nil)
64
+ data.each do |key, value|
65
+ original_encrypted_value = original_data ? original_data[key] : nil
66
+ data[key] = if value.is_a?(Hash) || value.is_a?(Array)
67
+ encrypt_values(value, original_encrypted_value)
68
+ else
69
+ original_decrypted_value = original_data ? decrypt_string(original_encrypted_value) : nil
70
+ key_changed = original_decrypted_value.nil? || original_decrypted_value != value
71
+ key_changed ? encrypt_string(value) : original_encrypted_value
72
+ end
73
+ end
74
+ data
75
+ end
76
+ # rubocop:enable Metrics/PerceivedComplexity, Metrics/MethodLength, Metrics/CyclomaticComplexity
77
+
78
+ # @param [String] value The encrypted value that needs decrypting
79
+ # @return [String]
80
+ def decrypt_string(value)
81
+ @encryptor.decrypt_and_verify value
82
+ end
83
+ end
84
+ end
85
+
86
+ # rubocop:enable Layout/LineLength
@@ -0,0 +1,126 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'pathname'
4
+ require 'tmpdir'
5
+
6
+ require 'active_support/ordered_options'
7
+ require 'active_support/core_ext/hash'
8
+ require 'active_support/core_ext/module/delegation'
9
+ require 'active_support/core_ext/object/inclusion'
10
+
11
+ module Diffcrypt
12
+ module Rails
13
+ class EncryptedConfiguration
14
+ attr_reader :content_path
15
+ attr_reader :key_path
16
+ attr_reader :env_key
17
+ attr_reader :raise_if_missing_key
18
+
19
+ delegate :[], :fetch, to: :config
20
+ delegate_missing_to :options
21
+
22
+ def initialize(config_path:, key_path:, env_key:, raise_if_missing_key:)
23
+ @content_path = Pathname.new(File.absolute_path(config_path)).yield_self do |path|
24
+ path.symlink? ? path.realpath : path
25
+ end
26
+ @key_path = Pathname.new(key_path)
27
+ @env_key = env_key
28
+ @raise_if_missing_key = raise_if_missing_key
29
+ @active_support_encryptor = ActiveSupport::MessageEncryptor.new([key].pack('H*'), cipher: Encryptor::CIPHER)
30
+ end
31
+
32
+ # Allow a config to be started without a file present
33
+ # @return [String] Returns decryped content or a blank string
34
+ def read
35
+ raise MissingContentError, content_path unless !key.nil? && content_path.exist?
36
+
37
+ decrypt content_path.binread
38
+ rescue MissingContentError
39
+ ''
40
+ end
41
+
42
+ def write(contents, original_encrypted_contents = nil)
43
+ deserialize(contents)
44
+
45
+ IO.binwrite "#{content_path}.tmp", encrypt(contents, original_encrypted_contents)
46
+ FileUtils.mv "#{content_path}.tmp", content_path
47
+ end
48
+
49
+ def config
50
+ @config ||= deserialize(read).deep_symbolize_keys
51
+ end
52
+
53
+ # @raise [MissingKeyError] Will raise if key is not set
54
+ # @return [String]
55
+ def key
56
+ read_env_key || read_key_file || handle_missing_key
57
+ end
58
+
59
+ def change(&block)
60
+ writing read, &block
61
+ end
62
+
63
+ protected
64
+
65
+ # rubocop:disable Metrics/AbcSize
66
+ def writing(contents)
67
+ tmp_file = "#{Process.pid}.#{content_path.basename.to_s.chomp('.enc')}"
68
+ tmp_path = Pathname.new File.join(Dir.tmpdir, tmp_file)
69
+ tmp_path.binwrite contents
70
+
71
+ yield tmp_path
72
+
73
+ updated_contents = tmp_path.binread
74
+
75
+ write(updated_contents, content_path.binread)
76
+ ensure
77
+ FileUtils.rm(tmp_path) if tmp_path&.exist?
78
+ end
79
+ # rubocop:enable Metrics/AbcSize
80
+
81
+ # @param [String] contents The new content to be encrypted
82
+ # @param [String] diff_against The original (encrypted) content to determine which keys have changed
83
+ # @return [String] Encrypted content to commit
84
+ def encrypt(contents, original_encrypted_contents = nil)
85
+ encryptor.encrypt contents, original_encrypted_contents
86
+ end
87
+
88
+ # @param [String] contents
89
+ # @return [String]
90
+ def decrypt(contents)
91
+ if contents.index('---').nil?
92
+ @active_support_encryptor.decrypt_and_verify contents
93
+ else
94
+ encryptor.decrypt contents
95
+ end
96
+ end
97
+
98
+ # @return [Encryptor]
99
+ def encryptor
100
+ @encryptor ||= Encryptor.new key
101
+ end
102
+
103
+ def read_env_key
104
+ ENV[env_key]
105
+ end
106
+
107
+ def read_key_file
108
+ key_path.binread.strip if key_path.exist?
109
+ end
110
+
111
+ # @raise [MissingKeyError]
112
+ # @return [void]
113
+ def handle_missing_key
114
+ raise MissingKeyError.new(key_path: key_path, env_key: env_key) if raise_if_missing_key
115
+ end
116
+
117
+ def options
118
+ @options ||= ActiveSupport::InheritableOptions.new(config)
119
+ end
120
+
121
+ def deserialize(config)
122
+ YAML.safe_load(config).presence || {}
123
+ end
124
+ end
125
+ end
126
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Diffcrypt
4
+ VERSION = '0.1.0'
5
+ end
metadata ADDED
@@ -0,0 +1,74 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: diffcrypt
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Marc Qualie
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-06-28 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activesupport
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: 6.0.0
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: 6.0.0
27
+ description: Diffable encrypted configuration files that can be safely committed into
28
+ a git repository
29
+ email:
30
+ - marc@marcqualie.com
31
+ executables: []
32
+ extensions: []
33
+ extra_rdoc_files: []
34
+ files:
35
+ - ".gitignore"
36
+ - ".rubocop.yml"
37
+ - ".travis.yml"
38
+ - Gemfile
39
+ - LICENSE.txt
40
+ - README.md
41
+ - Rakefile
42
+ - bin/console
43
+ - bin/setup
44
+ - diffcrypt.gemspec
45
+ - lib/diffcrypt.rb
46
+ - lib/diffcrypt/encryptor.rb
47
+ - lib/diffcrypt/rails/encrypted_configuration.rb
48
+ - lib/diffcrypt/version.rb
49
+ homepage: https://github.com/marcqualie/diffcrypt
50
+ licenses:
51
+ - MIT
52
+ metadata:
53
+ homepage_uri: https://github.com/marcqualie/diffcrypt
54
+ source_code_uri: https://github.com/marcqualie/diffcrypt
55
+ post_install_message:
56
+ rdoc_options: []
57
+ require_paths:
58
+ - lib
59
+ required_ruby_version: !ruby/object:Gem::Requirement
60
+ requirements:
61
+ - - ">="
62
+ - !ruby/object:Gem::Version
63
+ version: 2.3.0
64
+ required_rubygems_version: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ requirements: []
70
+ rubygems_version: 3.0.3
71
+ signing_key:
72
+ specification_version: 4
73
+ summary: Diffable encrypted configuration files
74
+ test_files: []