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.



14
15
16
17
18
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 14

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.



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

def aad_fields
  @aad_fields
end

Instance Method Details

#categoryObject



164
165
166
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 164

def category
  :encrypted
end

#decrypt_value(record, encrypted) ⇒ Object

Decrypt a value for the given record



153
154
155
156
157
158
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 153

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



98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 98

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?

      # Prevent fast writer within transaction/pipeline - the return value
      # would be Redis::Future which doesn't support zero?/positive? checks
      if Fiber[:familia_transaction]
        Familia.trace :FAST_WRITER_BLOCKED, dbkey,
                     "#{fast_method_name} blocked by active transaction context"
        raise Familia::OperationModeError, <<~ERROR_MESSAGE.chomp
          Cannot call fast writer #{fast_method_name} within a transaction.
          Use multi_field_update or commit_fields instead.
        ERROR_MESSAGE
      elsif Fiber[:familia_pipeline]
        Familia.trace :FAST_WRITER_BLOCKED, dbkey,
                     "#{fast_method_name} blocked by active pipeline context"
        raise Familia::OperationModeError, <<~ERROR_MESSAGE.chomp
          Cannot call fast writer #{fast_method_name} within a pipeline.
          Restructure to call fast writers outside the pipeline.
        ERROR_MESSAGE
      end

      # 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



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
88
89
90
91
92
93
94
95
96
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 56

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



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

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|
      old_value = instance_variable_get(:"@#{field_name}")

      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

      # Track the change for dirty-tracking (only for Horreum instances)
      mark_dirty!(field_name, old_value) if respond_to?(:mark_dirty!)
    end
  end
end

#encrypt_value(record, value) ⇒ Object

Encrypt a value for the given record



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

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)


169
170
171
172
173
174
175
176
177
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 169

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)


160
161
162
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 160

def persistent?
  true
end