Class: Familia::EncryptedFieldType

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

Instance Attribute Summary collapse

Attributes inherited from FieldType

#fast_method_name, #loggable, #method_name, #name, #on_conflict, #options

Instance Method Summary collapse

Methods inherited from FieldType

#deserialize, #generated_methods, #inspect, #install, #serialize, #transient?

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



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

def category
  :encrypted
end

#decrypt_value(record, encrypted) ⇒ Object

Decrypt a value for the given record



123
124
125
126
127
128
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 123

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



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

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
  field_type = 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?

      # Set 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



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

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.kind_of?(::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}:#{self.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
# 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 from database - wrap in ConcealedString without re-encrypting
        concealed = ConcealedString.new(value, 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



115
116
117
118
119
120
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 115

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)


139
140
141
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 139

def encrypted_json?(data)
  Familia::Encryption::EncryptedData.valid?(data)
end

#persistent?Boolean

Returns:

  • (Boolean)


130
131
132
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 130

def persistent?
  true
end