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: [], key_material: nil, algorithm: nil, **options) ⇒ EncryptedFieldType

Returns a new instance of EncryptedFieldType.



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 14

def initialize(name, aad_fields: [], key_material: nil, algorithm: nil, **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
  @key_material = key_material # Proc returning entropy string
  # Optional per-field write-algorithm pin. When nil, writes use the
  # registry's default provider (highest priority available). When set to a
  # registered algorithm identifier (e.g. 'aes-256-gcm', 'xchacha20poly1305')
  # every write from this field is encrypted with that algorithm regardless
  # of the default. Reads are unaffected -- the provider is always resolved
  # from the stored envelope's own algorithm field -- so pinning changes
  # only the write side and never breaks ciphertext already at rest.
  # Validated lazily: an unregistered algorithm raises Familia::EncryptionError
  # on the first write, not at field declaration.
  @algorithm = algorithm
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

#algorithmObject (readonly)

Returns the value of attribute algorithm.



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

def algorithm
  @algorithm
end

#key_materialObject (readonly)

Returns the value of attribute key_material.



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

def key_material
  @key_material
end

Instance Method Details

#categoryObject



194
195
196
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 194

def category
  :encrypted
end

#conceal_stored(record, stored_envelope) ⇒ ConcealedString?

Wrap a value rehydrated from storage for the given record.

The payload is normally the parsed envelope (deserialize_value returns a Hash), which is re-serialized to its canonical JSON string and wrapped without re-encrypting. A payload that is not an envelope at all is a legacy plaintext value already at rest in this slot; it is encrypted in memory so the next save protects it, as before.

Parameters:

Returns:



225
226
227
228
229
230
231
232
233
234
235
236
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 225

def conceal_stored(record, stored_envelope)
  stored = stored_envelope.payload
  return nil if stored.nil? || (stored.is_a?(::String) && stored.empty?)

  encrypted = if encrypted_json?(stored)
    stored.is_a?(Hash) ? Familia::JsonSerializer.dump(stored) : stored
  else
    encrypt_value(record, stored)
  end

  ConcealedString.new(encrypted, record, self)
end

#decrypt_value(record, encrypted) ⇒ Object



172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 172

def decrypt_value(record, encrypted)
  envelope = Familia::Encryption::EncryptedData.from_json(encrypted)
  context = build_context(record)

  if envelope.envelope_version && envelope.envelope_version >= 2
    # v2 envelopes are self-describing: a nil stored_aad_fields means the
    # value was encrypted with no AAD fields. Fall back to [] (not the
    # current class-level @aad_fields) so that adding aad_fields to a model
    # later cannot break decryption of already-stored v2 envelopes.
    additional_data = build_aad(record, fields: envelope.stored_aad_fields || [])
    context = context_with_entropy(context, build_key_material(record)) if envelope.has_key_material?
  else
    additional_data = build_aad(record)
  end

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

#define_fast_writer(klass) ⇒ Object



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

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?

      # Use 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)
      Familia.success?(ret)
    end
  end
end

#define_getter(klass) ⇒ Object



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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 68

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}' accessed from " \
              "#{self.class.name}:#{field_name}:#{identifier} but was encrypted for " \
              "#{concealed.context_description}"
      end

      concealed
    end
  end
end

#define_setter(klass) ⇒ Object



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

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 value.is_a?(Familia::Encryption::StoredEnvelope)
        # Rehydrated from storage (load, find_by_id, refresh!). Provenance,
        # not shape, earns the verbatim path: #deserialize is the only place
        # that wraps values in StoredEnvelope, so nothing a caller assigns
        # reaches this branch by looking like an envelope (#405).
        instance_variable_set(:"@#{field_name}", field_type.conceal_stored(self, value))
      else
        # Plaintext -- including anything that merely looks like an
        # envelope. Encrypt 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

#deserialize(value, _record = nil) ⇒ Familia::Encryption::StoredEnvelope?

Storage hook (FieldType#deserialize): mark the value as having come from storage so the setter can take it verbatim. Horreum calls this only while hydrating an object from its hash, never for values assigned by callers, which is what makes the marker a provenance signal rather than a shape check (#405).

Parameters:

  • value (Hash, String, nil)

    The decoded stored value

Returns:



207
208
209
210
211
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 207

def deserialize(value, _record = nil)
  return nil if value.nil?

  Familia::Encryption::StoredEnvelope.new(payload: value)
end

#encrypt_value(record, value) ⇒ Object

Encrypt plaintext using a context bound to a stable record identifier.

Raises:



143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 143

def encrypt_value(record, value)
  identifier = record.identifier
  if identifier.nil? || identifier.to_s.empty?
    raise Familia::NoIdentifier,
          "Cannot encrypt '#{@name}' for #{record.class} without a record identifier"
  end

  context = build_context(record, identifier: identifier)
  additional_data = build_aad(record, identifier: identifier)
  entropy = build_key_material(record)
  context = context_with_entropy(context, entropy)

  # A per-field @algorithm pins the write algorithm via encrypt_with;
  # otherwise the default provider (registry priority) is used. Either path
  # records the chosen algorithm in the envelope, so the read path stays
  # self-describing and unpinning/repinning never affects existing data.
  result = if @algorithm
    Familia::Encryption.encrypt_with(@algorithm, value, context: context, additional_data: additional_data)
  else
    Familia::Encryption.encrypt(value, context: context, additional_data: additional_data)
  end

  Familia::Encryption::EncryptedData.from_json(result).(
    envelope_version: 2,
    aad_fields: @aad_fields.empty? ? nil : @aad_fields.map(&:to_s),
    key_material_fields: entropy ? ['key_material'] : nil
  ).to_json
end

#encrypted_json?(data) ⇒ Boolean

Shape check: does this value parse as an encryption envelope? Used to validate what came back from storage. It is deliberately NOT how the setter decides whether to encrypt -- that is decided by provenance via StoredEnvelope (#405), because any caller can produce this shape.

Returns:

  • (Boolean)


242
243
244
245
246
247
248
249
250
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 242

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)


190
191
192
# File 'lib/familia/features/encrypted_fields/encrypted_field_type.rb', line 190

def persistent?
  true
end