summaryrefslogtreecommitdiff
path: root/lib/tfa/secure_proxy.rb
blob: 8f4fffefc56bd3c6990270329ec033fd99b33941 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
module TFA
  class SecureProxy
    def initialize(original, passphrase_request)
      @original = original
      @passphrase_request = passphrase_request
    end

    def encrypt!(algorithm = "AES-256-CBC")
      cipher = OpenSSL::Cipher.new(algorithm)
      cipher.encrypt
      cipher.key = digest
      cipher.iv = iv = cipher.random_iv
      plain_text = IO.read(@original.path)
      json = JSON.generate(
        algorithm: algorithm,
        iv: Base64.encode64(iv),
        cipher_text: Base64.encode64(cipher.update(plain_text) + cipher.final),
      )
      IO.write(@original.path, json)
    end

    def decrypt!
      data = JSON.parse(IO.read(@original.path), symbolize_names: true)
      decipher = OpenSSL::Cipher.new(data[:algorithm])
      decipher.decrypt
      decipher.key = digest
      decipher.iv = Base64.decode64(data[:iv])
      IO.write(@original.path, decipher.update(Base64.decode64(data[:cipher_text])) + decipher.final)
    end

    def encrypted?
      return false unless File.exist?(@original.path)
      JSON.parse(IO.read(@original.path))
      true
    rescue JSON::ParserError
      false
    end

    private

    def method_missing(name, *args, &block)
      super unless @original.respond_to?(name)

      was_encrypted = encrypted?
      if was_encrypted
        encrypted_content = IO.read(@original.path)
        decrypt!
      end
      original_sha256 = Digest::SHA256.file(@original.path)
      result = @original.public_send(name, *args, &block)
      if was_encrypted
        new_sha256 = Digest::SHA256.file(@original.path)

        if original_sha256 == new_sha256
          IO.write(@original.path, encrypted_content)
        else
          encrypt!
        end
      end
      result
    end

    def digest
      @digest ||= Digest::SHA256.digest(@passphrase_request.call)
    end
  end
end