Module: Familia::Encryption

Defined in:
lib/familia/encryption.rb,
lib/familia/encryption/manager.rb,
lib/familia/encryption/provider.rb,
lib/familia/encryption/registry.rb,
lib/familia/encryption/request_cache.rb,
lib/familia/encryption/strict_base64.rb,
lib/familia/encryption/encrypted_data.rb,
lib/familia/encryption/stored_envelope.rb,
lib/familia/encryption/providers/aes_gcm_provider.rb,
lib/familia/encryption/providers/blake2b_personalization.rb,
lib/familia/encryption/providers/xchacha20_poly1305_provider.rb,
lib/familia/encryption/providers/secure_xchacha20_poly1305_provider.rb

Defined Under Namespace

Modules: Providers, StrictBase64 Classes: EncryptedData, Manager, Provider, Registry, StoredEnvelope

Constant Summary collapse

ENVELOPE_ENCODINGS =

Encoding names an envelope may carry. The write path records plaintext.encoding.name, so every legitimate value is a canonical Ruby encoding name (aliases are accepted too). The special names "locale", "external", "internal" and "filesystem" are excluded: they resolve differently per host, are never written, and would let a tampered envelope pick the encoding of whatever machine reads it.

The field is not covered by the AEAD tag, so this allowlist is what stands between a rewritten encoding and force_encoding raising ArgumentError/TypeError inside the decrypt path (#408).

(Encoding.name_list - %w[locale external internal filesystem]).freeze

Class Method Summary collapse

Class Method Details

.benchmark(iterations: 1000) ⇒ Object

Benchmark available providers

Times each provider with the monotonic clock, as Benchmark.realtime does, so the benchmark library is not needed.



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
# File 'lib/familia/encryption.rb', line 116

def benchmark(iterations: 1000)
  test_data = 'x' * 1024 # 1KB test
  context = 'benchmark:test'

  results = {}
  Registry.providers.each do |algo, provider_class|
    next unless provider_class.available?

    mgr = Manager.new(algorithm: algo)
    started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    iterations.times do
      encrypted = mgr.encrypt(test_data, context: context)
      mgr.decrypt(encrypted, context: context)
    end
    time = Process.clock_gettime(Process::CLOCK_MONOTONIC) - started

    results[algo] = {
      time: time,
      ops_per_sec: (iterations * 2 / time).round,
      priority: provider_class.priority,
    }
  end

  results
end

.clear_request_cache! ⇒ Object

Clear all cached keys and disable caching



48
49
50
51
52
53
54
55
# File 'lib/familia/encryption/request_cache.rb', line 48

def clear_request_cache!
  if (cache = Fiber[:familia_request_cache])
    cache.each_value { |key| secure_wipe(key) }
    cache.clear
  end
  Fiber[:familia_request_cache_enabled] = false
  Fiber[:familia_request_cache] = nil
end

.decrypt(encrypted_json, context:, additional_data: nil) ⇒ Object

Quick decryption (auto-detects algorithm from data)



65
66
67
# File 'lib/familia/encryption.rb', line 65

def decrypt(encrypted_json, context:, additional_data: nil)
  manager.decrypt(encrypted_json, context: context, additional_data: additional_data)
end

.derivation_count ⇒ Object

Derivation counter for monitoring no-caching behavior



79
80
81
# File 'lib/familia/encryption.rb', line 79

def derivation_count
  @derivation_count ||= Concurrent::AtomicFixnum.new(0)
end

.encrypt(plaintext, context:, additional_data: nil) ⇒ Object

Quick encryption with auto-selected best provider



60
61
62
# File 'lib/familia/encryption.rb', line 60

def encrypt(plaintext, context:, additional_data: nil)
  manager.encrypt(plaintext, context: context, additional_data: additional_data)
end

.encrypt_with(algorithm, plaintext, context:, additional_data: nil) ⇒ Object

Encrypt with specific algorithm



70
71
72
73
74
75
76
# File 'lib/familia/encryption.rb', line 70

def encrypt_with(algorithm, plaintext, context:, additional_data: nil)
  manager(algorithm: algorithm).encrypt(
    plaintext,
    context: context,
    additional_data: additional_data
  )
end

.hardware_acceleration? ⇒ Boolean

Check if we're using hardware acceleration

Returns:

  • (Boolean)


107
108
109
110
# File 'lib/familia/encryption.rb', line 107

def hardware_acceleration?
  provider = Registry.default_provider
  provider && provider.class.name.include?('Hardware')
end

.manager(algorithm: nil) ⇒ Object

Get or create a manager with specific algorithm

Thread-safe lazy initialization using Concurrent::Map to ensure only a single Manager instance is created per algorithm even under concurrent encryption/decryption requests.



54
55
56
57
# File 'lib/familia/encryption.rb', line 54

def manager(algorithm: nil)
  @managers ||= Concurrent::Map.new
  @managers.fetch_or_store(algorithm) { Manager.new(algorithm: algorithm) }
end

.reset_derivation_count! ⇒ Object



83
84
85
# File 'lib/familia/encryption.rb', line 83

def reset_derivation_count!
  derivation_count.value = 0
end

.secure_wipe(key) ⇒ Object

Clear key from memory (no security guarantees in Ruby)



88
89
90
# File 'lib/familia/encryption.rb', line 88

def secure_wipe(key)
  key&.clear
end

.status ⇒ Object

Get info about current encryption setup



93
94
95
96
97
98
99
100
101
102
103
104
# File 'lib/familia/encryption.rb', line 93

def status
  Registry.setup! if Registry.providers.empty?

  {
    default_algorithm: Registry.default_provider&.algorithm,
    available_algorithms: Registry.available_algorithms,
    preferred_available: Registry.default_provider&.class&.name,
    using_hardware: hardware_acceleration?,
    key_versions: encryption_keys.keys,
    current_version: current_key_version,
  }
end

.validate_configuration! ⇒ Object

Raises:



142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/familia/encryption.rb', line 142

def validate_configuration!
  raise EncryptionError, 'No encryption keys configured' if encryption_keys.empty?
  raise EncryptionError, 'No current key version set' unless current_key_version

  current_key = encryption_keys[current_key_version]
  raise EncryptionError, "Current key version not found: #{current_key_version}" unless current_key

  begin
    StrictBase64.decode(current_key)
  rescue ArgumentError
    raise EncryptionError, 'Current encryption key is not valid Base64'
  end

  Registry.setup!
  raise EncryptionError, 'No encryption providers available' unless Registry.default_provider
end

.with_request_cache ⇒ Object

Enable request-scoped caching (opt-in for performance)



36
37
38
39
40
41
42
43
44
45
# File 'lib/familia/encryption/request_cache.rb', line 36

def with_request_cache
  # Wipe any cache a reused fiber may still be carrying before installing a
  # fresh one, so this block can never observe a previous request's keys.
  clear_request_cache!
  Fiber[:familia_request_cache_enabled] = true
  Fiber[:familia_request_cache] = {}
  yield
ensure
  clear_request_cache!
end