Class: Familia::EncryptedFieldType

Inherits:
FieldType
  • Object
show all
Defined in:
lib/familia/features/encrypted_fields/encrypted_field_type.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, aad_fields: [], **options) ⇒ EncryptedFieldType

Returns a new instance of EncryptedFieldType.



10
11
12
13
14
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 10

def initialize(name, aad_fields: [], **options)
  # Encrypted fields are not loggable by default for security
  super(name, **options.merge(on_conflict: :raise, loggable: false))
  @aad_fields = Array(aad_fields).freeze
end

Instance Attribute Details

#aad_fieldsObject (readonly)

Returns the value of attribute aad_fields.



8
9
10
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 8

def aad_fields
  @aad_fields
end

Instance Method Details

#categoryObject



137
138
139
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 137

def category
  :encrypted
end

#decrypt_value(record, encrypted) ⇒ Object

Decrypt a value for the given record



126
127
128
129
130
131
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 126

def decrypt_value(record, encrypted)
  context = build_context(record)
  additional_data = build_aad(record)

  Familia::Encryption.decrypt(encrypted, context: context, additional_data: additional_data)
end

#define_fast_writer(klass) ⇒ Object



89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 89

def define_fast_writer(klass)
  # Encrypted fields override base fast writer for security
  return unless @fast_method_name&.to_s&.end_with?('!')

  field_name = @name
  method_name = @method_name
  fast_method_name = @fast_method_name
  self

  handle_method_conflict(klass, fast_method_name) do
    klass.define_method fast_method_name do |val|
      raise ArgumentError, "#{fast_method_name} requires a value" if val.nil?

      # UnsortedSet via the setter method to get proper ConcealedString wrapping
      send(:"#{method_name}=", val) if method_name

      # Get the ConcealedString and extract encrypted data for storage
      concealed = instance_variable_get(:"@#{field_name}")
      encrypted_data = concealed&.encrypted_value

      return false if encrypted_data.nil?

      ret = hset(field_name, encrypted_data)
      ret.zero? || ret.positive?
    end
  end
end

#define_getter(klass) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 47

def define_getter(klass)
  field_name = @name
  method_name = @method_name
  field_type = self

  handle_method_conflict(klass, method_name) do
    klass.define_method method_name do
      # Return ConcealedString directly - no auto-decryption!
      # Caller must use .reveal { } for plaintext access
      concealed = instance_variable_get(:"@#{field_name}")

      # Return nil directly if that's what was set
      return nil if concealed.nil?

      # If we have a raw string (from direct instance variable manipulation),
      # wrap it in ConcealedString which will trigger validation
      if concealed.is_a?(::String) && !concealed.is_a?(ConcealedString)
        # This happens when someone directly sets the instance variable
        # (e.g., during tampering tests). Wrapping in ConcealedString
        # will trigger validate_decryptable! and catch invalid algorithms
        begin
          concealed = ConcealedString.new(concealed, self, field_type)
          instance_variable_set(:"@#{field_name}", concealed)
        rescue Familia::EncryptionError => e
          # Increment derivation counter for failed validation attempts (similar to decrypt failures)
          Familia::Encryption.derivation_count.increment
          raise e
        end
      end

      # Context validation: detect cross-context attacks
      # Only validate if we have a proper ConcealedString instance
      if concealed.is_a?(ConcealedString) && !concealed.belongs_to_context?(self, field_name)
        raise Familia::EncryptionError,
              "Context isolation violation: encrypted field '#{field_name}' does not belong to #{self.class.name}:#{identifier}"
      end

      concealed
    end
  end
end

#define_setter(klass) ⇒ Object



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
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 16

def define_setter(klass)
  field_name = @name
  method_name = @method_name
  field_type = self

  handle_method_conflict(klass, :"#{method_name}=") do
    klass.define_method :"#{method_name}=" do |value|
      if value.nil?
        instance_variable_set(:"@#{field_name}", nil)
      elsif value.is_a?(::String) && value.empty?
        # Handle empty strings - treat as nil for encrypted fields
        instance_variable_set(:"@#{field_name}", nil)
      elsif value.is_a?(ConcealedString)
        # Already concealed, store as-is
        instance_variable_set(:"@#{field_name}", value)
      elsif field_type.encrypted_json?(value)
        # Already encrypted (JSON string or Hash from database) - wrap in ConcealedString without re-encrypting
        # Convert Hash back to JSON string if needed (v2.0 deserialization returns Hash)
        encrypted_string = value.is_a?(Hash) ? Familia::JsonSerializer.dump(value) : value
        concealed = ConcealedString.new(encrypted_string, self, field_type)
        instance_variable_set(:"@#{field_name}", concealed)
      else
        # Encrypt plaintext and wrap in ConcealedString
        encrypted = field_type.encrypt_value(self, value)
        concealed = ConcealedString.new(encrypted, self, field_type)
        instance_variable_set(:"@#{field_name}", concealed)
      end
    end
  end
end

#encrypt_value(record, value) ⇒ Object

Encrypt a value for the given record



118
119
120
121
122
123
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 118

def encrypt_value(record, value)
  context = build_context(record)
  additional_data = build_aad(record)

  Familia::Encryption.encrypt(value, context: context, additional_data: additional_data)
end

#encrypted_json?(data) ⇒ Boolean

Check if a string looks like encrypted JSON data

Returns:

  • (Boolean)


142
143
144
145
146
147
148
149
150
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 142

def encrypted_json?(data)
  # Support both JSON strings (legacy) and Hashes (v2.0 deserialization)
  if data.is_a?(Hash)
    required_keys = %w[algorithm nonce ciphertext auth_tag key_version]
    required_keys.all? { |key| data.key?(key) || data.key?(key.to_sym) }
  else
    Familia::Encryption::EncryptedData.valid?(data)
  end
end

#persistent?Boolean

Returns:

  • (Boolean)


133
134
135
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 133

def persistent?
  true
end